Annotation of imach/src/imach.c, revision 1.172
1.172 ! brouard 1: /* $Id: imach.c,v 1.171 2014/12/23 13:26:59 brouard Exp $
1.126 brouard 2: $State: Exp $
1.163 brouard 3: $Log: imach.c,v $
1.172 ! brouard 4: Revision 1.171 2014/12/23 13:26:59 brouard
! 5: Summary: Back from Visual C
! 6:
! 7: Still problem with utsname.h on Windows
! 8:
1.171 brouard 9: Revision 1.170 2014/12/23 11:17:12 brouard
10: Summary: Cleaning some \%% back to %%
11:
12: The escape was mandatory for a specific compiler (which one?), but too many warnings.
13:
1.170 brouard 14: Revision 1.169 2014/12/22 23:08:31 brouard
15: Summary: 0.98p
16:
17: Outputs some informations on compiler used, OS etc. Testing on different platforms.
18:
1.169 brouard 19: Revision 1.168 2014/12/22 15:17:42 brouard
1.170 brouard 20: Summary: update
1.169 brouard 21:
1.168 brouard 22: Revision 1.167 2014/12/22 13:50:56 brouard
23: Summary: Testing uname and compiler version and if compiled 32 or 64
24:
25: Testing on Linux 64
26:
1.167 brouard 27: Revision 1.166 2014/12/22 11:40:47 brouard
28: *** empty log message ***
29:
1.166 brouard 30: Revision 1.165 2014/12/16 11:20:36 brouard
31: Summary: After compiling on Visual C
32:
33: * imach.c (Module): Merging 1.61 to 1.162
34:
1.165 brouard 35: Revision 1.164 2014/12/16 10:52:11 brouard
36: Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
37:
38: * imach.c (Module): Merging 1.61 to 1.162
39:
1.164 brouard 40: Revision 1.163 2014/12/16 10:30:11 brouard
41: * imach.c (Module): Merging 1.61 to 1.162
42:
1.163 brouard 43: Revision 1.162 2014/09/25 11:43:39 brouard
44: Summary: temporary backup 0.99!
45:
1.162 brouard 46: Revision 1.1 2014/09/16 11:06:58 brouard
47: Summary: With some code (wrong) for nlopt
48:
49: Author:
50:
51: Revision 1.161 2014/09/15 20:41:41 brouard
52: Summary: Problem with macro SQR on Intel compiler
53:
1.161 brouard 54: Revision 1.160 2014/09/02 09:24:05 brouard
55: *** empty log message ***
56:
1.160 brouard 57: Revision 1.159 2014/09/01 10:34:10 brouard
58: Summary: WIN32
59: Author: Brouard
60:
1.159 brouard 61: Revision 1.158 2014/08/27 17:11:51 brouard
62: *** empty log message ***
63:
1.158 brouard 64: Revision 1.157 2014/08/27 16:26:55 brouard
65: Summary: Preparing windows Visual studio version
66: Author: Brouard
67:
68: In order to compile on Visual studio, time.h is now correct and time_t
69: and tm struct should be used. difftime should be used but sometimes I
70: just make the differences in raw time format (time(&now).
71: Trying to suppress #ifdef LINUX
72: Add xdg-open for __linux in order to open default browser.
73:
1.157 brouard 74: Revision 1.156 2014/08/25 20:10:10 brouard
75: *** empty log message ***
76:
1.156 brouard 77: Revision 1.155 2014/08/25 18:32:34 brouard
78: Summary: New compile, minor changes
79: Author: Brouard
80:
1.155 brouard 81: Revision 1.154 2014/06/20 17:32:08 brouard
82: Summary: Outputs now all graphs of convergence to period prevalence
83:
1.154 brouard 84: Revision 1.153 2014/06/20 16:45:46 brouard
85: Summary: If 3 live state, convergence to period prevalence on same graph
86: Author: Brouard
87:
1.153 brouard 88: Revision 1.152 2014/06/18 17:54:09 brouard
89: Summary: open browser, use gnuplot on same dir than imach if not found in the path
90:
1.152 brouard 91: Revision 1.151 2014/06/18 16:43:30 brouard
92: *** empty log message ***
93:
1.151 brouard 94: Revision 1.150 2014/06/18 16:42:35 brouard
95: Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
96: Author: brouard
97:
1.150 brouard 98: Revision 1.149 2014/06/18 15:51:14 brouard
99: Summary: Some fixes in parameter files errors
100: Author: Nicolas Brouard
101:
1.149 brouard 102: Revision 1.148 2014/06/17 17:38:48 brouard
103: Summary: Nothing new
104: Author: Brouard
105:
106: Just a new packaging for OS/X version 0.98nS
107:
1.148 brouard 108: Revision 1.147 2014/06/16 10:33:11 brouard
109: *** empty log message ***
110:
1.147 brouard 111: Revision 1.146 2014/06/16 10:20:28 brouard
112: Summary: Merge
113: Author: Brouard
114:
115: Merge, before building revised version.
116:
1.146 brouard 117: Revision 1.145 2014/06/10 21:23:15 brouard
118: Summary: Debugging with valgrind
119: Author: Nicolas Brouard
120:
121: Lot of changes in order to output the results with some covariates
122: After the Edimburgh REVES conference 2014, it seems mandatory to
123: improve the code.
124: No more memory valgrind error but a lot has to be done in order to
125: continue the work of splitting the code into subroutines.
126: Also, decodemodel has been improved. Tricode is still not
127: optimal. nbcode should be improved. Documentation has been added in
128: the source code.
129:
1.144 brouard 130: Revision 1.143 2014/01/26 09:45:38 brouard
131: Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
132:
133: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
134: (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
135:
1.143 brouard 136: Revision 1.142 2014/01/26 03:57:36 brouard
137: Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
138:
139: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
140:
1.142 brouard 141: Revision 1.141 2014/01/26 02:42:01 brouard
142: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
143:
1.141 brouard 144: Revision 1.140 2011/09/02 10:37:54 brouard
145: Summary: times.h is ok with mingw32 now.
146:
1.140 brouard 147: Revision 1.139 2010/06/14 07:50:17 brouard
148: After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
149: I remember having already fixed agemin agemax which are pointers now but not cvs saved.
150:
1.139 brouard 151: Revision 1.138 2010/04/30 18:19:40 brouard
152: *** empty log message ***
153:
1.138 brouard 154: Revision 1.137 2010/04/29 18:11:38 brouard
155: (Module): Checking covariates for more complex models
156: than V1+V2. A lot of change to be done. Unstable.
157:
1.137 brouard 158: Revision 1.136 2010/04/26 20:30:53 brouard
159: (Module): merging some libgsl code. Fixing computation
160: of likelione (using inter/intrapolation if mle = 0) in order to
161: get same likelihood as if mle=1.
162: Some cleaning of code and comments added.
163:
1.136 brouard 164: Revision 1.135 2009/10/29 15:33:14 brouard
165: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
166:
1.135 brouard 167: Revision 1.134 2009/10/29 13:18:53 brouard
168: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
169:
1.134 brouard 170: Revision 1.133 2009/07/06 10:21:25 brouard
171: just nforces
172:
1.133 brouard 173: Revision 1.132 2009/07/06 08:22:05 brouard
174: Many tings
175:
1.132 brouard 176: Revision 1.131 2009/06/20 16:22:47 brouard
177: Some dimensions resccaled
178:
1.131 brouard 179: Revision 1.130 2009/05/26 06:44:34 brouard
180: (Module): Max Covariate is now set to 20 instead of 8. A
181: lot of cleaning with variables initialized to 0. Trying to make
182: V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
183:
1.130 brouard 184: Revision 1.129 2007/08/31 13:49:27 lievre
185: Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
186:
1.129 lievre 187: Revision 1.128 2006/06/30 13:02:05 brouard
188: (Module): Clarifications on computing e.j
189:
1.128 brouard 190: Revision 1.127 2006/04/28 18:11:50 brouard
191: (Module): Yes the sum of survivors was wrong since
192: imach-114 because nhstepm was no more computed in the age
193: loop. Now we define nhstepma in the age loop.
194: (Module): In order to speed up (in case of numerous covariates) we
195: compute health expectancies (without variances) in a first step
196: and then all the health expectancies with variances or standard
197: deviation (needs data from the Hessian matrices) which slows the
198: computation.
199: In the future we should be able to stop the program is only health
200: expectancies and graph are needed without standard deviations.
201:
1.127 brouard 202: Revision 1.126 2006/04/28 17:23:28 brouard
203: (Module): Yes the sum of survivors was wrong since
204: imach-114 because nhstepm was no more computed in the age
205: loop. Now we define nhstepma in the age loop.
206: Version 0.98h
207:
1.126 brouard 208: Revision 1.125 2006/04/04 15:20:31 lievre
209: Errors in calculation of health expectancies. Age was not initialized.
210: Forecasting file added.
211:
212: Revision 1.124 2006/03/22 17:13:53 lievre
213: Parameters are printed with %lf instead of %f (more numbers after the comma).
214: The log-likelihood is printed in the log file
215:
216: Revision 1.123 2006/03/20 10:52:43 brouard
217: * imach.c (Module): <title> changed, corresponds to .htm file
218: name. <head> headers where missing.
219:
220: * imach.c (Module): Weights can have a decimal point as for
221: English (a comma might work with a correct LC_NUMERIC environment,
222: otherwise the weight is truncated).
223: Modification of warning when the covariates values are not 0 or
224: 1.
225: Version 0.98g
226:
227: Revision 1.122 2006/03/20 09:45:41 brouard
228: (Module): Weights can have a decimal point as for
229: English (a comma might work with a correct LC_NUMERIC environment,
230: otherwise the weight is truncated).
231: Modification of warning when the covariates values are not 0 or
232: 1.
233: Version 0.98g
234:
235: Revision 1.121 2006/03/16 17:45:01 lievre
236: * imach.c (Module): Comments concerning covariates added
237:
238: * imach.c (Module): refinements in the computation of lli if
239: status=-2 in order to have more reliable computation if stepm is
240: not 1 month. Version 0.98f
241:
242: Revision 1.120 2006/03/16 15:10:38 lievre
243: (Module): refinements in the computation of lli if
244: status=-2 in order to have more reliable computation if stepm is
245: not 1 month. Version 0.98f
246:
247: Revision 1.119 2006/03/15 17:42:26 brouard
248: (Module): Bug if status = -2, the loglikelihood was
249: computed as likelihood omitting the logarithm. Version O.98e
250:
251: Revision 1.118 2006/03/14 18:20:07 brouard
252: (Module): varevsij Comments added explaining the second
253: table of variances if popbased=1 .
254: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
255: (Module): Function pstamp added
256: (Module): Version 0.98d
257:
258: Revision 1.117 2006/03/14 17:16:22 brouard
259: (Module): varevsij Comments added explaining the second
260: table of variances if popbased=1 .
261: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
262: (Module): Function pstamp added
263: (Module): Version 0.98d
264:
265: Revision 1.116 2006/03/06 10:29:27 brouard
266: (Module): Variance-covariance wrong links and
267: varian-covariance of ej. is needed (Saito).
268:
269: Revision 1.115 2006/02/27 12:17:45 brouard
270: (Module): One freematrix added in mlikeli! 0.98c
271:
272: Revision 1.114 2006/02/26 12:57:58 brouard
273: (Module): Some improvements in processing parameter
274: filename with strsep.
275:
276: Revision 1.113 2006/02/24 14:20:24 brouard
277: (Module): Memory leaks checks with valgrind and:
278: datafile was not closed, some imatrix were not freed and on matrix
279: allocation too.
280:
281: Revision 1.112 2006/01/30 09:55:26 brouard
282: (Module): Back to gnuplot.exe instead of wgnuplot.exe
283:
284: Revision 1.111 2006/01/25 20:38:18 brouard
285: (Module): Lots of cleaning and bugs added (Gompertz)
286: (Module): Comments can be added in data file. Missing date values
287: can be a simple dot '.'.
288:
289: Revision 1.110 2006/01/25 00:51:50 brouard
290: (Module): Lots of cleaning and bugs added (Gompertz)
291:
292: Revision 1.109 2006/01/24 19:37:15 brouard
293: (Module): Comments (lines starting with a #) are allowed in data.
294:
295: Revision 1.108 2006/01/19 18:05:42 lievre
296: Gnuplot problem appeared...
297: To be fixed
298:
299: Revision 1.107 2006/01/19 16:20:37 brouard
300: Test existence of gnuplot in imach path
301:
302: Revision 1.106 2006/01/19 13:24:36 brouard
303: Some cleaning and links added in html output
304:
305: Revision 1.105 2006/01/05 20:23:19 lievre
306: *** empty log message ***
307:
308: Revision 1.104 2005/09/30 16:11:43 lievre
309: (Module): sump fixed, loop imx fixed, and simplifications.
310: (Module): If the status is missing at the last wave but we know
311: that the person is alive, then we can code his/her status as -2
312: (instead of missing=-1 in earlier versions) and his/her
313: contributions to the likelihood is 1 - Prob of dying from last
314: health status (= 1-p13= p11+p12 in the easiest case of somebody in
315: the healthy state at last known wave). Version is 0.98
316:
317: Revision 1.103 2005/09/30 15:54:49 lievre
318: (Module): sump fixed, loop imx fixed, and simplifications.
319:
320: Revision 1.102 2004/09/15 17:31:30 brouard
321: Add the possibility to read data file including tab characters.
322:
323: Revision 1.101 2004/09/15 10:38:38 brouard
324: Fix on curr_time
325:
326: Revision 1.100 2004/07/12 18:29:06 brouard
327: Add version for Mac OS X. Just define UNIX in Makefile
328:
329: Revision 1.99 2004/06/05 08:57:40 brouard
330: *** empty log message ***
331:
332: Revision 1.98 2004/05/16 15:05:56 brouard
333: New version 0.97 . First attempt to estimate force of mortality
334: directly from the data i.e. without the need of knowing the health
335: state at each age, but using a Gompertz model: log u =a + b*age .
336: This is the basic analysis of mortality and should be done before any
337: other analysis, in order to test if the mortality estimated from the
338: cross-longitudinal survey is different from the mortality estimated
339: from other sources like vital statistic data.
340:
341: The same imach parameter file can be used but the option for mle should be -3.
342:
1.133 brouard 343: Agnès, who wrote this part of the code, tried to keep most of the
1.126 brouard 344: former routines in order to include the new code within the former code.
345:
346: The output is very simple: only an estimate of the intercept and of
347: the slope with 95% confident intervals.
348:
349: Current limitations:
350: A) Even if you enter covariates, i.e. with the
351: model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
352: B) There is no computation of Life Expectancy nor Life Table.
353:
354: Revision 1.97 2004/02/20 13:25:42 lievre
355: Version 0.96d. Population forecasting command line is (temporarily)
356: suppressed.
357:
358: Revision 1.96 2003/07/15 15:38:55 brouard
359: * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
360: rewritten within the same printf. Workaround: many printfs.
361:
362: Revision 1.95 2003/07/08 07:54:34 brouard
363: * imach.c (Repository):
364: (Repository): Using imachwizard code to output a more meaningful covariance
365: matrix (cov(a12,c31) instead of numbers.
366:
367: Revision 1.94 2003/06/27 13:00:02 brouard
368: Just cleaning
369:
370: Revision 1.93 2003/06/25 16:33:55 brouard
371: (Module): On windows (cygwin) function asctime_r doesn't
372: exist so I changed back to asctime which exists.
373: (Module): Version 0.96b
374:
375: Revision 1.92 2003/06/25 16:30:45 brouard
376: (Module): On windows (cygwin) function asctime_r doesn't
377: exist so I changed back to asctime which exists.
378:
379: Revision 1.91 2003/06/25 15:30:29 brouard
380: * imach.c (Repository): Duplicated warning errors corrected.
381: (Repository): Elapsed time after each iteration is now output. It
382: helps to forecast when convergence will be reached. Elapsed time
383: is stamped in powell. We created a new html file for the graphs
384: concerning matrix of covariance. It has extension -cov.htm.
385:
386: Revision 1.90 2003/06/24 12:34:15 brouard
387: (Module): Some bugs corrected for windows. Also, when
388: mle=-1 a template is output in file "or"mypar.txt with the design
389: of the covariance matrix to be input.
390:
391: Revision 1.89 2003/06/24 12:30:52 brouard
392: (Module): Some bugs corrected for windows. Also, when
393: mle=-1 a template is output in file "or"mypar.txt with the design
394: of the covariance matrix to be input.
395:
396: Revision 1.88 2003/06/23 17:54:56 brouard
397: * 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.
398:
399: Revision 1.87 2003/06/18 12:26:01 brouard
400: Version 0.96
401:
402: Revision 1.86 2003/06/17 20:04:08 brouard
403: (Module): Change position of html and gnuplot routines and added
404: routine fileappend.
405:
406: Revision 1.85 2003/06/17 13:12:43 brouard
407: * imach.c (Repository): Check when date of death was earlier that
408: current date of interview. It may happen when the death was just
409: prior to the death. In this case, dh was negative and likelihood
410: was wrong (infinity). We still send an "Error" but patch by
411: assuming that the date of death was just one stepm after the
412: interview.
413: (Repository): Because some people have very long ID (first column)
414: we changed int to long in num[] and we added a new lvector for
415: memory allocation. But we also truncated to 8 characters (left
416: truncation)
417: (Repository): No more line truncation errors.
418:
419: Revision 1.84 2003/06/13 21:44:43 brouard
420: * imach.c (Repository): Replace "freqsummary" at a correct
421: place. It differs from routine "prevalence" which may be called
422: many times. Probs is memory consuming and must be used with
423: parcimony.
424: Version 0.95a3 (should output exactly the same maximization than 0.8a2)
425:
426: Revision 1.83 2003/06/10 13:39:11 lievre
427: *** empty log message ***
428:
429: Revision 1.82 2003/06/05 15:57:20 brouard
430: Add log in imach.c and fullversion number is now printed.
431:
432: */
433: /*
434: Interpolated Markov Chain
435:
436: Short summary of the programme:
437:
438: This program computes Healthy Life Expectancies from
439: cross-longitudinal data. Cross-longitudinal data consist in: -1- a
440: first survey ("cross") where individuals from different ages are
441: interviewed on their health status or degree of disability (in the
442: case of a health survey which is our main interest) -2- at least a
443: second wave of interviews ("longitudinal") which measure each change
444: (if any) in individual health status. Health expectancies are
445: computed from the time spent in each health state according to a
446: model. More health states you consider, more time is necessary to reach the
447: Maximum Likelihood of the parameters involved in the model. The
448: simplest model is the multinomial logistic model where pij is the
449: probability to be observed in state j at the second wave
450: conditional to be observed in state i at the first wave. Therefore
451: the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
452: 'age' is age and 'sex' is a covariate. If you want to have a more
453: complex model than "constant and age", you should modify the program
454: where the markup *Covariates have to be included here again* invites
455: you to do it. More covariates you add, slower the
456: convergence.
457:
458: The advantage of this computer programme, compared to a simple
459: multinomial logistic model, is clear when the delay between waves is not
460: identical for each individual. Also, if a individual missed an
461: intermediate interview, the information is lost, but taken into
462: account using an interpolation or extrapolation.
463:
464: hPijx is the probability to be observed in state i at age x+h
465: conditional to the observed state i at age x. The delay 'h' can be
466: split into an exact number (nh*stepm) of unobserved intermediate
467: states. This elementary transition (by month, quarter,
468: semester or year) is modelled as a multinomial logistic. The hPx
469: matrix is simply the matrix product of nh*stepm elementary matrices
470: and the contribution of each individual to the likelihood is simply
471: hPijx.
472:
473: Also this programme outputs the covariance matrix of the parameters but also
474: of the life expectancies. It also computes the period (stable) prevalence.
475:
1.133 brouard 476: Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
477: Institut national d'études démographiques, Paris.
1.126 brouard 478: This software have been partly granted by Euro-REVES, a concerted action
479: from the European Union.
480: It is copyrighted identically to a GNU software product, ie programme and
481: software can be distributed freely for non commercial use. Latest version
482: can be accessed at http://euroreves.ined.fr/imach .
483:
484: Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
485: or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
486:
487: **********************************************************************/
488: /*
489: main
490: read parameterfile
491: read datafile
492: concatwav
493: freqsummary
494: if (mle >= 1)
495: mlikeli
496: print results files
497: if mle==1
498: computes hessian
499: read end of parameter file: agemin, agemax, bage, fage, estepm
500: begin-prev-date,...
501: open gnuplot file
502: open html file
1.145 brouard 503: period (stable) prevalence | pl_nom 1-1 2-2 etc by covariate
504: for age prevalim() | #****** V1=0 V2=1 V3=1 V4=0 ******
505: | 65 1 0 2 1 3 1 4 0 0.96326 0.03674
506: freexexit2 possible for memory heap.
507:
508: h Pij x | pij_nom ficrestpij
509: # Cov Agex agex+h hpijx with i,j= 1-1 1-2 1-3 2-1 2-2 2-3
510: 1 85 85 1.00000 0.00000 0.00000 0.00000 1.00000 0.00000
511: 1 85 86 0.68299 0.22291 0.09410 0.71093 0.00000 0.28907
512:
513: 1 65 99 0.00364 0.00322 0.99314 0.00350 0.00310 0.99340
514: 1 65 100 0.00214 0.00204 0.99581 0.00206 0.00196 0.99597
515: variance of p one-step probabilities varprob | prob_nom ficresprob #One-step probabilities and stand. devi in ()
516: Standard deviation of one-step probabilities | probcor_nom ficresprobcor #One-step probabilities and correlation matrix
517: Matrix of variance covariance of one-step probabilities | probcov_nom ficresprobcov #One-step probabilities and covariance matrix
518:
1.126 brouard 519: forecasting if prevfcast==1 prevforecast call prevalence()
520: health expectancies
521: Variance-covariance of DFLE
522: prevalence()
523: movingaverage()
524: varevsij()
525: if popbased==1 varevsij(,popbased)
526: total life expectancies
527: Variance of period (stable) prevalence
528: end
529: */
530:
1.165 brouard 531: #define POWELL /* Instead of NLOPT */
1.126 brouard 532:
533: #include <math.h>
534: #include <stdio.h>
535: #include <stdlib.h>
536: #include <string.h>
1.159 brouard 537:
538: #ifdef _WIN32
539: #include <io.h>
1.172 ! brouard 540: #include <windows.h>
! 541: #include <tchar.h>
1.159 brouard 542: #else
1.126 brouard 543: #include <unistd.h>
1.159 brouard 544: #endif
1.126 brouard 545:
546: #include <limits.h>
547: #include <sys/types.h>
1.171 brouard 548:
549: #if defined(__GNUC__)
550: #include <sys/utsname.h> /* Doesn't work on Windows */
551: #endif
552:
1.126 brouard 553: #include <sys/stat.h>
554: #include <errno.h>
1.159 brouard 555: /* extern int errno; */
1.126 brouard 556:
1.157 brouard 557: /* #ifdef LINUX */
558: /* #include <time.h> */
559: /* #include "timeval.h" */
560: /* #else */
561: /* #include <sys/time.h> */
562: /* #endif */
563:
1.126 brouard 564: #include <time.h>
565:
1.136 brouard 566: #ifdef GSL
567: #include <gsl/gsl_errno.h>
568: #include <gsl/gsl_multimin.h>
569: #endif
570:
1.167 brouard 571:
1.162 brouard 572: #ifdef NLOPT
573: #include <nlopt.h>
574: typedef struct {
575: double (* function)(double [] );
576: } myfunc_data ;
577: #endif
578:
1.126 brouard 579: /* #include <libintl.h> */
580: /* #define _(String) gettext (String) */
581:
1.141 brouard 582: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126 brouard 583:
584: #define GNUPLOTPROGRAM "gnuplot"
585: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
586: #define FILENAMELENGTH 132
587:
588: #define GLOCK_ERROR_NOPATH -1 /* empty path */
589: #define GLOCK_ERROR_GETCWD -2 /* cannot get cwd */
590:
1.144 brouard 591: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
592: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126 brouard 593:
594: #define NINTERVMAX 8
1.144 brouard 595: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
596: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
597: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.145 brouard 598: #define codtabm(h,k) 1 & (h-1) >> (k-1) ;
1.126 brouard 599: #define MAXN 20000
1.144 brouard 600: #define YEARM 12. /**< Number of months per year */
1.126 brouard 601: #define AGESUP 130
602: #define AGEBASE 40
1.164 brouard 603: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157 brouard 604: #ifdef _WIN32
605: #define DIRSEPARATOR '\\'
606: #define CHARSEPARATOR "\\"
607: #define ODIRSEPARATOR '/'
608: #else
1.126 brouard 609: #define DIRSEPARATOR '/'
610: #define CHARSEPARATOR "/"
611: #define ODIRSEPARATOR '\\'
612: #endif
613:
1.172 ! brouard 614: /* $Id: imach.c,v 1.171 2014/12/23 13:26:59 brouard Exp $ */
1.126 brouard 615: /* $State: Exp $ */
616:
1.169 brouard 617: char version[]="Imach version 0.98p, December 2014,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015";
1.172 ! brouard 618: char fullversion[]="$Revision: 1.171 $ $Date: 2014/12/23 13:26:59 $";
1.126 brouard 619: char strstart[80];
620: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130 brouard 621: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings */
1.133 brouard 622: int nvar=0, nforce=0; /* Number of variables, number of forces */
1.145 brouard 623: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
624: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
625: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
626: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
627: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
628: int cptcovprodnoage=0; /**< Number of covariate products without age */
629: int cptcoveff=0; /* Total number of covariates to vary for printing results */
630: int cptcov=0; /* Working variable */
1.126 brouard 631: int npar=NPARMAX;
632: int nlstate=2; /* Number of live states */
633: int ndeath=1; /* Number of dead states */
1.130 brouard 634: int ncovmodel=0, ncovcol=0; /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126 brouard 635: int popbased=0;
636:
637: int *wav; /* Number of waves for this individuual 0 is possible */
1.130 brouard 638: int maxwav=0; /* Maxim number of waves */
639: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
640: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */
641: int gipmx=0, gsw=0; /* Global variables on the number of contributions
1.126 brouard 642: to the likelihood and the sum of weights (done by funcone)*/
1.130 brouard 643: int mle=1, weightopt=0;
1.126 brouard 644: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
645: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
646: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
647: * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162 brouard 648: int countcallfunc=0; /* Count the number of calls to func */
1.130 brouard 649: double jmean=1; /* Mean space between 2 waves */
1.145 brouard 650: double **matprod2(); /* test */
1.126 brouard 651: double **oldm, **newm, **savm; /* Working pointers to matrices */
652: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136 brouard 653: /*FILE *fic ; */ /* Used in readdata only */
654: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126 brouard 655: FILE *ficlog, *ficrespow;
1.130 brouard 656: int globpr=0; /* Global variable for printing or not */
1.126 brouard 657: double fretone; /* Only one call to likelihood */
1.130 brouard 658: long ipmx=0; /* Number of contributions */
1.126 brouard 659: double sw; /* Sum of weights */
660: char filerespow[FILENAMELENGTH];
661: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
662: FILE *ficresilk;
663: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
664: FILE *ficresprobmorprev;
665: FILE *fichtm, *fichtmcov; /* Html File */
666: FILE *ficreseij;
667: char filerese[FILENAMELENGTH];
668: FILE *ficresstdeij;
669: char fileresstde[FILENAMELENGTH];
670: FILE *ficrescveij;
671: char filerescve[FILENAMELENGTH];
672: FILE *ficresvij;
673: char fileresv[FILENAMELENGTH];
674: FILE *ficresvpl;
675: char fileresvpl[FILENAMELENGTH];
676: char title[MAXLINE];
677: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH], filerespl[FILENAMELENGTH];
678: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
679: char tmpout[FILENAMELENGTH], tmpout2[FILENAMELENGTH];
680: char command[FILENAMELENGTH];
681: int outcmd=0;
682:
683: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
684:
685: char filelog[FILENAMELENGTH]; /* Log file */
686: char filerest[FILENAMELENGTH];
687: char fileregp[FILENAMELENGTH];
688: char popfile[FILENAMELENGTH];
689:
690: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
691:
1.157 brouard 692: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
693: /* struct timezone tzp; */
694: /* extern int gettimeofday(); */
695: struct tm tml, *gmtime(), *localtime();
696:
697: extern time_t time();
698:
699: struct tm start_time, end_time, curr_time, last_time, forecast_time;
700: time_t rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
701: struct tm tm;
702:
1.126 brouard 703: char strcurr[80], strfor[80];
704:
705: char *endptr;
706: long lval;
707: double dval;
708:
709: #define NR_END 1
710: #define FREE_ARG char*
711: #define FTOL 1.0e-10
712:
713: #define NRANSI
714: #define ITMAX 200
715:
716: #define TOL 2.0e-4
717:
718: #define CGOLD 0.3819660
719: #define ZEPS 1.0e-10
720: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
721:
722: #define GOLD 1.618034
723: #define GLIMIT 100.0
724: #define TINY 1.0e-20
725:
726: static double maxarg1,maxarg2;
727: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
728: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
729:
730: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
731: #define rint(a) floor(a+0.5)
1.166 brouard 732: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
733: /* #define mytinydouble 1.0e-16 */
734: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
735: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
736: /* static double dsqrarg; */
737: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126 brouard 738: static double sqrarg;
739: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
740: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
741: int agegomp= AGEGOMP;
742:
743: int imx;
744: int stepm=1;
745: /* Stepm, step in month: minimum step interpolation*/
746:
747: int estepm;
748: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
749:
750: int m,nb;
751: long *num;
752: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
753: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
754: double **pmmij, ***probs;
755: double *ageexmed,*agecens;
756: double dateintmean=0;
757:
758: double *weight;
759: int **s; /* Status */
1.141 brouard 760: double *agedc;
1.145 brouard 761: double **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141 brouard 762: * covar=matrix(0,NCOVMAX,1,n);
763: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; */
764: double idx;
765: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.145 brouard 766: int *Ndum; /** Freq of modality (tricode */
1.141 brouard 767: int **codtab; /**< codtab=imatrix(1,100,1,10); */
768: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126 brouard 769: double *lsurv, *lpop, *tpop;
770:
1.143 brouard 771: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
772: double ftolhess; /**< Tolerance for computing hessian */
1.126 brouard 773:
774: /**************** split *************************/
775: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
776: {
777: /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
778: the name of the file (name), its extension only (ext) and its first part of the name (finame)
779: */
780: char *ss; /* pointer */
781: int l1, l2; /* length counters */
782:
783: l1 = strlen(path ); /* length of path */
784: if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
785: ss= strrchr( path, DIRSEPARATOR ); /* find last / */
786: if ( ss == NULL ) { /* no directory, so determine current directory */
787: strcpy( name, path ); /* we got the fullname name because no directory */
788: /*if(strrchr(path, ODIRSEPARATOR )==NULL)
789: printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
790: /* get current working directory */
791: /* extern char* getcwd ( char *buf , int len);*/
792: if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
793: return( GLOCK_ERROR_GETCWD );
794: }
795: /* got dirc from getcwd*/
796: printf(" DIRC = %s \n",dirc);
797: } else { /* strip direcotry from path */
798: ss++; /* after this, the filename */
799: l2 = strlen( ss ); /* length of filename */
800: if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
801: strcpy( name, ss ); /* save file name */
802: strncpy( dirc, path, l1 - l2 ); /* now the directory */
803: dirc[l1-l2] = 0; /* add zero */
804: printf(" DIRC2 = %s \n",dirc);
805: }
806: /* We add a separator at the end of dirc if not exists */
807: l1 = strlen( dirc ); /* length of directory */
808: if( dirc[l1-1] != DIRSEPARATOR ){
809: dirc[l1] = DIRSEPARATOR;
810: dirc[l1+1] = 0;
811: printf(" DIRC3 = %s \n",dirc);
812: }
813: ss = strrchr( name, '.' ); /* find last / */
814: if (ss >0){
815: ss++;
816: strcpy(ext,ss); /* save extension */
817: l1= strlen( name);
818: l2= strlen(ss)+1;
819: strncpy( finame, name, l1-l2);
820: finame[l1-l2]= 0;
821: }
822:
823: return( 0 ); /* we're done */
824: }
825:
826:
827: /******************************************/
828:
829: void replace_back_to_slash(char *s, char*t)
830: {
831: int i;
832: int lg=0;
833: i=0;
834: lg=strlen(t);
835: for(i=0; i<= lg; i++) {
836: (s[i] = t[i]);
837: if (t[i]== '\\') s[i]='/';
838: }
839: }
840:
1.132 brouard 841: char *trimbb(char *out, char *in)
1.137 brouard 842: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132 brouard 843: char *s;
844: s=out;
845: while (*in != '\0'){
1.137 brouard 846: while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132 brouard 847: in++;
848: }
849: *out++ = *in++;
850: }
851: *out='\0';
852: return s;
853: }
854:
1.145 brouard 855: char *cutl(char *blocc, char *alocc, char *in, char occ)
856: {
857: /* cuts string in into blocc and alocc where blocc ends before first occurence of char 'occ'
858: and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
859: gives blocc="abcdef2ghi" and alocc="j".
860: If occ is not found blocc is null and alocc is equal to in. Returns blocc
861: */
1.160 brouard 862: char *s, *t;
1.145 brouard 863: t=in;s=in;
864: while ((*in != occ) && (*in != '\0')){
865: *alocc++ = *in++;
866: }
867: if( *in == occ){
868: *(alocc)='\0';
869: s=++in;
870: }
871:
872: if (s == t) {/* occ not found */
873: *(alocc-(in-s))='\0';
874: in=s;
875: }
876: while ( *in != '\0'){
877: *blocc++ = *in++;
878: }
879:
880: *blocc='\0';
881: return t;
882: }
1.137 brouard 883: char *cutv(char *blocc, char *alocc, char *in, char occ)
884: {
885: /* cuts string in into blocc and alocc where blocc ends before last occurence of char 'occ'
886: and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
887: gives blocc="abcdef2ghi" and alocc="j".
888: If occ is not found blocc is null and alocc is equal to in. Returns alocc
889: */
890: char *s, *t;
891: t=in;s=in;
892: while (*in != '\0'){
893: while( *in == occ){
894: *blocc++ = *in++;
895: s=in;
896: }
897: *blocc++ = *in++;
898: }
899: if (s == t) /* occ not found */
900: *(blocc-(in-s))='\0';
901: else
902: *(blocc-(in-s)-1)='\0';
903: in=s;
904: while ( *in != '\0'){
905: *alocc++ = *in++;
906: }
907:
908: *alocc='\0';
909: return s;
910: }
911:
1.126 brouard 912: int nbocc(char *s, char occ)
913: {
914: int i,j=0;
915: int lg=20;
916: i=0;
917: lg=strlen(s);
918: for(i=0; i<= lg; i++) {
919: if (s[i] == occ ) j++;
920: }
921: return j;
922: }
923:
1.137 brouard 924: /* void cutv(char *u,char *v, char*t, char occ) */
925: /* { */
926: /* /\* cuts string t into u and v where u ends before last occurence of char 'occ' */
927: /* and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
928: /* gives u="abcdef2ghi" and v="j" *\/ */
929: /* int i,lg,j,p=0; */
930: /* i=0; */
931: /* lg=strlen(t); */
932: /* for(j=0; j<=lg-1; j++) { */
933: /* if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
934: /* } */
1.126 brouard 935:
1.137 brouard 936: /* for(j=0; j<p; j++) { */
937: /* (u[j] = t[j]); */
938: /* } */
939: /* u[p]='\0'; */
1.126 brouard 940:
1.137 brouard 941: /* for(j=0; j<= lg; j++) { */
942: /* if (j>=(p+1))(v[j-p-1] = t[j]); */
943: /* } */
944: /* } */
1.126 brouard 945:
1.160 brouard 946: #ifdef _WIN32
947: char * strsep(char **pp, const char *delim)
948: {
949: char *p, *q;
950:
951: if ((p = *pp) == NULL)
952: return 0;
953: if ((q = strpbrk (p, delim)) != NULL)
954: {
955: *pp = q + 1;
956: *q = '\0';
957: }
958: else
959: *pp = 0;
960: return p;
961: }
962: #endif
963:
1.126 brouard 964: /********************** nrerror ********************/
965:
966: void nrerror(char error_text[])
967: {
968: fprintf(stderr,"ERREUR ...\n");
969: fprintf(stderr,"%s\n",error_text);
970: exit(EXIT_FAILURE);
971: }
972: /*********************** vector *******************/
973: double *vector(int nl, int nh)
974: {
975: double *v;
976: v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
977: if (!v) nrerror("allocation failure in vector");
978: return v-nl+NR_END;
979: }
980:
981: /************************ free vector ******************/
982: void free_vector(double*v, int nl, int nh)
983: {
984: free((FREE_ARG)(v+nl-NR_END));
985: }
986:
987: /************************ivector *******************************/
988: int *ivector(long nl,long nh)
989: {
990: int *v;
991: v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
992: if (!v) nrerror("allocation failure in ivector");
993: return v-nl+NR_END;
994: }
995:
996: /******************free ivector **************************/
997: void free_ivector(int *v, long nl, long nh)
998: {
999: free((FREE_ARG)(v+nl-NR_END));
1000: }
1001:
1002: /************************lvector *******************************/
1003: long *lvector(long nl,long nh)
1004: {
1005: long *v;
1006: v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
1007: if (!v) nrerror("allocation failure in ivector");
1008: return v-nl+NR_END;
1009: }
1010:
1011: /******************free lvector **************************/
1012: void free_lvector(long *v, long nl, long nh)
1013: {
1014: free((FREE_ARG)(v+nl-NR_END));
1015: }
1016:
1017: /******************* imatrix *******************************/
1018: int **imatrix(long nrl, long nrh, long ncl, long nch)
1019: /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
1020: {
1021: long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
1022: int **m;
1023:
1024: /* allocate pointers to rows */
1025: m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
1026: if (!m) nrerror("allocation failure 1 in matrix()");
1027: m += NR_END;
1028: m -= nrl;
1029:
1030:
1031: /* allocate rows and set pointers to them */
1032: m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
1033: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1034: m[nrl] += NR_END;
1035: m[nrl] -= ncl;
1036:
1037: for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
1038:
1039: /* return pointer to array of pointers to rows */
1040: return m;
1041: }
1042:
1043: /****************** free_imatrix *************************/
1044: void free_imatrix(m,nrl,nrh,ncl,nch)
1045: int **m;
1046: long nch,ncl,nrh,nrl;
1047: /* free an int matrix allocated by imatrix() */
1048: {
1049: free((FREE_ARG) (m[nrl]+ncl-NR_END));
1050: free((FREE_ARG) (m+nrl-NR_END));
1051: }
1052:
1053: /******************* matrix *******************************/
1054: double **matrix(long nrl, long nrh, long ncl, long nch)
1055: {
1056: long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
1057: double **m;
1058:
1059: m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1060: if (!m) nrerror("allocation failure 1 in matrix()");
1061: m += NR_END;
1062: m -= nrl;
1063:
1064: m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1065: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1066: m[nrl] += NR_END;
1067: m[nrl] -= ncl;
1068:
1069: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1070: return m;
1.145 brouard 1071: /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
1072: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
1073: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126 brouard 1074: */
1075: }
1076:
1077: /*************************free matrix ************************/
1078: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
1079: {
1080: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1081: free((FREE_ARG)(m+nrl-NR_END));
1082: }
1083:
1084: /******************* ma3x *******************************/
1085: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
1086: {
1087: long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
1088: double ***m;
1089:
1090: m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1091: if (!m) nrerror("allocation failure 1 in matrix()");
1092: m += NR_END;
1093: m -= nrl;
1094:
1095: m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1096: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1097: m[nrl] += NR_END;
1098: m[nrl] -= ncl;
1099:
1100: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1101:
1102: m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
1103: if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
1104: m[nrl][ncl] += NR_END;
1105: m[nrl][ncl] -= nll;
1106: for (j=ncl+1; j<=nch; j++)
1107: m[nrl][j]=m[nrl][j-1]+nlay;
1108:
1109: for (i=nrl+1; i<=nrh; i++) {
1110: m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
1111: for (j=ncl+1; j<=nch; j++)
1112: m[i][j]=m[i][j-1]+nlay;
1113: }
1114: return m;
1115: /* gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
1116: &(m[i][j][k]) <=> *((*(m+i) + j)+k)
1117: */
1118: }
1119:
1120: /*************************free ma3x ************************/
1121: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
1122: {
1123: free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
1124: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1125: free((FREE_ARG)(m+nrl-NR_END));
1126: }
1127:
1128: /*************** function subdirf ***********/
1129: char *subdirf(char fileres[])
1130: {
1131: /* Caution optionfilefiname is hidden */
1132: strcpy(tmpout,optionfilefiname);
1133: strcat(tmpout,"/"); /* Add to the right */
1134: strcat(tmpout,fileres);
1135: return tmpout;
1136: }
1137:
1138: /*************** function subdirf2 ***********/
1139: char *subdirf2(char fileres[], char *preop)
1140: {
1141:
1142: /* Caution optionfilefiname is hidden */
1143: strcpy(tmpout,optionfilefiname);
1144: strcat(tmpout,"/");
1145: strcat(tmpout,preop);
1146: strcat(tmpout,fileres);
1147: return tmpout;
1148: }
1149:
1150: /*************** function subdirf3 ***********/
1151: char *subdirf3(char fileres[], char *preop, char *preop2)
1152: {
1153:
1154: /* Caution optionfilefiname is hidden */
1155: strcpy(tmpout,optionfilefiname);
1156: strcat(tmpout,"/");
1157: strcat(tmpout,preop);
1158: strcat(tmpout,preop2);
1159: strcat(tmpout,fileres);
1160: return tmpout;
1161: }
1162:
1.162 brouard 1163: char *asc_diff_time(long time_sec, char ascdiff[])
1164: {
1165: long sec_left, days, hours, minutes;
1166: days = (time_sec) / (60*60*24);
1167: sec_left = (time_sec) % (60*60*24);
1168: hours = (sec_left) / (60*60) ;
1169: sec_left = (sec_left) %(60*60);
1170: minutes = (sec_left) /60;
1171: sec_left = (sec_left) % (60);
1172: sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);
1173: return ascdiff;
1174: }
1175:
1.126 brouard 1176: /***************** f1dim *************************/
1177: extern int ncom;
1178: extern double *pcom,*xicom;
1179: extern double (*nrfunc)(double []);
1180:
1181: double f1dim(double x)
1182: {
1183: int j;
1184: double f;
1185: double *xt;
1186:
1187: xt=vector(1,ncom);
1188: for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
1189: f=(*nrfunc)(xt);
1190: free_vector(xt,1,ncom);
1191: return f;
1192: }
1193:
1194: /*****************brent *************************/
1195: double brent(double ax, double bx, double cx, double (*f)(double), double tol, double *xmin)
1196: {
1197: int iter;
1198: double a,b,d,etemp;
1.159 brouard 1199: double fu=0,fv,fw,fx;
1.164 brouard 1200: double ftemp=0.;
1.126 brouard 1201: double p,q,r,tol1,tol2,u,v,w,x,xm;
1202: double e=0.0;
1203:
1204: a=(ax < cx ? ax : cx);
1205: b=(ax > cx ? ax : cx);
1206: x=w=v=bx;
1207: fw=fv=fx=(*f)(x);
1208: for (iter=1;iter<=ITMAX;iter++) {
1209: xm=0.5*(a+b);
1210: tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
1211: /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
1212: printf(".");fflush(stdout);
1213: fprintf(ficlog,".");fflush(ficlog);
1.162 brouard 1214: #ifdef DEBUGBRENT
1.126 brouard 1215: 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);
1216: 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);
1217: /* if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
1218: #endif
1219: if (fabs(x-xm) <= (tol2-0.5*(b-a))){
1220: *xmin=x;
1221: return fx;
1222: }
1223: ftemp=fu;
1224: if (fabs(e) > tol1) {
1225: r=(x-w)*(fx-fv);
1226: q=(x-v)*(fx-fw);
1227: p=(x-v)*q-(x-w)*r;
1228: q=2.0*(q-r);
1229: if (q > 0.0) p = -p;
1230: q=fabs(q);
1231: etemp=e;
1232: e=d;
1233: if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
1234: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1235: else {
1236: d=p/q;
1237: u=x+d;
1238: if (u-a < tol2 || b-u < tol2)
1239: d=SIGN(tol1,xm-x);
1240: }
1241: } else {
1242: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1243: }
1244: u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
1245: fu=(*f)(u);
1246: if (fu <= fx) {
1247: if (u >= x) a=x; else b=x;
1248: SHFT(v,w,x,u)
1249: SHFT(fv,fw,fx,fu)
1250: } else {
1251: if (u < x) a=u; else b=u;
1252: if (fu <= fw || w == x) {
1253: v=w;
1254: w=u;
1255: fv=fw;
1256: fw=fu;
1257: } else if (fu <= fv || v == x || v == w) {
1258: v=u;
1259: fv=fu;
1260: }
1261: }
1262: }
1263: nrerror("Too many iterations in brent");
1264: *xmin=x;
1265: return fx;
1266: }
1267:
1268: /****************** mnbrak ***********************/
1269:
1270: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
1271: double (*func)(double))
1272: {
1273: double ulim,u,r,q, dum;
1274: double fu;
1275:
1276: *fa=(*func)(*ax);
1277: *fb=(*func)(*bx);
1278: if (*fb > *fa) {
1279: SHFT(dum,*ax,*bx,dum)
1280: SHFT(dum,*fb,*fa,dum)
1281: }
1282: *cx=(*bx)+GOLD*(*bx-*ax);
1283: *fc=(*func)(*cx);
1.162 brouard 1284: while (*fb > *fc) { /* Declining fa, fb, fc */
1.126 brouard 1285: r=(*bx-*ax)*(*fb-*fc);
1286: q=(*bx-*cx)*(*fb-*fa);
1287: u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
1.162 brouard 1288: (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscisse of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
1289: ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscisse where function can be evaluated */
1290: if ((*bx-u)*(u-*cx) > 0.0) { /* if u between b and c */
1.126 brouard 1291: fu=(*func)(u);
1.163 brouard 1292: #ifdef DEBUG
1293: /* f(x)=A(x-u)**2+f(u) */
1294: double A, fparabu;
1295: A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
1296: fparabu= *fa - A*(*ax-u)*(*ax-u);
1297: 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);
1298: 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);
1299: #endif
1.162 brouard 1300: } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.126 brouard 1301: fu=(*func)(u);
1302: if (fu < *fc) {
1303: SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
1304: SHFT(*fb,*fc,fu,(*func)(u))
1305: }
1.162 brouard 1306: } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.126 brouard 1307: u=ulim;
1308: fu=(*func)(u);
1309: } else {
1310: u=(*cx)+GOLD*(*cx-*bx);
1311: fu=(*func)(u);
1312: }
1313: SHFT(*ax,*bx,*cx,u)
1314: SHFT(*fa,*fb,*fc,fu)
1315: }
1316: }
1317:
1318: /*************** linmin ************************/
1.162 brouard 1319: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
1320: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
1321: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
1322: the value of func at the returned location p . This is actually all accomplished by calling the
1323: routines mnbrak and brent .*/
1.126 brouard 1324: int ncom;
1325: double *pcom,*xicom;
1326: double (*nrfunc)(double []);
1327:
1328: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
1329: {
1330: double brent(double ax, double bx, double cx,
1331: double (*f)(double), double tol, double *xmin);
1332: double f1dim(double x);
1333: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
1334: double *fc, double (*func)(double));
1335: int j;
1336: double xx,xmin,bx,ax;
1337: double fx,fb,fa;
1338:
1339: ncom=n;
1340: pcom=vector(1,n);
1341: xicom=vector(1,n);
1342: nrfunc=func;
1343: for (j=1;j<=n;j++) {
1344: pcom[j]=p[j];
1345: xicom[j]=xi[j];
1346: }
1347: ax=0.0;
1348: xx=1.0;
1.162 brouard 1349: mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Find a bracket a,x,b in direction n=xi ie xicom */
1350: *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 1351: #ifdef DEBUG
1352: printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1353: fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1354: #endif
1355: for (j=1;j<=n;j++) {
1356: xi[j] *= xmin;
1357: p[j] += xi[j];
1358: }
1359: free_vector(xicom,1,n);
1360: free_vector(pcom,1,n);
1361: }
1362:
1363:
1364: /*************** powell ************************/
1.162 brouard 1365: /*
1366: Minimization of a function func of n variables. Input consists of an initial starting point
1367: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
1368: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
1369: such that failure to decrease by more than this amount on one iteration signals doneness. On
1370: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
1371: function value at p , and iter is the number of iterations taken. The routine linmin is used.
1372: */
1.126 brouard 1373: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
1374: double (*func)(double []))
1375: {
1376: void linmin(double p[], double xi[], int n, double *fret,
1377: double (*func)(double []));
1378: int i,ibig,j;
1379: double del,t,*pt,*ptt,*xit;
1380: double fp,fptt;
1381: double *xits;
1382: int niterf, itmp;
1383:
1384: pt=vector(1,n);
1385: ptt=vector(1,n);
1386: xit=vector(1,n);
1387: xits=vector(1,n);
1388: *fret=(*func)(p);
1389: for (j=1;j<=n;j++) pt[j]=p[j];
1.157 brouard 1390: rcurr_time = time(NULL);
1.126 brouard 1391: for (*iter=1;;++(*iter)) {
1392: fp=(*fret);
1393: ibig=0;
1394: del=0.0;
1.157 brouard 1395: rlast_time=rcurr_time;
1396: /* (void) gettimeofday(&curr_time,&tzp); */
1397: rcurr_time = time(NULL);
1398: curr_time = *localtime(&rcurr_time);
1399: printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
1400: fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1401: /* fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.126 brouard 1402: for (i=1;i<=n;i++) {
1403: printf(" %d %.12f",i, p[i]);
1404: fprintf(ficlog," %d %.12lf",i, p[i]);
1405: fprintf(ficrespow," %.12lf", p[i]);
1406: }
1407: printf("\n");
1408: fprintf(ficlog,"\n");
1409: fprintf(ficrespow,"\n");fflush(ficrespow);
1410: if(*iter <=3){
1.157 brouard 1411: tml = *localtime(&rcurr_time);
1412: strcpy(strcurr,asctime(&tml));
1413: rforecast_time=rcurr_time;
1.126 brouard 1414: itmp = strlen(strcurr);
1415: if(strcurr[itmp-1]=='\n') /* Windows outputs with a new line */
1416: strcurr[itmp-1]='\0';
1.162 brouard 1417: printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157 brouard 1418: fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126 brouard 1419: for(niterf=10;niterf<=30;niterf+=10){
1.157 brouard 1420: rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
1421: forecast_time = *localtime(&rforecast_time);
1422: strcpy(strfor,asctime(&forecast_time));
1.126 brouard 1423: itmp = strlen(strfor);
1424: if(strfor[itmp-1]=='\n')
1425: strfor[itmp-1]='\0';
1.157 brouard 1426: 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);
1427: 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 1428: }
1429: }
1430: for (i=1;i<=n;i++) {
1431: for (j=1;j<=n;j++) xit[j]=xi[j][i];
1432: fptt=(*fret);
1433: #ifdef DEBUG
1.164 brouard 1434: printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1435: fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126 brouard 1436: #endif
1437: printf("%d",i);fflush(stdout);
1438: fprintf(ficlog,"%d",i);fflush(ficlog);
1439: linmin(p,xit,n,fret,func);
1440: if (fabs(fptt-(*fret)) > del) {
1441: del=fabs(fptt-(*fret));
1442: ibig=i;
1443: }
1444: #ifdef DEBUG
1445: printf("%d %.12e",i,(*fret));
1446: fprintf(ficlog,"%d %.12e",i,(*fret));
1447: for (j=1;j<=n;j++) {
1448: xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
1449: printf(" x(%d)=%.12e",j,xit[j]);
1450: fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1451: }
1452: for(j=1;j<=n;j++) {
1.162 brouard 1453: printf(" p(%d)=%.12e",j,p[j]);
1454: fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126 brouard 1455: }
1456: printf("\n");
1457: fprintf(ficlog,"\n");
1458: #endif
1.162 brouard 1459: } /* end i */
1.126 brouard 1460: if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
1461: #ifdef DEBUG
1462: int k[2],l;
1463: k[0]=1;
1464: k[1]=-1;
1465: printf("Max: %.12e",(*func)(p));
1466: fprintf(ficlog,"Max: %.12e",(*func)(p));
1467: for (j=1;j<=n;j++) {
1468: printf(" %.12e",p[j]);
1469: fprintf(ficlog," %.12e",p[j]);
1470: }
1471: printf("\n");
1472: fprintf(ficlog,"\n");
1473: for(l=0;l<=1;l++) {
1474: for (j=1;j<=n;j++) {
1475: ptt[j]=p[j]+(p[j]-pt[j])*k[l];
1476: printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1477: fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1478: }
1479: printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1480: fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1481: }
1482: #endif
1483:
1484:
1485: free_vector(xit,1,n);
1486: free_vector(xits,1,n);
1487: free_vector(ptt,1,n);
1488: free_vector(pt,1,n);
1489: return;
1490: }
1491: if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
1.161 brouard 1492: for (j=1;j<=n;j++) { /* Computes an extrapolated point */
1.126 brouard 1493: ptt[j]=2.0*p[j]-pt[j];
1494: xit[j]=p[j]-pt[j];
1495: pt[j]=p[j];
1496: }
1497: fptt=(*func)(ptt);
1.161 brouard 1498: if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.162 brouard 1499: /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161 brouard 1500: /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162 brouard 1501: /* Let f"(x2) be the 2nd derivative equal everywhere. */
1502: /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
1503: /* will reach at f3 = fm + h^2/2 f"m ; f" = (f1 -2f2 +f3 ) / h**2 */
1.161 brouard 1504: /* f1-f3 = delta(2h) = 2 h**2 f'' = 2(f1- 2f2 +f3) */
1505: /* Thus we compare delta(2h) with observed f1-f3 */
1.162 brouard 1506: /* or best gain on one ancient line 'del' with total */
1507: /* gain f1-f2 = f1 - f2 - 'del' with del */
1.161 brouard 1508: /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.162 brouard 1509:
1.161 brouard 1510: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del);
1511: t= t- del*SQR(fp-fptt);
1512: printf("t1= %.12lf, t2= %.12lf, t=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t);
1513: 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);
1514: #ifdef DEBUG
1515: printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1516: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1517: fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1518: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1519: 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);
1520: 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);
1521: #endif
1522: if (t < 0.0) { /* Then we use it for last direction */
1523: linmin(p,xit,n,fret,func); /* computes mean on the extrapolated direction.*/
1.126 brouard 1524: for (j=1;j<=n;j++) {
1.161 brouard 1525: xi[j][ibig]=xi[j][n]; /* Replace the direction with biggest decrease by n */
1526: xi[j][n]=xit[j]; /* and nth direction by the extrapolated */
1.126 brouard 1527: }
1.161 brouard 1528: printf("Gaining to use average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.169 brouard 1529: fprintf(ficlog,"Gaining to use average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161 brouard 1530:
1.126 brouard 1531: #ifdef DEBUG
1.164 brouard 1532: printf("Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1533: fprintf(ficlog,"Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126 brouard 1534: for(j=1;j<=n;j++){
1535: printf(" %.12e",xit[j]);
1536: fprintf(ficlog," %.12e",xit[j]);
1537: }
1538: printf("\n");
1539: fprintf(ficlog,"\n");
1540: #endif
1.162 brouard 1541: } /* end of t negative */
1542: } /* end if (fptt < fp) */
1.126 brouard 1543: }
1544: }
1545:
1546: /**** Prevalence limit (stable or period prevalence) ****************/
1547:
1548: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
1549: {
1550: /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1551: matrix by transitions matrix until convergence is reached */
1.169 brouard 1552:
1.126 brouard 1553: int i, ii,j,k;
1554: double min, max, maxmin, maxmax,sumnew=0.;
1.145 brouard 1555: /* double **matprod2(); */ /* test */
1.131 brouard 1556: double **out, cov[NCOVMAX+1], **pmij();
1.126 brouard 1557: double **newm;
1558: double agefin, delaymax=50 ; /* Max number of years to converge */
1.169 brouard 1559:
1.126 brouard 1560: for (ii=1;ii<=nlstate+ndeath;ii++)
1561: for (j=1;j<=nlstate+ndeath;j++){
1562: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1563: }
1.169 brouard 1564:
1565: cov[1]=1.;
1566:
1567: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.126 brouard 1568: for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1569: newm=savm;
1570: /* Covariates have to be included here again */
1.138 brouard 1571: cov[2]=agefin;
1572:
1573: for (k=1; k<=cptcovn;k++) {
1574: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.145 brouard 1575: /*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 1576: }
1.145 brouard 1577: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1578: /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
1579: /* 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 1580:
1581: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
1582: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
1583: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145 brouard 1584: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1585: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142 brouard 1586: out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138 brouard 1587:
1.126 brouard 1588: savm=oldm;
1589: oldm=newm;
1590: maxmax=0.;
1591: for(j=1;j<=nlstate;j++){
1592: min=1.;
1593: max=0.;
1594: for(i=1; i<=nlstate; i++) {
1595: sumnew=0;
1596: for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
1597: prlim[i][j]= newm[i][j]/(1-sumnew);
1.145 brouard 1598: /*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 1599: max=FMAX(max,prlim[i][j]);
1600: min=FMIN(min,prlim[i][j]);
1601: }
1602: maxmin=max-min;
1603: maxmax=FMAX(maxmax,maxmin);
1.169 brouard 1604: } /* j loop */
1.126 brouard 1605: if(maxmax < ftolpl){
1606: return prlim;
1607: }
1.169 brouard 1608: } /* age loop */
1609: return prlim; /* should not reach here */
1.126 brouard 1610: }
1611:
1612: /*************** transition probabilities ***************/
1613:
1614: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1615: {
1.138 brouard 1616: /* According to parameters values stored in x and the covariate's values stored in cov,
1617: computes the probability to be observed in state j being in state i by appying the
1618: model to the ncovmodel covariates (including constant and age).
1619: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
1620: and, according on how parameters are entered, the position of the coefficient xij(nc) of the
1621: ncth covariate in the global vector x is given by the formula:
1622: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
1623: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
1624: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
1625: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1626: Outputs ps[i][j] the probability to be observed in j being in j according to
1627: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1628: */
1629: double s1, lnpijopii;
1.126 brouard 1630: /*double t34;*/
1.164 brouard 1631: int i,j, nc, ii, jj;
1.126 brouard 1632:
1633: for(i=1; i<= nlstate; i++){
1634: for(j=1; j<i;j++){
1.138 brouard 1635: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1636: /*lnpijopii += param[i][j][nc]*cov[nc];*/
1637: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
1638: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 1639: }
1.138 brouard 1640: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1641: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 1642: }
1643: for(j=i+1; j<=nlstate+ndeath;j++){
1.138 brouard 1644: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1645: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
1646: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
1647: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126 brouard 1648: }
1.138 brouard 1649: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126 brouard 1650: }
1651: }
1652:
1653: for(i=1; i<= nlstate; i++){
1654: s1=0;
1.131 brouard 1655: for(j=1; j<i; j++){
1.138 brouard 1656: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 1657: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1658: }
1659: for(j=i+1; j<=nlstate+ndeath; j++){
1.138 brouard 1660: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 1661: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1662: }
1.138 brouard 1663: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126 brouard 1664: ps[i][i]=1./(s1+1.);
1.138 brouard 1665: /* Computing other pijs */
1.126 brouard 1666: for(j=1; j<i; j++)
1667: ps[i][j]= exp(ps[i][j])*ps[i][i];
1668: for(j=i+1; j<=nlstate+ndeath; j++)
1669: ps[i][j]= exp(ps[i][j])*ps[i][i];
1670: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
1671: } /* end i */
1672:
1673: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
1674: for(jj=1; jj<= nlstate+ndeath; jj++){
1675: ps[ii][jj]=0;
1676: ps[ii][ii]=1;
1677: }
1678: }
1679:
1.145 brouard 1680:
1681: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
1682: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */
1683: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
1684: /* } */
1685: /* printf("\n "); */
1686: /* } */
1687: /* printf("\n ");printf("%lf ",cov[2]);*/
1688: /*
1.126 brouard 1689: for(i=1; i<= npar; i++) printf("%f ",x[i]);
1690: goto end;*/
1691: return ps;
1692: }
1693:
1694: /**************** Product of 2 matrices ******************/
1695:
1.145 brouard 1696: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126 brouard 1697: {
1698: /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
1699: b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
1700: /* in, b, out are matrice of pointers which should have been initialized
1701: before: only the contents of out is modified. The function returns
1702: a pointer to pointers identical to out */
1.145 brouard 1703: int i, j, k;
1.126 brouard 1704: for(i=nrl; i<= nrh; i++)
1.145 brouard 1705: for(k=ncolol; k<=ncoloh; k++){
1706: out[i][k]=0.;
1707: for(j=ncl; j<=nch; j++)
1708: out[i][k] +=in[i][j]*b[j][k];
1709: }
1.126 brouard 1710: return out;
1711: }
1712:
1713:
1714: /************* Higher Matrix Product ***************/
1715:
1716: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
1717: {
1718: /* Computes the transition matrix starting at age 'age' over
1719: 'nhstepm*hstepm*stepm' months (i.e. until
1720: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
1721: nhstepm*hstepm matrices.
1722: Output is stored in matrix po[i][j][h] for h every 'hstepm' step
1723: (typically every 2 years instead of every month which is too big
1724: for the memory).
1725: Model is determined by parameters x and covariates have to be
1726: included manually here.
1727:
1728: */
1729:
1730: int i, j, d, h, k;
1.131 brouard 1731: double **out, cov[NCOVMAX+1];
1.126 brouard 1732: double **newm;
1733:
1734: /* Hstepm could be zero and should return the unit matrix */
1735: for (i=1;i<=nlstate+ndeath;i++)
1736: for (j=1;j<=nlstate+ndeath;j++){
1737: oldm[i][j]=(i==j ? 1.0 : 0.0);
1738: po[i][j][0]=(i==j ? 1.0 : 0.0);
1739: }
1740: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1741: for(h=1; h <=nhstepm; h++){
1742: for(d=1; d <=hstepm; d++){
1743: newm=savm;
1744: /* Covariates have to be included here again */
1745: cov[1]=1.;
1746: cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
1.131 brouard 1747: for (k=1; k<=cptcovn;k++)
1748: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.126 brouard 1749: for (k=1; k<=cptcovage;k++)
1750: cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
1.145 brouard 1751: for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.126 brouard 1752: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
1753:
1754:
1755: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
1756: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1757: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
1758: pmij(pmmij,cov,ncovmodel,x,nlstate));
1759: savm=oldm;
1760: oldm=newm;
1761: }
1762: for(i=1; i<=nlstate+ndeath; i++)
1763: for(j=1;j<=nlstate+ndeath;j++) {
1764: po[i][j][h]=newm[i][j];
1.128 brouard 1765: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126 brouard 1766: }
1.128 brouard 1767: /*printf("h=%d ",h);*/
1.126 brouard 1768: } /* end h */
1.128 brouard 1769: /* printf("\n H=%d \n",h); */
1.126 brouard 1770: return po;
1771: }
1772:
1.162 brouard 1773: #ifdef NLOPT
1774: double myfunc(unsigned n, const double *p1, double *grad, void *pd){
1775: double fret;
1776: double *xt;
1777: int j;
1778: myfunc_data *d2 = (myfunc_data *) pd;
1779: /* xt = (p1-1); */
1780: xt=vector(1,n);
1781: for (j=1;j<=n;j++) xt[j]=p1[j-1]; /* xt[1]=p1[0] */
1782:
1783: fret=(d2->function)(xt); /* p xt[1]@8 is fine */
1784: /* fret=(*func)(xt); /\* p xt[1]@8 is fine *\/ */
1785: printf("Function = %.12lf ",fret);
1786: for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]);
1787: printf("\n");
1788: free_vector(xt,1,n);
1789: return fret;
1790: }
1791: #endif
1.126 brouard 1792:
1793: /*************** log-likelihood *************/
1794: double func( double *x)
1795: {
1796: int i, ii, j, k, mi, d, kk;
1.131 brouard 1797: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 1798: double **out;
1799: double sw; /* Sum of weights */
1800: double lli; /* Individual log likelihood */
1801: int s1, s2;
1802: double bbh, survp;
1803: long ipmx;
1804: /*extern weight */
1805: /* We are differentiating ll according to initial status */
1806: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
1807: /*for(i=1;i<imx;i++)
1808: printf(" %d\n",s[4][i]);
1809: */
1.162 brouard 1810:
1811: ++countcallfunc;
1812:
1.126 brouard 1813: cov[1]=1.;
1814:
1815: for(k=1; k<=nlstate; k++) ll[k]=0.;
1816:
1817: if(mle==1){
1818: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138 brouard 1819: /* Computes the values of the ncovmodel covariates of the model
1820: depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
1821: Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
1822: to be observed in j being in i according to the model.
1823: */
1.145 brouard 1824: for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1825: cov[2+k]=covar[Tvar[k]][i];
1826: }
1.137 brouard 1827: /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4]
1.138 brouard 1828: is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]
1.137 brouard 1829: has been calculated etc */
1.126 brouard 1830: for(mi=1; mi<= wav[i]-1; mi++){
1831: for (ii=1;ii<=nlstate+ndeath;ii++)
1832: for (j=1;j<=nlstate+ndeath;j++){
1833: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1834: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1835: }
1836: for(d=0; d<dh[mi][i]; d++){
1837: newm=savm;
1838: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1839: for (kk=1; kk<=cptcovage;kk++) {
1.137 brouard 1840: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; /* Tage[kk] gives the data-covariate associated with age */
1.126 brouard 1841: }
1842: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1843: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1844: savm=oldm;
1845: oldm=newm;
1846: } /* end mult */
1847:
1848: /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
1849: /* But now since version 0.9 we anticipate for bias at large stepm.
1850: * If stepm is larger than one month (smallest stepm) and if the exact delay
1851: * (in months) between two waves is not a multiple of stepm, we rounded to
1852: * the nearest (and in case of equal distance, to the lowest) interval but now
1853: * we keep into memory the bias bh[mi][i] and also the previous matrix product
1854: * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
1855: * probability in order to take into account the bias as a fraction of the way
1856: * from savm to out if bh is negative or even beyond if bh is positive. bh varies
1857: * -stepm/2 to stepm/2 .
1858: * For stepm=1 the results are the same as for previous versions of Imach.
1859: * For stepm > 1 the results are less biased than in previous versions.
1860: */
1861: s1=s[mw[mi][i]][i];
1862: s2=s[mw[mi+1][i]][i];
1863: bbh=(double)bh[mi][i]/(double)stepm;
1864: /* bias bh is positive if real duration
1865: * is higher than the multiple of stepm and negative otherwise.
1866: */
1867: /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
1868: if( s2 > nlstate){
1869: /* i.e. if s2 is a death state and if the date of death is known
1870: then the contribution to the likelihood is the probability to
1871: die between last step unit time and current step unit time,
1872: which is also equal to probability to die before dh
1873: minus probability to die before dh-stepm .
1874: In version up to 0.92 likelihood was computed
1875: as if date of death was unknown. Death was treated as any other
1876: health state: the date of the interview describes the actual state
1877: and not the date of a change in health state. The former idea was
1878: to consider that at each interview the state was recorded
1879: (healthy, disable or death) and IMaCh was corrected; but when we
1880: introduced the exact date of death then we should have modified
1881: the contribution of an exact death to the likelihood. This new
1882: contribution is smaller and very dependent of the step unit
1883: stepm. It is no more the probability to die between last interview
1884: and month of death but the probability to survive from last
1885: interview up to one month before death multiplied by the
1886: probability to die within a month. Thanks to Chris
1887: Jackson for correcting this bug. Former versions increased
1888: mortality artificially. The bad side is that we add another loop
1889: which slows down the processing. The difference can be up to 10%
1890: lower mortality.
1891: */
1892: lli=log(out[s1][s2] - savm[s1][s2]);
1893:
1894:
1895: } else if (s2==-2) {
1896: for (j=1,survp=0. ; j<=nlstate; j++)
1897: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1898: /*survp += out[s1][j]; */
1899: lli= log(survp);
1900: }
1901:
1902: else if (s2==-4) {
1903: for (j=3,survp=0. ; j<=nlstate; j++)
1904: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1905: lli= log(survp);
1906: }
1907:
1908: else if (s2==-5) {
1909: for (j=1,survp=0. ; j<=2; j++)
1910: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1911: lli= log(survp);
1912: }
1913:
1914: else{
1915: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1916: /* 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 */
1917: }
1918: /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
1919: /*if(lli ==000.0)*/
1920: /*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); */
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==2){
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]>(double)1.e-8 ?log((1.+bbh)*out[s1][s2]- bbh*(savm[s1][s2])):log((1.+bbh)*out[s1][s2])); /* linear interpolation */
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==3){ /* exponential 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: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1972: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1973: savm=oldm;
1974: oldm=newm;
1975: } /* end mult */
1976:
1977: s1=s[mw[mi][i]][i];
1978: s2=s[mw[mi+1][i]][i];
1979: bbh=(double)bh[mi][i]/(double)stepm;
1980: 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 */
1981: ipmx +=1;
1982: sw += weight[i];
1983: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1984: } /* end of wave */
1985: } /* end of individual */
1986: }else if (mle==4){ /* ml=4 no inter-extrapolation */
1987: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1988: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1989: for(mi=1; mi<= wav[i]-1; mi++){
1990: for (ii=1;ii<=nlstate+ndeath;ii++)
1991: for (j=1;j<=nlstate+ndeath;j++){
1992: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1993: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1994: }
1995: for(d=0; d<dh[mi][i]; d++){
1996: newm=savm;
1997: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1998: for (kk=1; kk<=cptcovage;kk++) {
1999: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2000: }
2001:
2002: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2003: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2004: savm=oldm;
2005: oldm=newm;
2006: } /* end mult */
2007:
2008: s1=s[mw[mi][i]][i];
2009: s2=s[mw[mi+1][i]][i];
2010: if( s2 > nlstate){
2011: lli=log(out[s1][s2] - savm[s1][s2]);
2012: }else{
2013: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2014: }
2015: ipmx +=1;
2016: sw += weight[i];
2017: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2018: /* 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]); */
2019: } /* end of wave */
2020: } /* end of individual */
2021: }else{ /* ml=5 no inter-extrapolation no jackson =0.8a */
2022: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2023: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2024: for(mi=1; mi<= wav[i]-1; mi++){
2025: for (ii=1;ii<=nlstate+ndeath;ii++)
2026: for (j=1;j<=nlstate+ndeath;j++){
2027: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2028: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2029: }
2030: for(d=0; d<dh[mi][i]; d++){
2031: newm=savm;
2032: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2033: for (kk=1; kk<=cptcovage;kk++) {
2034: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2035: }
2036:
2037: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2038: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2039: savm=oldm;
2040: oldm=newm;
2041: } /* end mult */
2042:
2043: s1=s[mw[mi][i]][i];
2044: s2=s[mw[mi+1][i]][i];
2045: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2046: ipmx +=1;
2047: sw += weight[i];
2048: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2049: /*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]);*/
2050: } /* end of wave */
2051: } /* end of individual */
2052: } /* End of if */
2053: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2054: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2055: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2056: return -l;
2057: }
2058:
2059: /*************** log-likelihood *************/
2060: double funcone( double *x)
2061: {
2062: /* Same as likeli but slower because of a lot of printf and if */
2063: int i, ii, j, k, mi, d, kk;
1.131 brouard 2064: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 2065: double **out;
2066: double lli; /* Individual log likelihood */
2067: double llt;
2068: int s1, s2;
2069: double bbh, survp;
2070: /*extern weight */
2071: /* We are differentiating ll according to initial status */
2072: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2073: /*for(i=1;i<imx;i++)
2074: printf(" %d\n",s[4][i]);
2075: */
2076: cov[1]=1.;
2077:
2078: for(k=1; k<=nlstate; k++) ll[k]=0.;
2079:
2080: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2081: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2082: for(mi=1; mi<= wav[i]-1; mi++){
2083: for (ii=1;ii<=nlstate+ndeath;ii++)
2084: for (j=1;j<=nlstate+ndeath;j++){
2085: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2086: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2087: }
2088: for(d=0; d<dh[mi][i]; d++){
2089: newm=savm;
2090: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2091: for (kk=1; kk<=cptcovage;kk++) {
2092: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2093: }
1.145 brouard 2094: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126 brouard 2095: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2096: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145 brouard 2097: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
2098: /* 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126 brouard 2099: savm=oldm;
2100: oldm=newm;
2101: } /* end mult */
2102:
2103: s1=s[mw[mi][i]][i];
2104: s2=s[mw[mi+1][i]][i];
2105: bbh=(double)bh[mi][i]/(double)stepm;
2106: /* bias is positive if real duration
2107: * is higher than the multiple of stepm and negative otherwise.
2108: */
2109: if( s2 > nlstate && (mle <5) ){ /* Jackson */
2110: lli=log(out[s1][s2] - savm[s1][s2]);
2111: } else if (s2==-2) {
2112: for (j=1,survp=0. ; j<=nlstate; j++)
2113: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2114: lli= log(survp);
2115: }else if (mle==1){
2116: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2117: } else if(mle==2){
2118: 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 */
2119: } else if(mle==3){ /* exponential inter-extrapolation */
2120: 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 */
2121: } else if (mle==4){ /* mle=4 no inter-extrapolation */
2122: lli=log(out[s1][s2]); /* Original formula */
1.136 brouard 2123: } else{ /* mle=0 back to 1 */
2124: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2125: /*lli=log(out[s1][s2]); */ /* Original formula */
1.126 brouard 2126: } /* End of if */
2127: ipmx +=1;
2128: sw += weight[i];
2129: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132 brouard 2130: /*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 2131: if(globpr){
1.141 brouard 2132: fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
1.126 brouard 2133: %11.6f %11.6f %11.6f ", \
2134: num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
2135: 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
2136: for(k=1,llt=0.,l=0.; k<=nlstate; k++){
2137: llt +=ll[k]*gipmx/gsw;
2138: fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
2139: }
2140: fprintf(ficresilk," %10.6f\n", -llt);
2141: }
2142: } /* end of wave */
2143: } /* end of individual */
2144: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2145: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2146: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2147: if(globpr==0){ /* First time we count the contributions and weights */
2148: gipmx=ipmx;
2149: gsw=sw;
2150: }
2151: return -l;
2152: }
2153:
2154:
2155: /*************** function likelione ***********/
2156: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
2157: {
2158: /* This routine should help understanding what is done with
2159: the selection of individuals/waves and
2160: to check the exact contribution to the likelihood.
2161: Plotting could be done.
2162: */
2163: int k;
2164:
2165: if(*globpri !=0){ /* Just counts and sums, no printings */
2166: strcpy(fileresilk,"ilk");
2167: strcat(fileresilk,fileres);
2168: if((ficresilk=fopen(fileresilk,"w"))==NULL) {
2169: printf("Problem with resultfile: %s\n", fileresilk);
2170: fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
2171: }
2172: 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");
2173: fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
2174: /* i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
2175: for(k=1; k<=nlstate; k++)
2176: fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
2177: fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
2178: }
2179:
2180: *fretone=(*funcone)(p);
2181: if(*globpri !=0){
2182: fclose(ficresilk);
2183: fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
2184: fflush(fichtm);
2185: }
2186: return;
2187: }
2188:
2189:
2190: /*********** Maximum Likelihood Estimation ***************/
2191:
2192: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
2193: {
1.165 brouard 2194: int i,j, iter=0;
1.126 brouard 2195: double **xi;
2196: double fret;
2197: double fretone; /* Only one call to likelihood */
2198: /* char filerespow[FILENAMELENGTH];*/
1.162 brouard 2199:
2200: #ifdef NLOPT
2201: int creturn;
2202: nlopt_opt opt;
2203: /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
2204: double *lb;
2205: double minf; /* the minimum objective value, upon return */
2206: double * p1; /* Shifted parameters from 0 instead of 1 */
2207: myfunc_data dinst, *d = &dinst;
2208: #endif
2209:
2210:
1.126 brouard 2211: xi=matrix(1,npar,1,npar);
2212: for (i=1;i<=npar;i++)
2213: for (j=1;j<=npar;j++)
2214: xi[i][j]=(i==j ? 1.0 : 0.0);
2215: printf("Powell\n"); fprintf(ficlog,"Powell\n");
2216: strcpy(filerespow,"pow");
2217: strcat(filerespow,fileres);
2218: if((ficrespow=fopen(filerespow,"w"))==NULL) {
2219: printf("Problem with resultfile: %s\n", filerespow);
2220: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
2221: }
2222: fprintf(ficrespow,"# Powell\n# iter -2*LL");
2223: for (i=1;i<=nlstate;i++)
2224: for(j=1;j<=nlstate+ndeath;j++)
2225: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
2226: fprintf(ficrespow,"\n");
1.162 brouard 2227: #ifdef POWELL
1.126 brouard 2228: powell(p,xi,npar,ftol,&iter,&fret,func);
1.162 brouard 2229: #endif
1.126 brouard 2230:
1.162 brouard 2231: #ifdef NLOPT
2232: #ifdef NEWUOA
2233: opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
2234: #else
2235: opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
2236: #endif
2237: lb=vector(0,npar-1);
2238: for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
2239: nlopt_set_lower_bounds(opt, lb);
2240: nlopt_set_initial_step1(opt, 0.1);
2241:
2242: p1= (p+1); /* p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
2243: d->function = func;
2244: printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
2245: nlopt_set_min_objective(opt, myfunc, d);
2246: nlopt_set_xtol_rel(opt, ftol);
2247: if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
2248: printf("nlopt failed! %d\n",creturn);
2249: }
2250: else {
2251: printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
2252: printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
2253: iter=1; /* not equal */
2254: }
2255: nlopt_destroy(opt);
2256: #endif
1.126 brouard 2257: free_matrix(xi,1,npar,1,npar);
2258: fclose(ficrespow);
1.162 brouard 2259: printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2260: fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2261: fprintf(ficres,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126 brouard 2262:
2263: }
2264:
2265: /**** Computes Hessian and covariance matrix ***/
2266: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
2267: {
2268: double **a,**y,*x,pd;
2269: double **hess;
1.164 brouard 2270: int i, j;
1.126 brouard 2271: int *indx;
2272:
2273: double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
2274: double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
2275: void lubksb(double **a, int npar, int *indx, double b[]) ;
2276: void ludcmp(double **a, int npar, int *indx, double *d) ;
2277: double gompertz(double p[]);
2278: hess=matrix(1,npar,1,npar);
2279:
2280: printf("\nCalculation of the hessian matrix. Wait...\n");
2281: fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
2282: for (i=1;i<=npar;i++){
2283: printf("%d",i);fflush(stdout);
2284: fprintf(ficlog,"%d",i);fflush(ficlog);
2285:
2286: hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
2287:
2288: /* printf(" %f ",p[i]);
2289: printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
2290: }
2291:
2292: for (i=1;i<=npar;i++) {
2293: for (j=1;j<=npar;j++) {
2294: if (j>i) {
2295: printf(".%d%d",i,j);fflush(stdout);
2296: fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
2297: hess[i][j]=hessij(p,delti,i,j,func,npar);
2298:
2299: hess[j][i]=hess[i][j];
2300: /*printf(" %lf ",hess[i][j]);*/
2301: }
2302: }
2303: }
2304: printf("\n");
2305: fprintf(ficlog,"\n");
2306:
2307: printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
2308: fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
2309:
2310: a=matrix(1,npar,1,npar);
2311: y=matrix(1,npar,1,npar);
2312: x=vector(1,npar);
2313: indx=ivector(1,npar);
2314: for (i=1;i<=npar;i++)
2315: for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
2316: ludcmp(a,npar,indx,&pd);
2317:
2318: for (j=1;j<=npar;j++) {
2319: for (i=1;i<=npar;i++) x[i]=0;
2320: x[j]=1;
2321: lubksb(a,npar,indx,x);
2322: for (i=1;i<=npar;i++){
2323: matcov[i][j]=x[i];
2324: }
2325: }
2326:
2327: printf("\n#Hessian matrix#\n");
2328: fprintf(ficlog,"\n#Hessian matrix#\n");
2329: for (i=1;i<=npar;i++) {
2330: for (j=1;j<=npar;j++) {
2331: printf("%.3e ",hess[i][j]);
2332: fprintf(ficlog,"%.3e ",hess[i][j]);
2333: }
2334: printf("\n");
2335: fprintf(ficlog,"\n");
2336: }
2337:
2338: /* Recompute Inverse */
2339: for (i=1;i<=npar;i++)
2340: for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
2341: ludcmp(a,npar,indx,&pd);
2342:
2343: /* printf("\n#Hessian matrix recomputed#\n");
2344:
2345: for (j=1;j<=npar;j++) {
2346: for (i=1;i<=npar;i++) x[i]=0;
2347: x[j]=1;
2348: lubksb(a,npar,indx,x);
2349: for (i=1;i<=npar;i++){
2350: y[i][j]=x[i];
2351: printf("%.3e ",y[i][j]);
2352: fprintf(ficlog,"%.3e ",y[i][j]);
2353: }
2354: printf("\n");
2355: fprintf(ficlog,"\n");
2356: }
2357: */
2358:
2359: free_matrix(a,1,npar,1,npar);
2360: free_matrix(y,1,npar,1,npar);
2361: free_vector(x,1,npar);
2362: free_ivector(indx,1,npar);
2363: free_matrix(hess,1,npar,1,npar);
2364:
2365:
2366: }
2367:
2368: /*************** hessian matrix ****************/
2369: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
2370: {
2371: int i;
2372: int l=1, lmax=20;
2373: double k1,k2;
1.132 brouard 2374: double p2[MAXPARM+1]; /* identical to x */
1.126 brouard 2375: double res;
2376: double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
2377: double fx;
2378: int k=0,kmax=10;
2379: double l1;
2380:
2381: fx=func(x);
2382: for (i=1;i<=npar;i++) p2[i]=x[i];
1.145 brouard 2383: for(l=0 ; l <=lmax; l++){ /* Enlarging the zone around the Maximum */
1.126 brouard 2384: l1=pow(10,l);
2385: delts=delt;
2386: for(k=1 ; k <kmax; k=k+1){
2387: delt = delta*(l1*k);
2388: p2[theta]=x[theta] +delt;
1.145 brouard 2389: k1=func(p2)-fx; /* Might be negative if too close to the theoretical maximum */
1.126 brouard 2390: p2[theta]=x[theta]-delt;
2391: k2=func(p2)-fx;
2392: /*res= (k1-2.0*fx+k2)/delt/delt; */
2393: res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
2394:
1.132 brouard 2395: #ifdef DEBUGHESS
1.126 brouard 2396: 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);
2397: 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);
2398: #endif
2399: /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
2400: if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
2401: k=kmax;
2402: }
2403: else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164 brouard 2404: k=kmax; l=lmax*10;
1.126 brouard 2405: }
2406: else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
2407: delts=delt;
2408: }
2409: }
2410: }
2411: delti[theta]=delts;
2412: return res;
2413:
2414: }
2415:
2416: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
2417: {
2418: int i;
1.164 brouard 2419: int l=1, lmax=20;
1.126 brouard 2420: double k1,k2,k3,k4,res,fx;
1.132 brouard 2421: double p2[MAXPARM+1];
1.126 brouard 2422: int k;
2423:
2424: fx=func(x);
2425: for (k=1; k<=2; k++) {
2426: for (i=1;i<=npar;i++) p2[i]=x[i];
2427: p2[thetai]=x[thetai]+delti[thetai]/k;
2428: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2429: k1=func(p2)-fx;
2430:
2431: p2[thetai]=x[thetai]+delti[thetai]/k;
2432: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2433: k2=func(p2)-fx;
2434:
2435: p2[thetai]=x[thetai]-delti[thetai]/k;
2436: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2437: k3=func(p2)-fx;
2438:
2439: p2[thetai]=x[thetai]-delti[thetai]/k;
2440: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2441: k4=func(p2)-fx;
2442: res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
2443: #ifdef DEBUG
2444: 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);
2445: 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);
2446: #endif
2447: }
2448: return res;
2449: }
2450:
2451: /************** Inverse of matrix **************/
2452: void ludcmp(double **a, int n, int *indx, double *d)
2453: {
2454: int i,imax,j,k;
2455: double big,dum,sum,temp;
2456: double *vv;
2457:
2458: vv=vector(1,n);
2459: *d=1.0;
2460: for (i=1;i<=n;i++) {
2461: big=0.0;
2462: for (j=1;j<=n;j++)
2463: if ((temp=fabs(a[i][j])) > big) big=temp;
2464: if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
2465: vv[i]=1.0/big;
2466: }
2467: for (j=1;j<=n;j++) {
2468: for (i=1;i<j;i++) {
2469: sum=a[i][j];
2470: for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
2471: a[i][j]=sum;
2472: }
2473: big=0.0;
2474: for (i=j;i<=n;i++) {
2475: sum=a[i][j];
2476: for (k=1;k<j;k++)
2477: sum -= a[i][k]*a[k][j];
2478: a[i][j]=sum;
2479: if ( (dum=vv[i]*fabs(sum)) >= big) {
2480: big=dum;
2481: imax=i;
2482: }
2483: }
2484: if (j != imax) {
2485: for (k=1;k<=n;k++) {
2486: dum=a[imax][k];
2487: a[imax][k]=a[j][k];
2488: a[j][k]=dum;
2489: }
2490: *d = -(*d);
2491: vv[imax]=vv[j];
2492: }
2493: indx[j]=imax;
2494: if (a[j][j] == 0.0) a[j][j]=TINY;
2495: if (j != n) {
2496: dum=1.0/(a[j][j]);
2497: for (i=j+1;i<=n;i++) a[i][j] *= dum;
2498: }
2499: }
2500: free_vector(vv,1,n); /* Doesn't work */
2501: ;
2502: }
2503:
2504: void lubksb(double **a, int n, int *indx, double b[])
2505: {
2506: int i,ii=0,ip,j;
2507: double sum;
2508:
2509: for (i=1;i<=n;i++) {
2510: ip=indx[i];
2511: sum=b[ip];
2512: b[ip]=b[i];
2513: if (ii)
2514: for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
2515: else if (sum) ii=i;
2516: b[i]=sum;
2517: }
2518: for (i=n;i>=1;i--) {
2519: sum=b[i];
2520: for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
2521: b[i]=sum/a[i][i];
2522: }
2523: }
2524:
2525: void pstamp(FILE *fichier)
2526: {
2527: fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
2528: }
2529:
2530: /************ Frequencies ********************/
2531: 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[])
2532: { /* Some frequencies */
2533:
1.164 brouard 2534: int i, m, jk, j1, bool, z1,j;
1.126 brouard 2535: int first;
2536: double ***freq; /* Frequencies */
2537: double *pp, **prop;
2538: double pos,posprop, k2, dateintsum=0,k2cpt=0;
2539: char fileresp[FILENAMELENGTH];
2540:
2541: pp=vector(1,nlstate);
2542: prop=matrix(1,nlstate,iagemin,iagemax+3);
2543: strcpy(fileresp,"p");
2544: strcat(fileresp,fileres);
2545: if((ficresp=fopen(fileresp,"w"))==NULL) {
2546: printf("Problem with prevalence resultfile: %s\n", fileresp);
2547: fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
2548: exit(0);
2549: }
2550: freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
2551: j1=0;
2552:
2553: j=cptcoveff;
2554: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2555:
2556: first=1;
2557:
1.169 brouard 2558: /* for(k1=1; k1<=j ; k1++){ */ /* Loop on covariates */
2559: /* for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
2560: /* j1++; */
1.145 brouard 2561: for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126 brouard 2562: /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
2563: scanf("%d", i);*/
2564: for (i=-5; i<=nlstate+ndeath; i++)
2565: for (jk=-5; jk<=nlstate+ndeath; jk++)
2566: for(m=iagemin; m <= iagemax+3; m++)
2567: freq[i][jk][m]=0;
1.143 brouard 2568:
2569: for (i=1; i<=nlstate; i++)
2570: for(m=iagemin; m <= iagemax+3; m++)
2571: prop[i][m]=0;
1.126 brouard 2572:
2573: dateintsum=0;
2574: k2cpt=0;
2575: for (i=1; i<=imx; i++) {
2576: bool=1;
1.144 brouard 2577: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
2578: for (z1=1; z1<=cptcoveff; z1++)
2579: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
1.145 brouard 2580: /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144 brouard 2581: bool=0;
1.145 brouard 2582: /* 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",
2583: bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
2584: j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
1.144 brouard 2585: /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
2586: }
1.126 brouard 2587: }
1.144 brouard 2588:
1.126 brouard 2589: if (bool==1){
2590: for(m=firstpass; m<=lastpass; m++){
2591: k2=anint[m][i]+(mint[m][i]/12.);
2592: /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
2593: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2594: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2595: if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
2596: if (m<lastpass) {
2597: freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
2598: freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
2599: }
2600:
2601: if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
2602: dateintsum=dateintsum+k2;
2603: k2cpt++;
2604: }
2605: /*}*/
2606: }
2607: }
1.145 brouard 2608: } /* end i */
1.126 brouard 2609:
2610: /* fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
2611: pstamp(ficresp);
2612: if (cptcovn>0) {
2613: fprintf(ficresp, "\n#********** Variable ");
2614: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2615: fprintf(ficresp, "**********\n#");
1.143 brouard 2616: fprintf(ficlog, "\n#********** Variable ");
2617: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2618: fprintf(ficlog, "**********\n#");
1.126 brouard 2619: }
2620: for(i=1; i<=nlstate;i++)
2621: fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
2622: fprintf(ficresp, "\n");
2623:
2624: for(i=iagemin; i <= iagemax+3; i++){
2625: if(i==iagemax+3){
2626: fprintf(ficlog,"Total");
2627: }else{
2628: if(first==1){
2629: first=0;
2630: printf("See log file for details...\n");
2631: }
2632: fprintf(ficlog,"Age %d", i);
2633: }
2634: for(jk=1; jk <=nlstate ; jk++){
2635: for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
2636: pp[jk] += freq[jk][m][i];
2637: }
2638: for(jk=1; jk <=nlstate ; jk++){
2639: for(m=-1, pos=0; m <=0 ; m++)
2640: pos += freq[jk][m][i];
2641: if(pp[jk]>=1.e-10){
2642: if(first==1){
1.132 brouard 2643: printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126 brouard 2644: }
2645: fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
2646: }else{
2647: if(first==1)
2648: printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2649: fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2650: }
2651: }
2652:
2653: for(jk=1; jk <=nlstate ; jk++){
2654: for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
2655: pp[jk] += freq[jk][m][i];
2656: }
2657: for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
2658: pos += pp[jk];
2659: posprop += prop[jk][i];
2660: }
2661: for(jk=1; jk <=nlstate ; jk++){
2662: if(pos>=1.e-5){
2663: if(first==1)
2664: printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2665: fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2666: }else{
2667: if(first==1)
2668: printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2669: fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2670: }
2671: if( i <= iagemax){
2672: if(pos>=1.e-5){
2673: fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
2674: /*probs[i][jk][j1]= pp[jk]/pos;*/
2675: /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
2676: }
2677: else
2678: fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
2679: }
2680: }
2681:
2682: for(jk=-1; jk <=nlstate+ndeath; jk++)
2683: for(m=-1; m <=nlstate+ndeath; m++)
2684: if(freq[jk][m][i] !=0 ) {
2685: if(first==1)
2686: printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
2687: fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
2688: }
2689: if(i <= iagemax)
2690: fprintf(ficresp,"\n");
2691: if(first==1)
2692: printf("Others in log...\n");
2693: fprintf(ficlog,"\n");
2694: }
1.145 brouard 2695: /*}*/
1.126 brouard 2696: }
2697: dateintmean=dateintsum/k2cpt;
2698:
2699: fclose(ficresp);
2700: free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
2701: free_vector(pp,1,nlstate);
2702: free_matrix(prop,1,nlstate,iagemin, iagemax+3);
2703: /* End of Freq */
2704: }
2705:
2706: /************ Prevalence ********************/
2707: 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)
2708: {
2709: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
2710: in each health status at the date of interview (if between dateprev1 and dateprev2).
2711: We still use firstpass and lastpass as another selection.
2712: */
2713:
1.164 brouard 2714: int i, m, jk, j1, bool, z1,j;
2715:
2716: double **prop;
2717: double posprop;
1.126 brouard 2718: double y2; /* in fractional years */
2719: int iagemin, iagemax;
1.145 brouard 2720: int first; /** to stop verbosity which is redirected to log file */
1.126 brouard 2721:
2722: iagemin= (int) agemin;
2723: iagemax= (int) agemax;
2724: /*pp=vector(1,nlstate);*/
2725: prop=matrix(1,nlstate,iagemin,iagemax+3);
2726: /* freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
2727: j1=0;
2728:
1.145 brouard 2729: /*j=cptcoveff;*/
1.126 brouard 2730: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2731:
1.145 brouard 2732: first=1;
2733: for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
2734: /*for(i1=1; i1<=ncodemax[k1];i1++){
2735: j1++;*/
1.126 brouard 2736:
2737: for (i=1; i<=nlstate; i++)
2738: for(m=iagemin; m <= iagemax+3; m++)
2739: prop[i][m]=0.0;
2740:
2741: for (i=1; i<=imx; i++) { /* Each individual */
2742: bool=1;
2743: if (cptcovn>0) {
2744: for (z1=1; z1<=cptcoveff; z1++)
2745: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
2746: bool=0;
2747: }
2748: if (bool==1) {
2749: for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
2750: y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
2751: if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
2752: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2753: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2754: 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);
2755: if (s[m][i]>0 && s[m][i]<=nlstate) {
2756: /*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]]);*/
2757: prop[s[m][i]][(int)agev[m][i]] += weight[i];
2758: prop[s[m][i]][iagemax+3] += weight[i];
2759: }
2760: }
2761: } /* end selection of waves */
2762: }
2763: }
2764: for(i=iagemin; i <= iagemax+3; i++){
2765: for(jk=1,posprop=0; jk <=nlstate ; jk++) {
2766: posprop += prop[jk][i];
2767: }
1.145 brouard 2768:
1.126 brouard 2769: for(jk=1; jk <=nlstate ; jk++){
2770: if( i <= iagemax){
2771: if(posprop>=1.e-5){
2772: probs[i][jk][j1]= prop[jk][i]/posprop;
1.145 brouard 2773: } else{
2774: if(first==1){
2775: first=0;
2776: 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]);
2777: }
2778: }
1.126 brouard 2779: }
2780: }/* end jk */
2781: }/* end i */
1.145 brouard 2782: /*} *//* end i1 */
2783: } /* end j1 */
1.126 brouard 2784:
2785: /* free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
2786: /*free_vector(pp,1,nlstate);*/
2787: free_matrix(prop,1,nlstate, iagemin,iagemax+3);
2788: } /* End of prevalence */
2789:
2790: /************* Waves Concatenation ***************/
2791:
2792: 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)
2793: {
2794: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
2795: Death is a valid wave (if date is known).
2796: mw[mi][i] is the mi (mi=1 to wav[i]) effective wave of individual i
2797: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
2798: and mw[mi+1][i]. dh depends on stepm.
2799: */
2800:
2801: int i, mi, m;
2802: /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
2803: double sum=0., jmean=0.;*/
2804: int first;
2805: int j, k=0,jk, ju, jl;
2806: double sum=0.;
2807: first=0;
1.164 brouard 2808: jmin=100000;
1.126 brouard 2809: jmax=-1;
2810: jmean=0.;
2811: for(i=1; i<=imx; i++){
2812: mi=0;
2813: m=firstpass;
2814: while(s[m][i] <= nlstate){
2815: if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
2816: mw[++mi][i]=m;
2817: if(m >=lastpass)
2818: break;
2819: else
2820: m++;
2821: }/* end while */
2822: if (s[m][i] > nlstate){
2823: mi++; /* Death is another wave */
2824: /* if(mi==0) never been interviewed correctly before death */
2825: /* Only death is a correct wave */
2826: mw[mi][i]=m;
2827: }
2828:
2829: wav[i]=mi;
2830: if(mi==0){
2831: nbwarn++;
2832: if(first==0){
2833: printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
2834: first=1;
2835: }
2836: if(first==1){
2837: fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
2838: }
2839: } /* end mi==0 */
2840: } /* End individuals */
2841:
2842: for(i=1; i<=imx; i++){
2843: for(mi=1; mi<wav[i];mi++){
2844: if (stepm <=0)
2845: dh[mi][i]=1;
2846: else{
2847: if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
2848: if (agedc[i] < 2*AGESUP) {
2849: j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
2850: if(j==0) j=1; /* Survives at least one month after exam */
2851: else if(j<0){
2852: nberr++;
2853: 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]);
2854: j=1; /* Temporary Dangerous patch */
2855: 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);
2856: 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]);
2857: 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);
2858: }
2859: k=k+1;
2860: if (j >= jmax){
2861: jmax=j;
2862: ijmax=i;
2863: }
2864: if (j <= jmin){
2865: jmin=j;
2866: ijmin=i;
2867: }
2868: sum=sum+j;
2869: /*if (j<0) printf("j=%d num=%d \n",j,i);*/
2870: /* printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
2871: }
2872: }
2873: else{
2874: j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
2875: /* 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]); */
2876:
2877: k=k+1;
2878: if (j >= jmax) {
2879: jmax=j;
2880: ijmax=i;
2881: }
2882: else if (j <= jmin){
2883: jmin=j;
2884: ijmin=i;
2885: }
2886: /* if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
2887: /*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]);*/
2888: if(j<0){
2889: nberr++;
2890: 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]);
2891: 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]);
2892: }
2893: sum=sum+j;
2894: }
2895: jk= j/stepm;
2896: jl= j -jk*stepm;
2897: ju= j -(jk+1)*stepm;
2898: if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
2899: if(jl==0){
2900: dh[mi][i]=jk;
2901: bh[mi][i]=0;
2902: }else{ /* We want a negative bias in order to only have interpolation ie
1.136 brouard 2903: * to avoid the price of an extra matrix product in likelihood */
1.126 brouard 2904: dh[mi][i]=jk+1;
2905: bh[mi][i]=ju;
2906: }
2907: }else{
2908: if(jl <= -ju){
2909: dh[mi][i]=jk;
2910: bh[mi][i]=jl; /* bias is positive if real duration
2911: * is higher than the multiple of stepm and negative otherwise.
2912: */
2913: }
2914: else{
2915: dh[mi][i]=jk+1;
2916: bh[mi][i]=ju;
2917: }
2918: if(dh[mi][i]==0){
2919: dh[mi][i]=1; /* At least one step */
2920: bh[mi][i]=ju; /* At least one step */
2921: /* 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);*/
2922: }
2923: } /* end if mle */
2924: }
2925: } /* end wave */
2926: }
2927: jmean=sum/k;
2928: 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 2929: 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 2930: }
2931:
2932: /*********** Tricode ****************************/
1.145 brouard 2933: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126 brouard 2934: {
1.144 brouard 2935: /**< Uses cptcovn+2*cptcovprod as the number of covariates */
2936: /* Tvar[i]=atoi(stre); find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1
1.169 brouard 2937: * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145 brouard 2938: * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.169 brouard 2939: * nbcode[Tvar[j]][1]=
1.144 brouard 2940: */
1.130 brouard 2941:
1.145 brouard 2942: int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136 brouard 2943: int modmaxcovj=0; /* Modality max of covariates j */
1.145 brouard 2944: int cptcode=0; /* Modality max of covariates j */
2945: int modmincovj=0; /* Modality min of covariates j */
2946:
2947:
1.126 brouard 2948: cptcoveff=0;
2949:
1.145 brouard 2950: for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.144 brouard 2951: for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126 brouard 2952:
1.145 brouard 2953: /* Loop on covariates without age and products */
2954: for (j=1; j<=(cptcovs); j++) { /* model V1 + V2*age+ V3 + V3*V4 : V1 + V3 = 2 only */
2955: for (i=1; i<=imx; i++) { /* Lopp on individuals: reads the data file to get the maximum value of the
1.136 brouard 2956: modality of this covariate Vj*/
1.145 brouard 2957: ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
2958: * If product of Vn*Vm, still boolean *:
2959: * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
2960: * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0 */
2961: /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136 brouard 2962: modality of the nth covariate of individual i. */
1.145 brouard 2963: if (ij > modmaxcovj)
2964: modmaxcovj=ij;
2965: else if (ij < modmincovj)
2966: modmincovj=ij;
2967: if ((ij < -1) && (ij > NCOVMAX)){
2968: printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
2969: exit(1);
2970: }else
1.136 brouard 2971: Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145 brouard 2972: /* If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126 brouard 2973: /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136 brouard 2974: /* getting the maximum value of the modality of the covariate
2975: (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
2976: female is 1, then modmaxcovj=1.*/
1.126 brouard 2977: }
1.145 brouard 2978: printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
2979: cptcode=modmaxcovj;
1.137 brouard 2980: /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145 brouard 2981: /*for (i=0; i<=cptcode; i++) {*/
2982: for (i=modmincovj; i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
2983: printf("Frequencies of covariates %d V%d %d\n", j, Tvar[j], Ndum[i]);
2984: if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
2985: ncodemax[j]++; /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
2986: }
2987: /* In fact ncodemax[j]=2 (dichotom. variables only) but it could be more for
2988: historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131 brouard 2989: } /* Ndum[-1] number of undefined modalities */
1.126 brouard 2990:
1.136 brouard 2991: /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.145 brouard 2992: /* For covariate j, modalities could be 1, 2, 3, 4. If Ndum[2]=0 ncodemax[j] is not 4 but 3 */
2993: /* If Ndum[3}= 635; Ndum[4]=0; Ndum[5]=0; Ndum[6]=27; Ndum[7]=125;
2994: modmincovj=3; modmaxcovj = 7;
2995: There are only 3 modalities non empty (or 2 if 27 is too few) : ncodemax[j]=3;
2996: which will be coded 0, 1, 2 which in binary on 3-1 digits are 0=00 1=01, 2=10; defining two dummy
2997: variables V1_1 and V1_2.
2998: nbcode[Tvar[j]][ij]=k;
2999: nbcode[Tvar[j]][1]=0;
3000: nbcode[Tvar[j]][2]=1;
3001: nbcode[Tvar[j]][3]=2;
3002: */
3003: ij=1; /* ij is similar to i but can jumps over null modalities */
3004: for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
3005: for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
3006: /*recode from 0 */
1.131 brouard 3007: if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
3008: nbcode[Tvar[j]][ij]=k; /* stores the modality in an array nbcode.
3009: k is a modality. If we have model=V1+V1*sex
3010: then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
1.126 brouard 3011: ij++;
3012: }
3013: if (ij > ncodemax[j]) break;
1.137 brouard 3014: } /* end of loop on */
3015: } /* end of loop on modality */
3016: } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/
3017:
1.145 brouard 3018: for (k=-1; k< maxncov; k++) Ndum[k]=0;
1.137 brouard 3019:
1.145 brouard 3020: for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */
3021: /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
3022: ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
3023: Ndum[ij]++;
3024: }
1.126 brouard 3025:
3026: ij=1;
1.145 brouard 3027: for (i=0; i<= maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
3028: /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126 brouard 3029: if((Ndum[i]!=0) && (i<=ncovcol)){
1.145 brouard 3030: /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
3031: Tvaraff[ij]=i; /*For printing (unclear) */
1.126 brouard 3032: ij++;
1.145 brouard 3033: }else
3034: Tvaraff[ij]=0;
1.126 brouard 3035: }
1.131 brouard 3036: ij--;
1.144 brouard 3037: cptcoveff=ij; /*Number of total covariates*/
1.145 brouard 3038:
1.126 brouard 3039: }
3040:
1.145 brouard 3041:
1.126 brouard 3042: /*********** Health Expectancies ****************/
3043:
1.127 brouard 3044: 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 3045:
3046: {
3047: /* Health expectancies, no variances */
1.164 brouard 3048: int i, j, nhstepm, hstepm, h, nstepm;
1.126 brouard 3049: int nhstepma, nstepma; /* Decreasing with age */
3050: double age, agelim, hf;
3051: double ***p3mat;
3052: double eip;
3053:
3054: pstamp(ficreseij);
3055: fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
3056: fprintf(ficreseij,"# Age");
3057: for(i=1; i<=nlstate;i++){
3058: for(j=1; j<=nlstate;j++){
3059: fprintf(ficreseij," e%1d%1d ",i,j);
3060: }
3061: fprintf(ficreseij," e%1d. ",i);
3062: }
3063: fprintf(ficreseij,"\n");
3064:
3065:
3066: if(estepm < stepm){
3067: printf ("Problem %d lower than %d\n",estepm, stepm);
3068: }
3069: else hstepm=estepm;
3070: /* We compute the life expectancy from trapezoids spaced every estepm months
3071: * This is mainly to measure the difference between two models: for example
3072: * if stepm=24 months pijx are given only every 2 years and by summing them
3073: * we are calculating an estimate of the Life Expectancy assuming a linear
3074: * progression in between and thus overestimating or underestimating according
3075: * to the curvature of the survival function. If, for the same date, we
3076: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3077: * to compare the new estimate of Life expectancy with the same linear
3078: * hypothesis. A more precise result, taking into account a more precise
3079: * curvature will be obtained if estepm is as small as stepm. */
3080:
3081: /* For example we decided to compute the life expectancy with the smallest unit */
3082: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3083: nhstepm is the number of hstepm from age to agelim
3084: nstepm is the number of stepm from age to agelin.
3085: Look at hpijx to understand the reason of that which relies in memory size
3086: and note for a fixed period like estepm months */
3087: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3088: survival function given by stepm (the optimization length). Unfortunately it
3089: means that if the survival funtion is printed only each two years of age and if
3090: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3091: results. So we changed our mind and took the option of the best precision.
3092: */
3093: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3094:
3095: agelim=AGESUP;
3096: /* If stepm=6 months */
3097: /* Computed by stepm unit matrices, product of hstepm matrices, stored
3098: in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
3099:
3100: /* nhstepm age range expressed in number of stepm */
3101: nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3102: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3103: /* if (stepm >= YEARM) hstepm=1;*/
3104: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3105: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3106:
3107: for (age=bage; age<=fage; age ++){
3108: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3109: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3110: /* if (stepm >= YEARM) hstepm=1;*/
3111: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3112:
3113: /* If stepm=6 months */
3114: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3115: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3116:
3117: hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3118:
3119: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3120:
3121: printf("%d|",(int)age);fflush(stdout);
3122: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3123:
3124: /* Computing expectancies */
3125: for(i=1; i<=nlstate;i++)
3126: for(j=1; j<=nlstate;j++)
3127: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3128: eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
3129:
3130: /* 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]);*/
3131:
3132: }
3133:
3134: fprintf(ficreseij,"%3.0f",age );
3135: for(i=1; i<=nlstate;i++){
3136: eip=0;
3137: for(j=1; j<=nlstate;j++){
3138: eip +=eij[i][j][(int)age];
3139: fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
3140: }
3141: fprintf(ficreseij,"%9.4f", eip );
3142: }
3143: fprintf(ficreseij,"\n");
3144:
3145: }
3146: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3147: printf("\n");
3148: fprintf(ficlog,"\n");
3149:
3150: }
3151:
1.127 brouard 3152: 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 3153:
3154: {
3155: /* Covariances of health expectancies eij and of total life expectancies according
3156: to initial status i, ei. .
3157: */
3158: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
3159: int nhstepma, nstepma; /* Decreasing with age */
3160: double age, agelim, hf;
3161: double ***p3matp, ***p3matm, ***varhe;
3162: double **dnewm,**doldm;
3163: double *xp, *xm;
3164: double **gp, **gm;
3165: double ***gradg, ***trgradg;
3166: int theta;
3167:
3168: double eip, vip;
3169:
3170: varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
3171: xp=vector(1,npar);
3172: xm=vector(1,npar);
3173: dnewm=matrix(1,nlstate*nlstate,1,npar);
3174: doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
3175:
3176: pstamp(ficresstdeij);
3177: fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
3178: fprintf(ficresstdeij,"# Age");
3179: for(i=1; i<=nlstate;i++){
3180: for(j=1; j<=nlstate;j++)
3181: fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
3182: fprintf(ficresstdeij," e%1d. ",i);
3183: }
3184: fprintf(ficresstdeij,"\n");
3185:
3186: pstamp(ficrescveij);
3187: fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
3188: fprintf(ficrescveij,"# Age");
3189: for(i=1; i<=nlstate;i++)
3190: for(j=1; j<=nlstate;j++){
3191: cptj= (j-1)*nlstate+i;
3192: for(i2=1; i2<=nlstate;i2++)
3193: for(j2=1; j2<=nlstate;j2++){
3194: cptj2= (j2-1)*nlstate+i2;
3195: if(cptj2 <= cptj)
3196: fprintf(ficrescveij," %1d%1d,%1d%1d",i,j,i2,j2);
3197: }
3198: }
3199: fprintf(ficrescveij,"\n");
3200:
3201: if(estepm < stepm){
3202: printf ("Problem %d lower than %d\n",estepm, stepm);
3203: }
3204: else hstepm=estepm;
3205: /* We compute the life expectancy from trapezoids spaced every estepm months
3206: * This is mainly to measure the difference between two models: for example
3207: * if stepm=24 months pijx are given only every 2 years and by summing them
3208: * we are calculating an estimate of the Life Expectancy assuming a linear
3209: * progression in between and thus overestimating or underestimating according
3210: * to the curvature of the survival function. If, for the same date, we
3211: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3212: * to compare the new estimate of Life expectancy with the same linear
3213: * hypothesis. A more precise result, taking into account a more precise
3214: * curvature will be obtained if estepm is as small as stepm. */
3215:
3216: /* For example we decided to compute the life expectancy with the smallest unit */
3217: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3218: nhstepm is the number of hstepm from age to agelim
3219: nstepm is the number of stepm from age to agelin.
3220: Look at hpijx to understand the reason of that which relies in memory size
3221: and note for a fixed period like estepm months */
3222: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3223: survival function given by stepm (the optimization length). Unfortunately it
3224: means that if the survival funtion is printed only each two years of age and if
3225: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3226: results. So we changed our mind and took the option of the best precision.
3227: */
3228: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3229:
3230: /* If stepm=6 months */
3231: /* nhstepm age range expressed in number of stepm */
3232: agelim=AGESUP;
3233: nstepm=(int) rint((agelim-bage)*YEARM/stepm);
3234: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3235: /* if (stepm >= YEARM) hstepm=1;*/
3236: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3237:
3238: p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3239: p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3240: gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
3241: trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
3242: gp=matrix(0,nhstepm,1,nlstate*nlstate);
3243: gm=matrix(0,nhstepm,1,nlstate*nlstate);
3244:
3245: for (age=bage; age<=fage; age ++){
3246: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3247: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3248: /* if (stepm >= YEARM) hstepm=1;*/
3249: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3250:
3251: /* If stepm=6 months */
3252: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3253: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3254:
3255: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3256:
3257: /* Computing Variances of health expectancies */
3258: /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
3259: decrease memory allocation */
3260: for(theta=1; theta <=npar; theta++){
3261: for(i=1; i<=npar; i++){
3262: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3263: xm[i] = x[i] - (i==theta ?delti[theta]:0);
3264: }
3265: hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);
3266: hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);
3267:
3268: for(j=1; j<= nlstate; j++){
3269: for(i=1; i<=nlstate; i++){
3270: for(h=0; h<=nhstepm-1; h++){
3271: gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
3272: gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
3273: }
3274: }
3275: }
3276:
3277: for(ij=1; ij<= nlstate*nlstate; ij++)
3278: for(h=0; h<=nhstepm-1; h++){
3279: gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
3280: }
3281: }/* End theta */
3282:
3283:
3284: for(h=0; h<=nhstepm-1; h++)
3285: for(j=1; j<=nlstate*nlstate;j++)
3286: for(theta=1; theta <=npar; theta++)
3287: trgradg[h][j][theta]=gradg[h][theta][j];
3288:
3289:
3290: for(ij=1;ij<=nlstate*nlstate;ij++)
3291: for(ji=1;ji<=nlstate*nlstate;ji++)
3292: varhe[ij][ji][(int)age] =0.;
3293:
3294: printf("%d|",(int)age);fflush(stdout);
3295: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3296: for(h=0;h<=nhstepm-1;h++){
3297: for(k=0;k<=nhstepm-1;k++){
3298: matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
3299: matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
3300: for(ij=1;ij<=nlstate*nlstate;ij++)
3301: for(ji=1;ji<=nlstate*nlstate;ji++)
3302: varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
3303: }
3304: }
3305:
3306: /* Computing expectancies */
3307: hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3308: for(i=1; i<=nlstate;i++)
3309: for(j=1; j<=nlstate;j++)
3310: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3311: eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
3312:
3313: /* 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]);*/
3314:
3315: }
3316:
3317: fprintf(ficresstdeij,"%3.0f",age );
3318: for(i=1; i<=nlstate;i++){
3319: eip=0.;
3320: vip=0.;
3321: for(j=1; j<=nlstate;j++){
3322: eip += eij[i][j][(int)age];
3323: for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
3324: vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
3325: fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
3326: }
3327: fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
3328: }
3329: fprintf(ficresstdeij,"\n");
3330:
3331: fprintf(ficrescveij,"%3.0f",age );
3332: for(i=1; i<=nlstate;i++)
3333: for(j=1; j<=nlstate;j++){
3334: cptj= (j-1)*nlstate+i;
3335: for(i2=1; i2<=nlstate;i2++)
3336: for(j2=1; j2<=nlstate;j2++){
3337: cptj2= (j2-1)*nlstate+i2;
3338: if(cptj2 <= cptj)
3339: fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
3340: }
3341: }
3342: fprintf(ficrescveij,"\n");
3343:
3344: }
3345: free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
3346: free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
3347: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
3348: free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
3349: free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3350: free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3351: printf("\n");
3352: fprintf(ficlog,"\n");
3353:
3354: free_vector(xm,1,npar);
3355: free_vector(xp,1,npar);
3356: free_matrix(dnewm,1,nlstate*nlstate,1,npar);
3357: free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
3358: free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
3359: }
3360:
3361: /************ Variance ******************/
3362: 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[])
3363: {
3364: /* Variance of health expectancies */
3365: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
3366: /* double **newm;*/
1.169 brouard 3367: /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
3368:
3369: int movingaverage();
1.126 brouard 3370: double **dnewm,**doldm;
3371: double **dnewmp,**doldmp;
3372: int i, j, nhstepm, hstepm, h, nstepm ;
1.164 brouard 3373: int k;
1.126 brouard 3374: double *xp;
3375: double **gp, **gm; /* for var eij */
3376: double ***gradg, ***trgradg; /*for var eij */
3377: double **gradgp, **trgradgp; /* for var p point j */
3378: double *gpp, *gmp; /* for var p point j */
3379: double **varppt; /* for var p point j nlstate to nlstate+ndeath */
3380: double ***p3mat;
3381: double age,agelim, hf;
3382: double ***mobaverage;
3383: int theta;
3384: char digit[4];
3385: char digitp[25];
3386:
3387: char fileresprobmorprev[FILENAMELENGTH];
3388:
3389: if(popbased==1){
3390: if(mobilav!=0)
3391: strcpy(digitp,"-populbased-mobilav-");
3392: else strcpy(digitp,"-populbased-nomobil-");
3393: }
3394: else
3395: strcpy(digitp,"-stablbased-");
3396:
3397: if (mobilav!=0) {
3398: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3399: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
3400: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
3401: printf(" Error in movingaverage mobilav=%d\n",mobilav);
3402: }
3403: }
3404:
3405: strcpy(fileresprobmorprev,"prmorprev");
3406: sprintf(digit,"%-d",ij);
3407: /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
3408: strcat(fileresprobmorprev,digit); /* Tvar to be done */
3409: strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
3410: strcat(fileresprobmorprev,fileres);
3411: if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
3412: printf("Problem with resultfile: %s\n", fileresprobmorprev);
3413: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
3414: }
3415: printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3416:
3417: fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3418: pstamp(ficresprobmorprev);
3419: 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);
3420: fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
3421: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3422: fprintf(ficresprobmorprev," p.%-d SE",j);
3423: for(i=1; i<=nlstate;i++)
3424: fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
3425: }
3426: fprintf(ficresprobmorprev,"\n");
3427: fprintf(ficgp,"\n# Routine varevsij");
3428: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
3429: 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");
3430: fprintf(fichtm,"\n<br>%s <br>\n",digitp);
3431: /* } */
3432: varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3433: pstamp(ficresvij);
3434: fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n# (weighted average of eij where weights are ");
3435: if(popbased==1)
1.128 brouard 3436: 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 3437: else
3438: fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
3439: fprintf(ficresvij,"# Age");
3440: for(i=1; i<=nlstate;i++)
3441: for(j=1; j<=nlstate;j++)
3442: fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
3443: fprintf(ficresvij,"\n");
3444:
3445: xp=vector(1,npar);
3446: dnewm=matrix(1,nlstate,1,npar);
3447: doldm=matrix(1,nlstate,1,nlstate);
3448: dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
3449: doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3450:
3451: gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
3452: gpp=vector(nlstate+1,nlstate+ndeath);
3453: gmp=vector(nlstate+1,nlstate+ndeath);
3454: trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
3455:
3456: if(estepm < stepm){
3457: printf ("Problem %d lower than %d\n",estepm, stepm);
3458: }
3459: else hstepm=estepm;
3460: /* For example we decided to compute the life expectancy with the smallest unit */
3461: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3462: nhstepm is the number of hstepm from age to agelim
3463: nstepm is the number of stepm from age to agelin.
1.128 brouard 3464: Look at function hpijx to understand why (it is linked to memory size questions) */
1.126 brouard 3465: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3466: survival function given by stepm (the optimization length). Unfortunately it
3467: means that if the survival funtion is printed every two years of age and if
3468: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3469: results. So we changed our mind and took the option of the best precision.
3470: */
3471: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3472: agelim = AGESUP;
3473: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3474: nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3475: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3476: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3477: gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
3478: gp=matrix(0,nhstepm,1,nlstate);
3479: gm=matrix(0,nhstepm,1,nlstate);
3480:
3481:
3482: for(theta=1; theta <=npar; theta++){
3483: for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
3484: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3485: }
3486: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3487: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3488:
3489: if (popbased==1) {
3490: if(mobilav ==0){
3491: for(i=1; i<=nlstate;i++)
3492: prlim[i][i]=probs[(int)age][i][ij];
3493: }else{ /* mobilav */
3494: for(i=1; i<=nlstate;i++)
3495: prlim[i][i]=mobaverage[(int)age][i][ij];
3496: }
3497: }
3498:
3499: for(j=1; j<= nlstate; j++){
3500: for(h=0; h<=nhstepm; h++){
3501: for(i=1, gp[h][j]=0.;i<=nlstate;i++)
3502: gp[h][j] += prlim[i][i]*p3mat[i][j][h];
3503: }
3504: }
3505: /* This for computing probability of death (h=1 means
3506: computed over hstepm matrices product = hstepm*stepm months)
3507: as a weighted average of prlim.
3508: */
3509: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3510: for(i=1,gpp[j]=0.; i<= nlstate; i++)
3511: gpp[j] += prlim[i][i]*p3mat[i][j][1];
3512: }
3513: /* end probability of death */
3514:
3515: for(i=1; i<=npar; i++) /* Computes gradient x - delta */
3516: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3517: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3518: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3519:
3520: if (popbased==1) {
3521: if(mobilav ==0){
3522: for(i=1; i<=nlstate;i++)
3523: prlim[i][i]=probs[(int)age][i][ij];
3524: }else{ /* mobilav */
3525: for(i=1; i<=nlstate;i++)
3526: prlim[i][i]=mobaverage[(int)age][i][ij];
3527: }
3528: }
3529:
1.128 brouard 3530: for(j=1; j<= nlstate; j++){ /* Sum of wi * eij = e.j */
1.126 brouard 3531: for(h=0; h<=nhstepm; h++){
3532: for(i=1, gm[h][j]=0.;i<=nlstate;i++)
3533: gm[h][j] += prlim[i][i]*p3mat[i][j][h];
3534: }
3535: }
3536: /* This for computing probability of death (h=1 means
3537: computed over hstepm matrices product = hstepm*stepm months)
3538: as a weighted average of prlim.
3539: */
3540: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3541: for(i=1,gmp[j]=0.; i<= nlstate; i++)
3542: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3543: }
3544: /* end probability of death */
3545:
3546: for(j=1; j<= nlstate; j++) /* vareij */
3547: for(h=0; h<=nhstepm; h++){
3548: gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
3549: }
3550:
3551: for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
3552: gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
3553: }
3554:
3555: } /* End theta */
3556:
3557: trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
3558:
3559: for(h=0; h<=nhstepm; h++) /* veij */
3560: for(j=1; j<=nlstate;j++)
3561: for(theta=1; theta <=npar; theta++)
3562: trgradg[h][j][theta]=gradg[h][theta][j];
3563:
3564: for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
3565: for(theta=1; theta <=npar; theta++)
3566: trgradgp[j][theta]=gradgp[theta][j];
3567:
3568:
3569: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3570: for(i=1;i<=nlstate;i++)
3571: for(j=1;j<=nlstate;j++)
3572: vareij[i][j][(int)age] =0.;
3573:
3574: for(h=0;h<=nhstepm;h++){
3575: for(k=0;k<=nhstepm;k++){
3576: matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
3577: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
3578: for(i=1;i<=nlstate;i++)
3579: for(j=1;j<=nlstate;j++)
3580: vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
3581: }
3582: }
3583:
3584: /* pptj */
3585: matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
3586: matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
3587: for(j=nlstate+1;j<=nlstate+ndeath;j++)
3588: for(i=nlstate+1;i<=nlstate+ndeath;i++)
3589: varppt[j][i]=doldmp[j][i];
3590: /* end ppptj */
3591: /* x centered again */
3592: hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);
3593: prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
3594:
3595: if (popbased==1) {
3596: if(mobilav ==0){
3597: for(i=1; i<=nlstate;i++)
3598: prlim[i][i]=probs[(int)age][i][ij];
3599: }else{ /* mobilav */
3600: for(i=1; i<=nlstate;i++)
3601: prlim[i][i]=mobaverage[(int)age][i][ij];
3602: }
3603: }
3604:
3605: /* This for computing probability of death (h=1 means
3606: computed over hstepm (estepm) matrices product = hstepm*stepm months)
3607: as a weighted average of prlim.
3608: */
3609: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3610: for(i=1,gmp[j]=0.;i<= nlstate; i++)
3611: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3612: }
3613: /* end probability of death */
3614:
3615: fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
3616: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3617: fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
3618: for(i=1; i<=nlstate;i++){
3619: fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
3620: }
3621: }
3622: fprintf(ficresprobmorprev,"\n");
3623:
3624: fprintf(ficresvij,"%.0f ",age );
3625: for(i=1; i<=nlstate;i++)
3626: for(j=1; j<=nlstate;j++){
3627: fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
3628: }
3629: fprintf(ficresvij,"\n");
3630: free_matrix(gp,0,nhstepm,1,nlstate);
3631: free_matrix(gm,0,nhstepm,1,nlstate);
3632: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
3633: free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
3634: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3635: } /* End age */
3636: free_vector(gpp,nlstate+1,nlstate+ndeath);
3637: free_vector(gmp,nlstate+1,nlstate+ndeath);
3638: free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
3639: free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.145 brouard 3640: fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
1.126 brouard 3641: /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131 brouard 3642: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.126 brouard 3643: /* fprintf(ficgp,"\n plot \"%s\" u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
3644: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
3645: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145 brouard 3646: fprintf(ficgp,"\n plot \"%s\" u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
1.170 brouard 3647: fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
1.145 brouard 3648: fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126 brouard 3649: fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
3650: 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);
3651: /* 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);
3652: */
3653: /* fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
3654: fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
3655:
3656: free_vector(xp,1,npar);
3657: free_matrix(doldm,1,nlstate,1,nlstate);
3658: free_matrix(dnewm,1,nlstate,1,npar);
3659: free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3660: free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
3661: free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3662: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3663: fclose(ficresprobmorprev);
3664: fflush(ficgp);
3665: fflush(fichtm);
3666: } /* end varevsij */
3667:
3668: /************ Variance of prevlim ******************/
3669: 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[])
3670: {
3671: /* Variance of prevalence limit */
3672: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164 brouard 3673:
1.126 brouard 3674: double **dnewm,**doldm;
3675: int i, j, nhstepm, hstepm;
3676: double *xp;
3677: double *gp, *gm;
3678: double **gradg, **trgradg;
3679: double age,agelim;
3680: int theta;
3681:
3682: pstamp(ficresvpl);
3683: fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
3684: fprintf(ficresvpl,"# Age");
3685: for(i=1; i<=nlstate;i++)
3686: fprintf(ficresvpl," %1d-%1d",i,i);
3687: fprintf(ficresvpl,"\n");
3688:
3689: xp=vector(1,npar);
3690: dnewm=matrix(1,nlstate,1,npar);
3691: doldm=matrix(1,nlstate,1,nlstate);
3692:
3693: hstepm=1*YEARM; /* Every year of age */
3694: hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
3695: agelim = AGESUP;
3696: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3697: nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3698: if (stepm >= YEARM) hstepm=1;
3699: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
3700: gradg=matrix(1,npar,1,nlstate);
3701: gp=vector(1,nlstate);
3702: gm=vector(1,nlstate);
3703:
3704: for(theta=1; theta <=npar; theta++){
3705: for(i=1; i<=npar; i++){ /* Computes gradient */
3706: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3707: }
3708: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3709: for(i=1;i<=nlstate;i++)
3710: gp[i] = prlim[i][i];
3711:
3712: for(i=1; i<=npar; i++) /* Computes gradient */
3713: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3714: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3715: for(i=1;i<=nlstate;i++)
3716: gm[i] = prlim[i][i];
3717:
3718: for(i=1;i<=nlstate;i++)
3719: gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
3720: } /* End theta */
3721:
3722: trgradg =matrix(1,nlstate,1,npar);
3723:
3724: for(j=1; j<=nlstate;j++)
3725: for(theta=1; theta <=npar; theta++)
3726: trgradg[j][theta]=gradg[theta][j];
3727:
3728: for(i=1;i<=nlstate;i++)
3729: varpl[i][(int)age] =0.;
3730: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
3731: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
3732: for(i=1;i<=nlstate;i++)
3733: varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
3734:
3735: fprintf(ficresvpl,"%.0f ",age );
3736: for(i=1; i<=nlstate;i++)
3737: fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
3738: fprintf(ficresvpl,"\n");
3739: free_vector(gp,1,nlstate);
3740: free_vector(gm,1,nlstate);
3741: free_matrix(gradg,1,npar,1,nlstate);
3742: free_matrix(trgradg,1,nlstate,1,npar);
3743: } /* End age */
3744:
3745: free_vector(xp,1,npar);
3746: free_matrix(doldm,1,nlstate,1,npar);
3747: free_matrix(dnewm,1,nlstate,1,nlstate);
3748:
3749: }
3750:
3751: /************ Variance of one-step probabilities ******************/
3752: 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[])
3753: {
1.164 brouard 3754: int i, j=0, k1, l1, tj;
1.126 brouard 3755: int k2, l2, j1, z1;
1.164 brouard 3756: int k=0, l;
1.145 brouard 3757: int first=1, first1, first2;
1.126 brouard 3758: double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
3759: double **dnewm,**doldm;
3760: double *xp;
3761: double *gp, *gm;
3762: double **gradg, **trgradg;
3763: double **mu;
1.164 brouard 3764: double age, cov[NCOVMAX+1];
1.126 brouard 3765: double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
3766: int theta;
3767: char fileresprob[FILENAMELENGTH];
3768: char fileresprobcov[FILENAMELENGTH];
3769: char fileresprobcor[FILENAMELENGTH];
3770: double ***varpij;
3771:
3772: strcpy(fileresprob,"prob");
3773: strcat(fileresprob,fileres);
3774: if((ficresprob=fopen(fileresprob,"w"))==NULL) {
3775: printf("Problem with resultfile: %s\n", fileresprob);
3776: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
3777: }
3778: strcpy(fileresprobcov,"probcov");
3779: strcat(fileresprobcov,fileres);
3780: if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
3781: printf("Problem with resultfile: %s\n", fileresprobcov);
3782: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
3783: }
3784: strcpy(fileresprobcor,"probcor");
3785: strcat(fileresprobcor,fileres);
3786: if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
3787: printf("Problem with resultfile: %s\n", fileresprobcor);
3788: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
3789: }
3790: printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3791: fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3792: printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3793: fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3794: printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3795: fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3796: pstamp(ficresprob);
3797: fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
3798: fprintf(ficresprob,"# Age");
3799: pstamp(ficresprobcov);
3800: fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
3801: fprintf(ficresprobcov,"# Age");
3802: pstamp(ficresprobcor);
3803: fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
3804: fprintf(ficresprobcor,"# Age");
3805:
3806:
3807: for(i=1; i<=nlstate;i++)
3808: for(j=1; j<=(nlstate+ndeath);j++){
3809: fprintf(ficresprob," p%1d-%1d (SE)",i,j);
3810: fprintf(ficresprobcov," p%1d-%1d ",i,j);
3811: fprintf(ficresprobcor," p%1d-%1d ",i,j);
3812: }
3813: /* fprintf(ficresprob,"\n");
3814: fprintf(ficresprobcov,"\n");
3815: fprintf(ficresprobcor,"\n");
3816: */
1.131 brouard 3817: xp=vector(1,npar);
1.126 brouard 3818: dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3819: doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
3820: mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
3821: varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
3822: first=1;
3823: fprintf(ficgp,"\n# Routine varprob");
3824: fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
3825: fprintf(fichtm,"\n");
3826:
3827: fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
3828: fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
3829: file %s<br>\n",optionfilehtmcov);
3830: fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
3831: and drawn. It helps understanding how is the covariance between two incidences.\
3832: They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
3833: 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. \
3834: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
3835: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
3836: standard deviations wide on each axis. <br>\
3837: Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
3838: and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
3839: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
3840:
3841: cov[1]=1;
1.145 brouard 3842: /* tj=cptcoveff; */
3843: tj = (int) pow(2,cptcoveff);
1.126 brouard 3844: if (cptcovn<1) {tj=1;ncodemax[1]=1;}
3845: j1=0;
1.145 brouard 3846: for(j1=1; j1<=tj;j1++){
3847: /*for(i1=1; i1<=ncodemax[t];i1++){ */
3848: /*j1++;*/
1.126 brouard 3849: if (cptcovn>0) {
3850: fprintf(ficresprob, "\n#********** Variable ");
3851: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3852: fprintf(ficresprob, "**********\n#\n");
3853: fprintf(ficresprobcov, "\n#********** Variable ");
3854: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3855: fprintf(ficresprobcov, "**********\n#\n");
3856:
3857: fprintf(ficgp, "\n#********** Variable ");
3858: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3859: fprintf(ficgp, "**********\n#\n");
3860:
3861:
3862: fprintf(fichtmcov, "\n<hr size=\"2\" color=\"#EC5E5E\">********** Variable ");
3863: for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3864: fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
3865:
3866: fprintf(ficresprobcor, "\n#********** Variable ");
3867: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3868: fprintf(ficresprobcor, "**********\n#");
3869: }
3870:
1.145 brouard 3871: gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
3872: trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3873: gp=vector(1,(nlstate)*(nlstate+ndeath));
3874: gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126 brouard 3875: for (age=bage; age<=fage; age ++){
3876: cov[2]=age;
3877: for (k=1; k<=cptcovn;k++) {
1.145 brouard 3878: cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
3879: * 1 1 1 1 1
3880: * 2 2 1 1 1
3881: * 3 1 2 1 1
3882: */
3883: /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126 brouard 3884: }
3885: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
3886: for (k=1; k<=cptcovprod;k++)
3887: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
3888:
3889:
3890: for(theta=1; theta <=npar; theta++){
3891: for(i=1; i<=npar; i++)
3892: xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
3893:
3894: pmij(pmmij,cov,ncovmodel,xp,nlstate);
3895:
3896: k=0;
3897: for(i=1; i<= (nlstate); i++){
3898: for(j=1; j<=(nlstate+ndeath);j++){
3899: k=k+1;
3900: gp[k]=pmmij[i][j];
3901: }
3902: }
3903:
3904: for(i=1; i<=npar; i++)
3905: xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
3906:
3907: pmij(pmmij,cov,ncovmodel,xp,nlstate);
3908: k=0;
3909: for(i=1; i<=(nlstate); i++){
3910: for(j=1; j<=(nlstate+ndeath);j++){
3911: k=k+1;
3912: gm[k]=pmmij[i][j];
3913: }
3914: }
3915:
3916: for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
3917: gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];
3918: }
3919:
3920: for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
3921: for(theta=1; theta <=npar; theta++)
3922: trgradg[j][theta]=gradg[theta][j];
3923:
3924: matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
3925: matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
3926:
3927: pmij(pmmij,cov,ncovmodel,x,nlstate);
3928:
3929: k=0;
3930: for(i=1; i<=(nlstate); i++){
3931: for(j=1; j<=(nlstate+ndeath);j++){
3932: k=k+1;
3933: mu[k][(int) age]=pmmij[i][j];
3934: }
3935: }
3936: for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
3937: for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
3938: varpij[i][j][(int)age] = doldm[i][j];
3939:
3940: /*printf("\n%d ",(int)age);
3941: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
3942: printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
3943: fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
3944: }*/
3945:
3946: fprintf(ficresprob,"\n%d ",(int)age);
3947: fprintf(ficresprobcov,"\n%d ",(int)age);
3948: fprintf(ficresprobcor,"\n%d ",(int)age);
3949:
3950: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
3951: fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
3952: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
3953: fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
3954: fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
3955: }
3956: i=0;
3957: for (k=1; k<=(nlstate);k++){
3958: for (l=1; l<=(nlstate+ndeath);l++){
1.145 brouard 3959: i++;
1.126 brouard 3960: fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
3961: fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
3962: for (j=1; j<=i;j++){
1.145 brouard 3963: /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126 brouard 3964: fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
3965: fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
3966: }
3967: }
3968: }/* end of loop for state */
3969: } /* end of loop for age */
1.145 brouard 3970: free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
3971: free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
3972: free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
3973: free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
3974:
1.126 brouard 3975: /* Confidence intervalle of pij */
3976: /*
1.131 brouard 3977: fprintf(ficgp,"\nunset parametric;unset label");
1.126 brouard 3978: fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
3979: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
3980: 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);
3981: fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
3982: fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
3983: fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
3984: */
3985:
3986: /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145 brouard 3987: first1=1;first2=2;
1.126 brouard 3988: for (k2=1; k2<=(nlstate);k2++){
3989: for (l2=1; l2<=(nlstate+ndeath);l2++){
3990: if(l2==k2) continue;
3991: j=(k2-1)*(nlstate+ndeath)+l2;
3992: for (k1=1; k1<=(nlstate);k1++){
3993: for (l1=1; l1<=(nlstate+ndeath);l1++){
3994: if(l1==k1) continue;
3995: i=(k1-1)*(nlstate+ndeath)+l1;
3996: if(i<=j) continue;
3997: for (age=bage; age<=fage; age ++){
3998: if ((int)age %5==0){
3999: v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
4000: v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
4001: cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
4002: mu1=mu[i][(int) age]/stepm*YEARM ;
4003: mu2=mu[j][(int) age]/stepm*YEARM;
4004: c12=cv12/sqrt(v1*v2);
4005: /* Computing eigen value of matrix of covariance */
4006: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
4007: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135 brouard 4008: if ((lc2 <0) || (lc1 <0) ){
1.145 brouard 4009: if(first2==1){
4010: first1=0;
4011: 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);
4012: }
4013: 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);
4014: /* lc1=fabs(lc1); */ /* If we want to have them positive */
4015: /* lc2=fabs(lc2); */
1.135 brouard 4016: }
4017:
1.126 brouard 4018: /* Eigen vectors */
4019: v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
4020: /*v21=sqrt(1.-v11*v11); *//* error */
4021: v21=(lc1-v1)/cv12*v11;
4022: v12=-v21;
4023: v22=v11;
4024: tnalp=v21/v11;
4025: if(first1==1){
4026: first1=0;
4027: 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);
4028: }
4029: 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);
4030: /*printf(fignu*/
4031: /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
4032: /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
4033: if(first==1){
4034: first=0;
4035: fprintf(ficgp,"\nset parametric;unset label");
4036: 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 4037: fprintf(ficgp,"\nset ter png small size 320, 240");
1.126 brouard 4038: fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
4039: :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
4040: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
4041: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
4042: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4043: fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4044: fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
4045: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4046: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4047: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4048: 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",\
4049: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4050: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4051: }else{
4052: first=0;
4053: fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
4054: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4055: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4056: 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",\
4057: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4058: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4059: }/* if first */
4060: } /* age mod 5 */
4061: } /* end loop age */
4062: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4063: first=1;
4064: } /*l12 */
4065: } /* k12 */
4066: } /*l1 */
4067: }/* k1 */
1.169 brouard 4068: /* } */ /* loop covariates */
1.126 brouard 4069: }
4070: free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
4071: free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
4072: free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4073: free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
4074: free_vector(xp,1,npar);
4075: fclose(ficresprob);
4076: fclose(ficresprobcov);
4077: fclose(ficresprobcor);
4078: fflush(ficgp);
4079: fflush(fichtmcov);
4080: }
4081:
4082:
4083: /******************* Printing html file ***********/
4084: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
4085: int lastpass, int stepm, int weightopt, char model[],\
4086: int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
4087: int popforecast, int estepm ,\
4088: double jprev1, double mprev1,double anprev1, \
4089: double jprev2, double mprev2,double anprev2){
4090: int jj1, k1, i1, cpt;
4091:
4092: fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
4093: <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
4094: </ul>");
4095: fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
4096: - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
4097: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
4098: fprintf(fichtm,"\
4099: - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
4100: stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
4101: fprintf(fichtm,"\
4102: - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
4103: subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
4104: fprintf(fichtm,"\
1.128 brouard 4105: - (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 4106: <a href=\"%s\">%s</a> <br>\n",
4107: estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
4108: fprintf(fichtm,"\
4109: - Population projections by age and states: \
4110: <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
4111:
4112: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
4113:
1.145 brouard 4114: m=pow(2,cptcoveff);
1.126 brouard 4115: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4116:
4117: jj1=0;
4118: for(k1=1; k1<=m;k1++){
4119: for(i1=1; i1<=ncodemax[k1];i1++){
4120: jj1++;
4121: if (cptcovn > 0) {
4122: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4123: for (cpt=1; cpt<=cptcoveff;cpt++)
4124: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4125: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4126: }
4127: /* Pij */
1.145 brouard 4128: 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> \
4129: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
1.126 brouard 4130: /* Quasi-incidences */
4131: fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
1.145 brouard 4132: 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> \
4133: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
1.126 brouard 4134: /* Period (stable) prevalence in each health state */
1.154 brouard 4135: for(cpt=1; cpt<=nlstate;cpt++){
1.166 brouard 4136: 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> \
4137: <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 4138: }
4139: for(cpt=1; cpt<=nlstate;cpt++) {
1.154 brouard 4140: 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> \
4141: <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 4142: }
4143: } /* end i1 */
4144: }/* End k1 */
4145: fprintf(fichtm,"</ul>");
4146:
4147:
4148: fprintf(fichtm,"\
4149: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
4150: - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
4151:
4152: fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4153: subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
4154: fprintf(fichtm,"\
4155: - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4156: subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
4157:
4158: fprintf(fichtm,"\
4159: - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4160: subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
4161: fprintf(fichtm,"\
4162: - 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): \
4163: <a href=\"%s\">%s</a> <br>\n</li>",
4164: estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
4165: fprintf(fichtm,"\
4166: - (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): \
4167: <a href=\"%s\">%s</a> <br>\n</li>",
4168: estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
4169: fprintf(fichtm,"\
1.128 brouard 4170: - 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 4171: estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
4172: fprintf(fichtm,"\
1.128 brouard 4173: - 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",
4174: estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
1.126 brouard 4175: fprintf(fichtm,"\
4176: - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
4177: subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
4178:
4179: /* if(popforecast==1) fprintf(fichtm,"\n */
4180: /* - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
4181: /* - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
4182: /* <br>",fileres,fileres,fileres,fileres); */
4183: /* else */
4184: /* 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); */
4185: fflush(fichtm);
4186: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
4187:
1.145 brouard 4188: m=pow(2,cptcoveff);
1.126 brouard 4189: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4190:
4191: jj1=0;
4192: for(k1=1; k1<=m;k1++){
4193: for(i1=1; i1<=ncodemax[k1];i1++){
4194: jj1++;
4195: if (cptcovn > 0) {
4196: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4197: for (cpt=1; cpt<=cptcoveff;cpt++)
4198: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4199: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4200: }
4201: for(cpt=1; cpt<=nlstate;cpt++) {
4202: fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.145 brouard 4203: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
4204: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);
1.126 brouard 4205: }
4206: fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128 brouard 4207: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
4208: true period expectancies (those weighted with period prevalences are also\
4209: drawn in addition to the population based expectancies computed using\
4210: observed and cahotic prevalences: %s%d.png<br>\
1.126 brouard 4211: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
4212: } /* end i1 */
4213: }/* End k1 */
4214: fprintf(fichtm,"</ul>");
4215: fflush(fichtm);
4216: }
4217:
4218: /******************* Gnuplot file **************/
4219: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4220:
4221: char dirfileres[132],optfileres[132];
1.164 brouard 4222: int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.130 brouard 4223: int ng=0;
1.126 brouard 4224: /* if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
4225: /* printf("Problem with file %s",optionfilegnuplot); */
4226: /* fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
4227: /* } */
4228:
4229: /*#ifdef windows */
4230: fprintf(ficgp,"cd \"%s\" \n",pathc);
4231: /*#endif */
4232: m=pow(2,cptcoveff);
4233:
4234: strcpy(dirfileres,optionfilefiname);
4235: strcpy(optfileres,"vpl");
4236: /* 1eme*/
1.153 brouard 4237: fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
1.126 brouard 4238: for (cpt=1; cpt<= nlstate ; cpt ++) {
1.145 brouard 4239: for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
4240: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
4241: fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
1.126 brouard 4242: fprintf(ficgp,"set xlabel \"Age\" \n\
4243: set ylabel \"Probability\" \n\
1.145 brouard 4244: set ter png small size 320, 240\n\
1.170 brouard 4245: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
1.126 brouard 4246:
4247: for (i=1; i<= nlstate ; i ++) {
1.170 brouard 4248: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4249: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4250: }
1.170 brouard 4251: 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 4252: for (i=1; i<= nlstate ; i ++) {
1.170 brouard 4253: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4254: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4255: }
1.170 brouard 4256: 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 4257: for (i=1; i<= nlstate ; i ++) {
1.170 brouard 4258: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4259: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4260: }
1.145 brouard 4261: 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 4262: }
4263: }
4264: /*2 eme*/
1.153 brouard 4265: fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
1.126 brouard 4266: for (k1=1; k1<= m ; k1 ++) {
4267: fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
1.145 brouard 4268: fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
1.126 brouard 4269:
4270: for (i=1; i<= nlstate+1 ; i ++) {
4271: k=2*i;
1.170 brouard 4272: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126 brouard 4273: for (j=1; j<= nlstate+1 ; j ++) {
1.170 brouard 4274: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4275: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4276: }
4277: if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
4278: else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
1.170 brouard 4279: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126 brouard 4280: for (j=1; j<= nlstate+1 ; j ++) {
1.170 brouard 4281: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4282: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4283: }
1.145 brouard 4284: fprintf(ficgp,"\" t\"\" w l lt 0,");
1.170 brouard 4285: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126 brouard 4286: for (j=1; j<= nlstate+1 ; j ++) {
1.170 brouard 4287: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4288: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4289: }
1.145 brouard 4290: if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
4291: else fprintf(ficgp,"\" t\"\" w l lt 0,");
1.126 brouard 4292: }
4293: }
4294:
4295: /*3eme*/
4296:
4297: for (k1=1; k1<= m ; k1 ++) {
4298: for (cpt=1; cpt<= nlstate ; cpt ++) {
4299: /* k=2+nlstate*(2*cpt-2); */
4300: k=2+(nlstate+1)*(cpt-1);
4301: fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
1.145 brouard 4302: fprintf(ficgp,"set ter png small size 320, 240\n\
1.126 brouard 4303: 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);
4304: /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4305: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4306: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4307: fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4308: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4309: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4310:
4311: */
4312: for (i=1; i< nlstate ; i ++) {
4313: 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);
4314: /* 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);*/
4315:
4316: }
4317: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
4318: }
4319: }
4320:
4321: /* CV preval stable (period) */
1.153 brouard 4322: for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
4323: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.126 brouard 4324: k=3;
1.153 brouard 4325: fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
1.145 brouard 4326: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
1.126 brouard 4327: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.145 brouard 4328: set ter png small size 320, 240\n\
1.126 brouard 4329: unset log y\n\
1.153 brouard 4330: plot [%.f:%.f] ", ageminpar, agemaxpar);
4331: for (i=1; i<= nlstate ; i ++){
4332: if(i==1)
4333: fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
4334: else
4335: fprintf(ficgp,", '' ");
1.154 brouard 4336: l=(nlstate+ndeath)*(i-1)+1;
4337: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.153 brouard 4338: for (j=1; j<= (nlstate-1) ; j ++)
4339: fprintf(ficgp,"+$%d",k+l+j);
4340: fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
4341: } /* nlstate */
4342: fprintf(ficgp,"\n");
4343: } /* end cpt state*/
4344: } /* end covariate */
1.126 brouard 4345:
4346: /* proba elementaires */
4347: for(i=1,jk=1; i <=nlstate; i++){
4348: for(k=1; k <=(nlstate+ndeath); k++){
4349: if (k != i) {
4350: for(j=1; j <=ncovmodel; j++){
4351: fprintf(ficgp,"p%d=%f ",jk,p[jk]);
4352: jk++;
4353: fprintf(ficgp,"\n");
4354: }
4355: }
4356: }
4357: }
1.145 brouard 4358: /*goto avoid;*/
1.126 brouard 4359: for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
4360: for(jk=1; jk <=m; jk++) {
1.145 brouard 4361: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);
1.126 brouard 4362: if (ng==2)
4363: fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
4364: else
4365: fprintf(ficgp,"\nset title \"Probability\"\n");
1.145 brouard 4366: fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot [%.f:%.f] ",ageminpar,agemaxpar);
1.126 brouard 4367: i=1;
4368: for(k2=1; k2<=nlstate; k2++) {
4369: k3=i;
4370: for(k=1; k<=(nlstate+ndeath); k++) {
4371: if (k != k2){
4372: if(ng==2)
4373: fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
4374: else
4375: fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
1.141 brouard 4376: ij=1;/* To be checked else nbcode[0][0] wrong */
1.126 brouard 4377: for(j=3; j <=ncovmodel; j++) {
1.145 brouard 4378: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /\* Bug valgrind *\/ */
4379: /* /\*fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);*\/ */
4380: /* ij++; */
4381: /* } */
4382: /* else */
1.126 brouard 4383: fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4384: }
4385: fprintf(ficgp,")/(1");
4386:
4387: for(k1=1; k1 <=nlstate; k1++){
4388: fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
4389: ij=1;
4390: for(j=3; j <=ncovmodel; j++){
1.145 brouard 4391: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { */
4392: /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]); */
4393: /* ij++; */
4394: /* } */
4395: /* else */
1.126 brouard 4396: fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4397: }
4398: fprintf(ficgp,")");
4399: }
4400: fprintf(ficgp,") t \"p%d%d\" ", k2,k);
4401: if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
4402: i=i+ncovmodel;
4403: }
4404: } /* end k */
4405: } /* end k2 */
4406: } /* end jk */
4407: } /* end ng */
1.164 brouard 4408: /* avoid: */
1.126 brouard 4409: fflush(ficgp);
4410: } /* end gnuplot */
4411:
4412:
4413: /*************** Moving average **************/
4414: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
4415:
4416: int i, cpt, cptcod;
4417: int modcovmax =1;
4418: int mobilavrange, mob;
4419: double age;
4420:
4421: modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
4422: a covariate has 2 modalities */
4423: if (cptcovn<1) modcovmax=1; /* At least 1 pass */
4424:
4425: if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
4426: if(mobilav==1) mobilavrange=5; /* default */
4427: else mobilavrange=mobilav;
4428: for (age=bage; age<=fage; age++)
4429: for (i=1; i<=nlstate;i++)
4430: for (cptcod=1;cptcod<=modcovmax;cptcod++)
4431: mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
4432: /* We keep the original values on the extreme ages bage, fage and for
4433: fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
4434: we use a 5 terms etc. until the borders are no more concerned.
4435: */
4436: for (mob=3;mob <=mobilavrange;mob=mob+2){
4437: for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
4438: for (i=1; i<=nlstate;i++){
4439: for (cptcod=1;cptcod<=modcovmax;cptcod++){
4440: mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
4441: for (cpt=1;cpt<=(mob-1)/2;cpt++){
4442: mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
4443: mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
4444: }
4445: mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
4446: }
4447: }
4448: }/* end age */
4449: }/* end mob */
4450: }else return -1;
4451: return 0;
4452: }/* End movingaverage */
4453:
4454:
4455: /************** Forecasting ******************/
1.169 brouard 4456: void prevforecast(char fileres[], double anproj1, double mproj1, double jproj1, double ageminpar, double agemax, double dateprev1, double dateprev2, int mobilav, double bage, double fage, int firstpass, int lastpass, double anproj2, double p[], int cptcoveff){
1.126 brouard 4457: /* proj1, year, month, day of starting projection
4458: agemin, agemax range of age
4459: dateprev1 dateprev2 range of dates during which prevalence is computed
4460: anproj2 year of en of projection (same day and month as proj1).
4461: */
1.164 brouard 4462: int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126 brouard 4463: double agec; /* generic age */
4464: double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
4465: double *popeffectif,*popcount;
4466: double ***p3mat;
4467: double ***mobaverage;
4468: char fileresf[FILENAMELENGTH];
4469:
4470: agelim=AGESUP;
4471: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4472:
4473: strcpy(fileresf,"f");
4474: strcat(fileresf,fileres);
4475: if((ficresf=fopen(fileresf,"w"))==NULL) {
4476: printf("Problem with forecast resultfile: %s\n", fileresf);
4477: fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
4478: }
4479: printf("Computing forecasting: result on file '%s' \n", fileresf);
4480: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
4481:
4482: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4483:
4484: if (mobilav!=0) {
4485: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4486: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4487: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4488: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4489: }
4490: }
4491:
4492: stepsize=(int) (stepm+YEARM-1)/YEARM;
4493: if (stepm<=12) stepsize=1;
4494: if(estepm < stepm){
4495: printf ("Problem %d lower than %d\n",estepm, stepm);
4496: }
4497: else hstepm=estepm;
4498:
4499: hstepm=hstepm/stepm;
4500: yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp and
4501: fractional in yp1 */
4502: anprojmean=yp;
4503: yp2=modf((yp1*12),&yp);
4504: mprojmean=yp;
4505: yp1=modf((yp2*30.5),&yp);
4506: jprojmean=yp;
4507: if(jprojmean==0) jprojmean=1;
4508: if(mprojmean==0) jprojmean=1;
4509:
4510: i1=cptcoveff;
4511: if (cptcovn < 1){i1=1;}
4512:
4513: fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
4514:
4515: fprintf(ficresf,"#****** Routine prevforecast **\n");
4516:
4517: /* if (h==(int)(YEARM*yearp)){ */
4518: for(cptcov=1, k=0;cptcov<=i1;cptcov++){
4519: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4520: k=k+1;
4521: fprintf(ficresf,"\n#******");
4522: for(j=1;j<=cptcoveff;j++) {
4523: 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]]);
4524: }
4525: fprintf(ficresf,"******\n");
4526: fprintf(ficresf,"# Covariate valuofcovar yearproj age");
4527: for(j=1; j<=nlstate+ndeath;j++){
4528: for(i=1; i<=nlstate;i++)
4529: fprintf(ficresf," p%d%d",i,j);
4530: fprintf(ficresf," p.%d",j);
4531: }
4532: for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
4533: fprintf(ficresf,"\n");
4534: fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);
4535:
4536: for (agec=fage; agec>=(ageminpar-1); agec--){
4537: nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
4538: nhstepm = nhstepm/hstepm;
4539: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4540: oldm=oldms;savm=savms;
4541: hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
4542:
4543: for (h=0; h<=nhstepm; h++){
4544: if (h*hstepm/YEARM*stepm ==yearp) {
4545: fprintf(ficresf,"\n");
4546: for(j=1;j<=cptcoveff;j++)
4547: fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4548: fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
4549: }
4550: for(j=1; j<=nlstate+ndeath;j++) {
4551: ppij=0.;
4552: for(i=1; i<=nlstate;i++) {
4553: if (mobilav==1)
4554: ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
4555: else {
4556: ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
4557: }
4558: if (h*hstepm/YEARM*stepm== yearp) {
4559: fprintf(ficresf," %.3f", p3mat[i][j][h]);
4560: }
4561: } /* end i */
4562: if (h*hstepm/YEARM*stepm==yearp) {
4563: fprintf(ficresf," %.3f", ppij);
4564: }
4565: }/* end j */
4566: } /* end h */
4567: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4568: } /* end agec */
4569: } /* end yearp */
4570: } /* end cptcod */
4571: } /* end cptcov */
4572:
4573: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4574:
4575: fclose(ficresf);
4576: }
4577:
4578: /************** Forecasting *****not tested NB*************/
1.169 brouard 4579: void populforecast(char fileres[], double anpyram,double mpyram,double jpyram,double ageminpar, double agemax,double dateprev1, double dateprev2, int mobilav, double agedeb, double fage, int popforecast, char popfile[], double anpyram1,double p[], int i2){
1.126 brouard 4580:
4581: int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
4582: int *popage;
4583: double calagedatem, agelim, kk1, kk2;
4584: double *popeffectif,*popcount;
4585: double ***p3mat,***tabpop,***tabpopprev;
4586: double ***mobaverage;
4587: char filerespop[FILENAMELENGTH];
4588:
4589: tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4590: tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4591: agelim=AGESUP;
4592: calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
4593:
4594: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4595:
4596:
4597: strcpy(filerespop,"pop");
4598: strcat(filerespop,fileres);
4599: if((ficrespop=fopen(filerespop,"w"))==NULL) {
4600: printf("Problem with forecast resultfile: %s\n", filerespop);
4601: fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
4602: }
4603: printf("Computing forecasting: result on file '%s' \n", filerespop);
4604: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
4605:
4606: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4607:
4608: if (mobilav!=0) {
4609: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4610: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4611: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4612: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4613: }
4614: }
4615:
4616: stepsize=(int) (stepm+YEARM-1)/YEARM;
4617: if (stepm<=12) stepsize=1;
4618:
4619: agelim=AGESUP;
4620:
4621: hstepm=1;
4622: hstepm=hstepm/stepm;
4623:
4624: if (popforecast==1) {
4625: if((ficpop=fopen(popfile,"r"))==NULL) {
4626: printf("Problem with population file : %s\n",popfile);exit(0);
4627: fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
4628: }
4629: popage=ivector(0,AGESUP);
4630: popeffectif=vector(0,AGESUP);
4631: popcount=vector(0,AGESUP);
4632:
4633: i=1;
4634: while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
4635:
4636: imx=i;
4637: for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
4638: }
4639:
4640: for(cptcov=1,k=0;cptcov<=i2;cptcov++){
4641: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4642: k=k+1;
4643: fprintf(ficrespop,"\n#******");
4644: for(j=1;j<=cptcoveff;j++) {
4645: fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4646: }
4647: fprintf(ficrespop,"******\n");
4648: fprintf(ficrespop,"# Age");
4649: for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
4650: if (popforecast==1) fprintf(ficrespop," [Population]");
4651:
4652: for (cpt=0; cpt<=0;cpt++) {
4653: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4654:
4655: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4656: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4657: nhstepm = nhstepm/hstepm;
4658:
4659: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4660: oldm=oldms;savm=savms;
4661: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4662:
4663: for (h=0; h<=nhstepm; h++){
4664: if (h==(int) (calagedatem+YEARM*cpt)) {
4665: fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4666: }
4667: for(j=1; j<=nlstate+ndeath;j++) {
4668: kk1=0.;kk2=0;
4669: for(i=1; i<=nlstate;i++) {
4670: if (mobilav==1)
4671: kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
4672: else {
4673: kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
4674: }
4675: }
4676: if (h==(int)(calagedatem+12*cpt)){
4677: tabpop[(int)(agedeb)][j][cptcod]=kk1;
4678: /*fprintf(ficrespop," %.3f", kk1);
4679: if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
4680: }
4681: }
4682: for(i=1; i<=nlstate;i++){
4683: kk1=0.;
4684: for(j=1; j<=nlstate;j++){
4685: kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
4686: }
4687: tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
4688: }
4689:
4690: if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
4691: fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
4692: }
4693: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4694: }
4695: }
4696:
4697: /******/
4698:
4699: for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
4700: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4701: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4702: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4703: nhstepm = nhstepm/hstepm;
4704:
4705: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4706: oldm=oldms;savm=savms;
4707: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4708: for (h=0; h<=nhstepm; h++){
4709: if (h==(int) (calagedatem+YEARM*cpt)) {
4710: fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4711: }
4712: for(j=1; j<=nlstate+ndeath;j++) {
4713: kk1=0.;kk2=0;
4714: for(i=1; i<=nlstate;i++) {
4715: kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];
4716: }
4717: if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);
4718: }
4719: }
4720: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4721: }
4722: }
4723: }
4724: }
4725:
4726: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4727:
4728: if (popforecast==1) {
4729: free_ivector(popage,0,AGESUP);
4730: free_vector(popeffectif,0,AGESUP);
4731: free_vector(popcount,0,AGESUP);
4732: }
4733: free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4734: free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4735: fclose(ficrespop);
4736: } /* End of popforecast */
4737:
4738: int fileappend(FILE *fichier, char *optionfich)
4739: {
4740: if((fichier=fopen(optionfich,"a"))==NULL) {
4741: printf("Problem with file: %s\n", optionfich);
4742: fprintf(ficlog,"Problem with file: %s\n", optionfich);
4743: return (0);
4744: }
4745: fflush(fichier);
4746: return (1);
4747: }
4748:
4749:
4750: /**************** function prwizard **********************/
4751: void prwizard(int ncovmodel, int nlstate, int ndeath, char model[], FILE *ficparo)
4752: {
4753:
4754: /* Wizard to print covariance matrix template */
4755:
1.164 brouard 4756: char ca[32], cb[32];
4757: int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126 brouard 4758: int numlinepar;
4759:
4760: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4761: fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4762: for(i=1; i <=nlstate; i++){
4763: jj=0;
4764: for(j=1; j <=nlstate+ndeath; j++){
4765: if(j==i) continue;
4766: jj++;
4767: /*ca[0]= k+'a'-1;ca[1]='\0';*/
4768: printf("%1d%1d",i,j);
4769: fprintf(ficparo,"%1d%1d",i,j);
4770: for(k=1; k<=ncovmodel;k++){
4771: /* printf(" %lf",param[i][j][k]); */
4772: /* fprintf(ficparo," %lf",param[i][j][k]); */
4773: printf(" 0.");
4774: fprintf(ficparo," 0.");
4775: }
4776: printf("\n");
4777: fprintf(ficparo,"\n");
4778: }
4779: }
4780: printf("# Scales (for hessian or gradient estimation)\n");
4781: fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
4782: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
4783: for(i=1; i <=nlstate; i++){
4784: jj=0;
4785: for(j=1; j <=nlstate+ndeath; j++){
4786: if(j==i) continue;
4787: jj++;
4788: fprintf(ficparo,"%1d%1d",i,j);
4789: printf("%1d%1d",i,j);
4790: fflush(stdout);
4791: for(k=1; k<=ncovmodel;k++){
4792: /* printf(" %le",delti3[i][j][k]); */
4793: /* fprintf(ficparo," %le",delti3[i][j][k]); */
4794: printf(" 0.");
4795: fprintf(ficparo," 0.");
4796: }
4797: numlinepar++;
4798: printf("\n");
4799: fprintf(ficparo,"\n");
4800: }
4801: }
4802: printf("# Covariance matrix\n");
4803: /* # 121 Var(a12)\n\ */
4804: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4805: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
4806: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
4807: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
4808: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
4809: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
4810: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4811: fflush(stdout);
4812: fprintf(ficparo,"# Covariance matrix\n");
4813: /* # 121 Var(a12)\n\ */
4814: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4815: /* # ...\n\ */
4816: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4817:
4818: for(itimes=1;itimes<=2;itimes++){
4819: jj=0;
4820: for(i=1; i <=nlstate; i++){
4821: for(j=1; j <=nlstate+ndeath; j++){
4822: if(j==i) continue;
4823: for(k=1; k<=ncovmodel;k++){
4824: jj++;
4825: ca[0]= k+'a'-1;ca[1]='\0';
4826: if(itimes==1){
4827: printf("#%1d%1d%d",i,j,k);
4828: fprintf(ficparo,"#%1d%1d%d",i,j,k);
4829: }else{
4830: printf("%1d%1d%d",i,j,k);
4831: fprintf(ficparo,"%1d%1d%d",i,j,k);
4832: /* printf(" %.5le",matcov[i][j]); */
4833: }
4834: ll=0;
4835: for(li=1;li <=nlstate; li++){
4836: for(lj=1;lj <=nlstate+ndeath; lj++){
4837: if(lj==li) continue;
4838: for(lk=1;lk<=ncovmodel;lk++){
4839: ll++;
4840: if(ll<=jj){
4841: cb[0]= lk +'a'-1;cb[1]='\0';
4842: if(ll<jj){
4843: if(itimes==1){
4844: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4845: fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4846: }else{
4847: printf(" 0.");
4848: fprintf(ficparo," 0.");
4849: }
4850: }else{
4851: if(itimes==1){
4852: printf(" Var(%s%1d%1d)",ca,i,j);
4853: fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
4854: }else{
4855: printf(" 0.");
4856: fprintf(ficparo," 0.");
4857: }
4858: }
4859: }
4860: } /* end lk */
4861: } /* end lj */
4862: } /* end li */
4863: printf("\n");
4864: fprintf(ficparo,"\n");
4865: numlinepar++;
4866: } /* end k*/
4867: } /*end j */
4868: } /* end i */
4869: } /* end itimes */
4870:
4871: } /* end of prwizard */
4872: /******************* Gompertz Likelihood ******************************/
4873: double gompertz(double x[])
4874: {
4875: double A,B,L=0.0,sump=0.,num=0.;
4876: int i,n=0; /* n is the size of the sample */
4877:
4878: for (i=0;i<=imx-1 ; i++) {
4879: sump=sump+weight[i];
4880: /* sump=sump+1;*/
4881: num=num+1;
4882: }
4883:
4884:
4885: /* for (i=0; i<=imx; i++)
4886: 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]);*/
4887:
4888: for (i=1;i<=imx ; i++)
4889: {
4890: if (cens[i] == 1 && wav[i]>1)
4891: A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
4892:
4893: if (cens[i] == 0 && wav[i]>1)
4894: A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
4895: +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);
4896:
4897: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
4898: if (wav[i] > 1 ) { /* ??? */
4899: L=L+A*weight[i];
4900: /* 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]);*/
4901: }
4902: }
4903:
4904: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
4905:
4906: return -2*L*num/sump;
4907: }
4908:
1.136 brouard 4909: #ifdef GSL
4910: /******************* Gompertz_f Likelihood ******************************/
4911: double gompertz_f(const gsl_vector *v, void *params)
4912: {
4913: double A,B,LL=0.0,sump=0.,num=0.;
4914: double *x= (double *) v->data;
4915: int i,n=0; /* n is the size of the sample */
4916:
4917: for (i=0;i<=imx-1 ; i++) {
4918: sump=sump+weight[i];
4919: /* sump=sump+1;*/
4920: num=num+1;
4921: }
4922:
4923:
4924: /* for (i=0; i<=imx; i++)
4925: 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]);*/
4926: printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
4927: for (i=1;i<=imx ; i++)
4928: {
4929: if (cens[i] == 1 && wav[i]>1)
4930: A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
4931:
4932: if (cens[i] == 0 && wav[i]>1)
4933: A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
4934: +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);
4935:
4936: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
4937: if (wav[i] > 1 ) { /* ??? */
4938: LL=LL+A*weight[i];
4939: /* 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]);*/
4940: }
4941: }
4942:
4943: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
4944: printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
4945:
4946: return -2*LL*num/sump;
4947: }
4948: #endif
4949:
1.126 brouard 4950: /******************* Printing html file ***********/
4951: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
4952: int lastpass, int stepm, int weightopt, char model[],\
4953: int imx, double p[],double **matcov,double agemortsup){
4954: int i,k;
4955:
4956: fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
4957: fprintf(fichtm," mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
4958: for (i=1;i<=2;i++)
4959: 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]));
4960: fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
4961: fprintf(fichtm,"</ul>");
4962:
4963: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
4964:
4965: 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>");
4966:
4967: for (k=agegomp;k<(agemortsup-2);k++)
4968: 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]);
4969:
4970:
4971: fflush(fichtm);
4972: }
4973:
4974: /******************* Gnuplot file **************/
4975: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4976:
4977: char dirfileres[132],optfileres[132];
1.164 brouard 4978:
1.126 brouard 4979: int ng;
4980:
4981:
4982: /*#ifdef windows */
4983: fprintf(ficgp,"cd \"%s\" \n",pathc);
4984: /*#endif */
4985:
4986:
4987: strcpy(dirfileres,optionfilefiname);
4988: strcpy(optfileres,"vpl");
4989: fprintf(ficgp,"set out \"graphmort.png\"\n ");
4990: fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
1.145 brouard 4991: fprintf(ficgp, "set ter png small size 320, 240\n set log y\n");
4992: /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126 brouard 4993: fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
4994:
4995: }
4996:
1.136 brouard 4997: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
4998: {
1.126 brouard 4999:
1.136 brouard 5000: /*-------- data file ----------*/
5001: FILE *fic;
5002: char dummy[]=" ";
1.164 brouard 5003: int i=0, j=0, n=0;
1.136 brouard 5004: int linei, month, year,iout;
5005: char line[MAXLINE], linetmp[MAXLINE];
1.164 brouard 5006: char stra[MAXLINE], strb[MAXLINE];
1.136 brouard 5007: char *stratrunc;
5008: int lstra;
1.126 brouard 5009:
5010:
1.136 brouard 5011: if((fic=fopen(datafile,"r"))==NULL) {
5012: printf("Problem while opening datafile: %s\n", datafile);return 1;
5013: fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
5014: }
1.126 brouard 5015:
1.136 brouard 5016: i=1;
5017: linei=0;
5018: while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
5019: linei=linei+1;
5020: for(j=strlen(line); j>=0;j--){ /* Untabifies line */
5021: if(line[j] == '\t')
5022: line[j] = ' ';
5023: }
5024: for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
5025: ;
5026: };
5027: line[j+1]=0; /* Trims blanks at end of line */
5028: if(line[0]=='#'){
5029: fprintf(ficlog,"Comment line\n%s\n",line);
5030: printf("Comment line\n%s\n",line);
5031: continue;
5032: }
5033: trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164 brouard 5034: strcpy(line, linetmp);
1.136 brouard 5035:
1.126 brouard 5036:
1.136 brouard 5037: for (j=maxwav;j>=1;j--){
1.137 brouard 5038: cutv(stra, strb, line, ' ');
1.136 brouard 5039: if(strb[0]=='.') { /* Missing status */
5040: lval=-1;
5041: }else{
5042: errno=0;
5043: lval=strtol(strb,&endptr,10);
5044: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
5045: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5046: 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);
5047: 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 5048: return 1;
5049: }
5050: }
5051: s[j][i]=lval;
5052:
5053: strcpy(line,stra);
5054: cutv(stra, strb,line,' ');
1.169 brouard 5055: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136 brouard 5056: }
1.169 brouard 5057: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136 brouard 5058: month=99;
5059: year=9999;
5060: }else{
1.141 brouard 5061: 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);
5062: 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 5063: return 1;
5064: }
5065: anint[j][i]= (double) year;
5066: mint[j][i]= (double)month;
5067: strcpy(line,stra);
5068: } /* ENd Waves */
5069:
5070: cutv(stra, strb,line,' ');
1.169 brouard 5071: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136 brouard 5072: }
1.169 brouard 5073: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136 brouard 5074: month=99;
5075: year=9999;
5076: }else{
1.141 brouard 5077: 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);
5078: 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 5079: return 1;
5080: }
5081: andc[i]=(double) year;
5082: moisdc[i]=(double) month;
5083: strcpy(line,stra);
5084:
5085: cutv(stra, strb,line,' ');
1.169 brouard 5086: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136 brouard 5087: }
1.169 brouard 5088: else if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136 brouard 5089: month=99;
5090: year=9999;
5091: }else{
1.141 brouard 5092: printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be a date of birth (mm/yyyy or .). Exiting.\n",strb, linei,i,line);
5093: fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be a date of birth (mm/yyyy or .). Exiting.\n",strb, linei,i,line);fflush(ficlog);
1.136 brouard 5094: return 1;
5095: }
5096: if (year==9999) {
1.141 brouard 5097: 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);
5098: 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 5099: return 1;
1.126 brouard 5100:
1.136 brouard 5101: }
5102: annais[i]=(double)(year);
5103: moisnais[i]=(double)(month);
5104: strcpy(line,stra);
5105:
5106: cutv(stra, strb,line,' ');
5107: errno=0;
5108: dval=strtod(strb,&endptr);
5109: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5110: printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight. Exiting.\n",dval, i,line,linei);
5111: 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 5112: fflush(ficlog);
5113: return 1;
5114: }
5115: weight[i]=dval;
5116: strcpy(line,stra);
5117:
5118: for (j=ncovcol;j>=1;j--){
5119: cutv(stra, strb,line,' ');
5120: if(strb[0]=='.') { /* Missing status */
5121: lval=-1;
5122: }else{
5123: errno=0;
5124: lval=strtol(strb,&endptr,10);
5125: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5126: 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);
5127: 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 5128: return 1;
5129: }
5130: }
5131: if(lval <-1 || lval >1){
1.141 brouard 5132: printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 5133: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5134: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5135: For example, for multinomial values like 1, 2 and 3,\n \
5136: build V1=0 V2=0 for the reference value (1),\n \
5137: V1=1 V2=0 for (2) \n \
5138: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5139: output of IMaCh is often meaningless.\n \
5140: Exiting.\n",lval,linei, i,line,j);
1.141 brouard 5141: fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 5142: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5143: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5144: For example, for multinomial values like 1, 2 and 3,\n \
5145: build V1=0 V2=0 for the reference value (1),\n \
5146: V1=1 V2=0 for (2) \n \
5147: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5148: output of IMaCh is often meaningless.\n \
5149: Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
5150: return 1;
5151: }
5152: covar[j][i]=(double)(lval);
5153: strcpy(line,stra);
5154: }
5155: lstra=strlen(stra);
5156:
5157: if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
5158: stratrunc = &(stra[lstra-9]);
5159: num[i]=atol(stratrunc);
5160: }
5161: else
5162: num[i]=atol(stra);
5163: /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
5164: 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;}*/
5165:
5166: i=i+1;
5167: } /* End loop reading data */
1.126 brouard 5168:
1.136 brouard 5169: *imax=i-1; /* Number of individuals */
5170: fclose(fic);
5171:
5172: return (0);
1.164 brouard 5173: /* endread: */
1.136 brouard 5174: printf("Exiting readdata: ");
5175: fclose(fic);
5176: return (1);
1.126 brouard 5177:
5178:
5179:
1.136 brouard 5180: }
1.145 brouard 5181: void removespace(char *str) {
5182: char *p1 = str, *p2 = str;
5183: do
5184: while (*p2 == ' ')
5185: p2++;
1.169 brouard 5186: while (*p1++ == *p2++);
1.145 brouard 5187: }
5188:
5189: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
5190: * Model V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age
5191: * - cptcovt total number of covariates of the model nbocc(+)+1 = 8
5192: * - cptcovn or number of covariates k of the models excluding age*products =6
5193: * - cptcovage number of covariates with age*products =2
5194: * - cptcovs number of simple covariates
5195: * - 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
5196: * which is a new column after the 9 (ncovcol) variables.
5197: * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
5198: * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
5199: * Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
5200: * - Tvard[k] p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
5201: */
1.136 brouard 5202: {
1.145 brouard 5203: int i, j, k, ks;
1.164 brouard 5204: int j1, k1, k2;
1.136 brouard 5205: char modelsav[80];
1.145 brouard 5206: char stra[80], strb[80], strc[80], strd[80],stre[80];
1.136 brouard 5207:
1.145 brouard 5208: /*removespace(model);*/
1.136 brouard 5209: if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145 brouard 5210: j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
5211: j=nbocc(model,'+'); /**< j=Number of '+' */
5212: j1=nbocc(model,'*'); /**< j1=Number of '*' */
5213: cptcovs=j+1-j1; /**< Number of simple covariates V1+V2*age+V3 +V3*V4=> V1 + V3 =2 */
5214: cptcovt= j+1; /* Number of total covariates in the model V1 + V2*age+ V3 + V3*V4=> 4*/
5215: /* including age products which are counted in cptcovage.
1.169 brouard 5216: * but the covariates which are products must be treated separately: ncovn=4- 2=2 (V1+V3). */
1.145 brouard 5217: cptcovprod=j1; /**< Number of products V1*V2 +v3*age = 2 */
5218: cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1 */
1.136 brouard 5219: strcpy(modelsav,model);
1.137 brouard 5220: if (strstr(model,"AGE") !=0){
5221: printf("Error. AGE must be in lower case 'age' model=%s ",model);
5222: fprintf(ficlog,"Error. AGE must be in lower case model=%s ",model);fflush(ficlog);
1.136 brouard 5223: return 1;
5224: }
1.141 brouard 5225: if (strstr(model,"v") !=0){
5226: printf("Error. 'v' must be in upper case 'V' model=%s ",model);
5227: fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
5228: return 1;
5229: }
1.136 brouard 5230:
1.145 brouard 5231: /* Design
5232: * V1 V2 V3 V4 V5 V6 V7 V8 V9 Weight
5233: * < ncovcol=8 >
5234: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
5235: * k= 1 2 3 4 5 6 7 8
5236: * cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
5237: * covar[k,i], value of kth covariate if not including age for individual i:
5238: * covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
5239: * Tvar[k] # of the kth covariate: Tvar[1]=2 Tvar[4]=3 Tvar[8]=8
5240: * if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and
5241: * Tage[++cptcovage]=k
5242: * if products, new covar are created after ncovcol with k1
5243: * Tvar[k]=ncovcol+k1; # of the kth covariate product: Tvar[5]=ncovcol+1=10 Tvar[6]=ncovcol+1=11
5244: * Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
5245: * 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
5246: * Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
5247: * Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
5248: * V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
5249: * < ncovcol=8 >
5250: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 d1 d1 d2 d2
5251: * k= 1 2 3 4 5 6 7 8 9 10 11 12
5252: * Tvar[k]= 2 1 3 3 10 11 8 8 5 6 7 8
5253: * p Tvar[1]@12={2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5254: * p Tprod[1]@2={ 6, 5}
5255: *p Tvard[1][1]@4= {7, 8, 5, 6}
5256: * covar[k][i]= V2 V1 ? V3 V5*V6? V7*V8? ? V8
5257: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
5258: *How to reorganize?
5259: * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
5260: * Tvars {2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5261: * {2, 1, 4, 8, 5, 6, 3, 7}
5262: * Struct []
5263: */
5264:
1.136 brouard 5265: /* This loop fills the array Tvar from the string 'model'.*/
5266: /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
1.137 brouard 5267: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 */
5268: /* k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
5269: /* k=3 V4 Tvar[k=3]= 4 (from V4) */
5270: /* k=2 V1 Tvar[k=2]= 1 (from V1) */
5271: /* k=1 Tvar[1]=2 (from V2) */
5272: /* k=5 Tvar[5] */
5273: /* for (k=1; k<=cptcovn;k++) { */
5274: /* cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
5275: /* } */
5276: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.145 brouard 5277: /*
5278: * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
5279: for(k=cptcovt; k>=1;k--) /**< Number of covariates */
5280: Tvar[k]=0;
5281: cptcovage=0;
5282: for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
5283: cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+'
5284: modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */
1.137 brouard 5285: if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
1.136 brouard 5286: /* printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
5287: /*scanf("%d",i);*/
1.145 brouard 5288: if (strchr(strb,'*')) { /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
5289: cutl(strc,strd,strb,'*'); /**< strd*strc Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
5290: if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
5291: /* covar is not filled and then is empty */
1.136 brouard 5292: cptcovprod--;
1.145 brouard 5293: cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
5294: Tvar[k]=atoi(stre); /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2 */
1.136 brouard 5295: cptcovage++; /* Sums the number of covariates which include age as a product */
1.137 brouard 5296: Tage[cptcovage]=k; /* Tage[1] = 4 */
1.136 brouard 5297: /*printf("stre=%s ", stre);*/
1.137 brouard 5298: } else if (strcmp(strd,"age")==0) { /* or age*Vn */
1.136 brouard 5299: cptcovprod--;
1.145 brouard 5300: cutl(stre,strb,strc,'V');
1.136 brouard 5301: Tvar[k]=atoi(stre);
5302: cptcovage++;
5303: Tage[cptcovage]=k;
1.137 brouard 5304: } else { /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2 strb=V3*V2*/
5305: /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
1.145 brouard 5306: cptcovn++;
5307: cptcovprodnoage++;k1++;
5308: cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
5309: Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
1.137 brouard 5310: because this model-covariate is a construction we invent a new column
5311: ncovcol + k1
5312: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
5313: Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
1.145 brouard 5314: cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
1.137 brouard 5315: Tprod[k1]=k; /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 */
1.145 brouard 5316: Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
5317: Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
5318: k2=k2+2;
5319: Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
5320: Tvar[cptcovt+k2+1]=Tvard[k1][2]; /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
1.137 brouard 5321: for (i=1; i<=lastobs;i++){
5322: /* Computes the new covariate which is a product of
1.145 brouard 5323: covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
1.136 brouard 5324: covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
1.137 brouard 5325: }
5326: } /* End age is not in the model */
5327: } /* End if model includes a product */
1.136 brouard 5328: else { /* no more sum */
5329: /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
5330: /* scanf("%d",i);*/
1.145 brouard 5331: cutl(strd,strc,strb,'V');
5332: ks++; /**< Number of simple covariates */
5333: cptcovn++;
5334: Tvar[k]=atoi(strd);
1.136 brouard 5335: }
1.137 brouard 5336: strcpy(modelsav,stra); /* modelsav=V2+V1+V4 stra=V2+V1+V4 */
1.136 brouard 5337: /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
5338: scanf("%d",i);*/
5339: } /* end of loop + */
5340: } /* end model */
5341:
5342: /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
5343: If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
5344:
5345: /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
5346: printf("cptcovprod=%d ", cptcovprod);
5347: fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
5348:
5349: scanf("%d ",i);*/
5350:
5351:
1.137 brouard 5352: return (0); /* with covar[new additional covariate if product] and Tage if age */
1.164 brouard 5353: /*endread:*/
1.136 brouard 5354: printf("Exiting decodemodel: ");
5355: return (1);
5356: }
5357:
1.169 brouard 5358: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136 brouard 5359: {
5360: int i, m;
5361:
5362: for (i=1; i<=imx; i++) {
5363: for(m=2; (m<= maxwav); m++) {
5364: if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
5365: anint[m][i]=9999;
5366: s[m][i]=-1;
5367: }
5368: if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169 brouard 5369: *nberr = *nberr + 1;
5370: printf("Error! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown, you must set an arbitrary year of death or he/she is skipped and results are biased (%d)\n",(int)moisdc[i],(int)andc[i],num[i],i, *nberr);
5371: fprintf(ficlog,"Error! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown, you must set an arbitrary year of death or he/she is skipped and results are biased (%d)\n",(int)moisdc[i],(int)andc[i],num[i],i, *nberr);
1.136 brouard 5372: s[m][i]=-1;
5373: }
5374: if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169 brouard 5375: (*nberr)++;
1.136 brouard 5376: 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]);
5377: 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]);
5378: s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
5379: }
5380: }
5381: }
5382:
5383: for (i=1; i<=imx; i++) {
5384: agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
5385: for(m=firstpass; (m<= lastpass); m++){
5386: if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
5387: if (s[m][i] >= nlstate+1) {
1.169 brouard 5388: if(agedc[i]>0){
5389: if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136 brouard 5390: agev[m][i]=agedc[i];
5391: /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169 brouard 5392: }else {
1.136 brouard 5393: if ((int)andc[i]!=9999){
5394: nbwarn++;
5395: printf("Warning negative age at death: %ld line:%d\n",num[i],i);
5396: fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
5397: agev[m][i]=-1;
5398: }
5399: }
1.169 brouard 5400: } /* agedc > 0 */
1.136 brouard 5401: }
5402: else if(s[m][i] !=9){ /* Standard case, age in fractional
5403: years but with the precision of a month */
5404: agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
5405: if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
5406: agev[m][i]=1;
5407: else if(agev[m][i] < *agemin){
5408: *agemin=agev[m][i];
5409: printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
5410: }
5411: else if(agev[m][i] >*agemax){
5412: *agemax=agev[m][i];
1.156 brouard 5413: /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136 brouard 5414: }
5415: /*agev[m][i]=anint[m][i]-annais[i];*/
5416: /* agev[m][i] = age[i]+2*m;*/
5417: }
5418: else { /* =9 */
5419: agev[m][i]=1;
5420: s[m][i]=-1;
5421: }
5422: }
5423: else /*= 0 Unknown */
5424: agev[m][i]=1;
5425: }
5426:
5427: }
5428: for (i=1; i<=imx; i++) {
5429: for(m=firstpass; (m<=lastpass); m++){
5430: if (s[m][i] > (nlstate+ndeath)) {
1.169 brouard 5431: (*nberr)++;
1.136 brouard 5432: 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);
5433: 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);
5434: return 1;
5435: }
5436: }
5437: }
5438:
5439: /*for (i=1; i<=imx; i++){
5440: for (m=firstpass; (m<lastpass); m++){
5441: printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
5442: }
5443:
5444: }*/
5445:
5446:
1.139 brouard 5447: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
5448: fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
1.136 brouard 5449:
5450: return (0);
1.164 brouard 5451: /* endread:*/
1.136 brouard 5452: printf("Exiting calandcheckages: ");
5453: return (1);
5454: }
5455:
1.172 ! brouard 5456: #if defined(_MSC_VER)
! 5457: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
! 5458: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
! 5459: //#include "stdafx.h"
! 5460: //#include <stdio.h>
! 5461: //#include <tchar.h>
! 5462: //#include <windows.h>
! 5463: //#include <iostream>
! 5464: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
! 5465:
! 5466: LPFN_ISWOW64PROCESS fnIsWow64Process;
! 5467:
! 5468: BOOL IsWow64()
! 5469: {
! 5470: BOOL bIsWow64 = FALSE;
! 5471:
! 5472: //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
! 5473: // (HANDLE, PBOOL);
! 5474:
! 5475: //LPFN_ISWOW64PROCESS fnIsWow64Process;
! 5476:
! 5477: HMODULE module = GetModuleHandle(_T("kernel32"));
! 5478: const char funcName[] = "IsWow64Process";
! 5479: fnIsWow64Process = (LPFN_ISWOW64PROCESS)
! 5480: GetProcAddress(module, funcName);
! 5481:
! 5482: if (NULL != fnIsWow64Process)
! 5483: {
! 5484: if (!fnIsWow64Process(GetCurrentProcess(),
! 5485: &bIsWow64))
! 5486: //throw std::exception("Unknown error");
! 5487: printf("Unknown error\n");
! 5488: }
! 5489: return bIsWow64 != FALSE;
! 5490: }
! 5491: #endif
1.169 brouard 5492: void syscompilerinfo()
1.167 brouard 5493: {
5494: /* #include "syscompilerinfo.h"*/
1.169 brouard 5495: /* #include <gnu/libc-version.h> */ /* Only on gnu */
1.171 brouard 5496: #include <stdint.h>
1.169 brouard 5497: printf("Compiled with:");fprintf(ficlog,"Compiled with:");
5498: #if defined(__clang__)
5499: printf(" Clang/LLVM");fprintf(ficlog," Clang/LLVM"); /* Clang/LLVM. ---------------------------------------------- */
5500: #endif
5501: #if defined(__ICC) || defined(__INTEL_COMPILER)
5502: printf(" Intel ICC/ICPC");fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
5503: #endif
5504: #if defined(__GNUC__) || defined(__GNUG__)
5505: printf(" GNU GCC/G++");fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
5506: #endif
5507: #if defined(__HP_cc) || defined(__HP_aCC)
5508: printf(" Hewlett-Packard C/aC++");fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
5509: #endif
5510: #if defined(__IBMC__) || defined(__IBMCPP__)
5511: printf(" IBM XL C/C++"); fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
5512: #endif
5513: #if defined(_MSC_VER)
5514: printf(" Microsoft Visual Studio");fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
5515: #endif
5516: #if defined(__PGI)
5517: printf(" Portland Group PGCC/PGCPP");fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
5518: #endif
5519: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
5520: printf(" Oracle Solaris Studio");fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167 brouard 5521: #endif
1.169 brouard 5522: printf(". ");fprintf(ficlog,". ");
5523:
1.167 brouard 5524: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
5525: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
5526: // Windows (x64 and x86)
5527: #elif __unix__ // all unices, not all compilers
5528: // Unix
5529: #elif __linux__
5530: // linux
5531: #elif __APPLE__
5532: // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though...
5533: #endif
5534:
5535: /* __MINGW32__ */
5536: /* __CYGWIN__ */
5537: /* __MINGW64__ */
5538: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
5539: /* _MSC_VER //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /? */
5540: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
5541: /* _WIN64 // Defined for applications for Win64. */
5542: /* _M_X64 // Defined for compilations that target x64 processors. */
5543: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171 brouard 5544:
1.167 brouard 5545: #if UINTPTR_MAX == 0xffffffff
1.171 brouard 5546: printf(" 32-bit.\n"); fprintf(ficlog," 32-bit.\n");/* 32-bit */
1.167 brouard 5547: #elif UINTPTR_MAX == 0xffffffffffffffff
1.171 brouard 5548: printf(" 64-bit.\n"); fprintf(ficlog," 64-bit.\n");/* 64-bit */
1.167 brouard 5549: #else
1.171 brouard 5550: printf(" wtf-bit.\n"); fprintf(ficlog," wtf-bit.\n");/* wtf */
1.167 brouard 5551: #endif
5552:
1.171 brouard 5553: /* struct utsname sysInfo;
1.167 brouard 5554:
5555: if (uname(&sysInfo) != -1) {
1.169 brouard 5556: printf(" %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
5557: fprintf(ficlog," %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.167 brouard 5558: }
5559: else
5560: perror("uname() error");
1.171 brouard 5561: */
1.169 brouard 5562: #if defined(__GNUC__)
5563: # if defined(__GNUC_PATCHLEVEL__)
5564: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
5565: + __GNUC_MINOR__ * 100 \
5566: + __GNUC_PATCHLEVEL__)
5567: # else
5568: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
5569: + __GNUC_MINOR__ * 100)
5570: # endif
5571: printf("GNU C version %d.\n", __GNUC_VERSION__);
5572: fprintf(ficlog, "GNU C version %d.\n", __GNUC_VERSION__);
5573: #endif
1.172 ! brouard 5574:
! 5575: // void main()
! 5576: // {
1.169 brouard 5577: #if defined(_MSC_VER)
1.172 ! brouard 5578: if (IsWow64())
! 5579: printf("The process is running under WOW64.\n");
! 5580: else
! 5581: printf("The process is not running under WOW64.\n");
! 5582:
! 5583: // printf("\nPress Enter to continue...");
! 5584: // getchar();
! 5585: // }
! 5586:
1.169 brouard 5587: #endif
5588:
5589: /* printf("GNU libc version: %s\n", gnu_get_libc_version()); */
1.167 brouard 5590:
5591: }
1.136 brouard 5592:
5593: /***********************************************/
5594: /**************** Main Program *****************/
5595: /***********************************************/
5596:
5597: int main(int argc, char *argv[])
5598: {
5599: #ifdef GSL
5600: const gsl_multimin_fminimizer_type *T;
5601: size_t iteri = 0, it;
5602: int rval = GSL_CONTINUE;
5603: int status = GSL_SUCCESS;
5604: double ssval;
5605: #endif
5606: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164 brouard 5607: int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
5608:
5609: int jj, ll, li, lj, lk;
1.136 brouard 5610: int numlinepar=0; /* Current linenumber of parameter file */
5611: int itimes;
5612: int NDIM=2;
5613: int vpopbased=0;
5614:
1.164 brouard 5615: char ca[32], cb[32];
1.136 brouard 5616: /* FILE *fichtm; *//* Html File */
5617: /* FILE *ficgp;*/ /*Gnuplot File */
5618: struct stat info;
1.164 brouard 5619: double agedeb;
1.136 brouard 5620: double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
5621:
1.165 brouard 5622: double fret;
1.136 brouard 5623: double dum; /* Dummy variable */
5624: double ***p3mat;
5625: double ***mobaverage;
1.164 brouard 5626:
5627: char line[MAXLINE];
1.136 brouard 5628: char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
5629: char pathr[MAXLINE], pathimach[MAXLINE];
1.164 brouard 5630: char *tok, *val; /* pathtot */
1.136 brouard 5631: int firstobs=1, lastobs=10;
1.164 brouard 5632: int c, h , cpt;
5633: int jl;
5634: int i1, j1, jk, stepsize;
5635: int *tab;
1.136 brouard 5636: int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
5637: int mobilav=0,popforecast=0;
5638: int hstepm, nhstepm;
5639: int agemortsup;
5640: float sumlpop=0.;
5641: double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
5642: double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
5643:
1.164 brouard 5644: double bage=0, fage=110, age, agelim, agebase;
1.136 brouard 5645: double ftolpl=FTOL;
5646: double **prlim;
5647: double ***param; /* Matrix of parameters */
5648: double *p;
5649: double **matcov; /* Matrix of covariance */
5650: double ***delti3; /* Scale */
5651: double *delti; /* Scale */
5652: double ***eij, ***vareij;
5653: double **varpl; /* Variances of prevalence limits by age */
5654: double *epj, vepp;
1.164 brouard 5655:
1.136 brouard 5656: double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
5657: double **ximort;
1.145 brouard 5658: char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136 brouard 5659: int *dcwave;
5660:
1.164 brouard 5661: char z[1]="c";
1.136 brouard 5662:
5663: /*char *strt;*/
5664: char strtend[80];
1.126 brouard 5665:
1.164 brouard 5666:
1.126 brouard 5667: /* setlocale (LC_ALL, ""); */
5668: /* bindtextdomain (PACKAGE, LOCALEDIR); */
5669: /* textdomain (PACKAGE); */
5670: /* setlocale (LC_CTYPE, ""); */
5671: /* setlocale (LC_MESSAGES, ""); */
5672:
5673: /* gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157 brouard 5674: rstart_time = time(NULL);
5675: /* (void) gettimeofday(&start_time,&tzp);*/
5676: start_time = *localtime(&rstart_time);
1.126 brouard 5677: curr_time=start_time;
1.157 brouard 5678: /*tml = *localtime(&start_time.tm_sec);*/
5679: /* strcpy(strstart,asctime(&tml)); */
5680: strcpy(strstart,asctime(&start_time));
1.126 brouard 5681:
5682: /* printf("Localtime (at start)=%s",strstart); */
1.157 brouard 5683: /* tp.tm_sec = tp.tm_sec +86400; */
5684: /* tm = *localtime(&start_time.tm_sec); */
1.126 brouard 5685: /* tmg.tm_year=tmg.tm_year +dsign*dyear; */
5686: /* tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
5687: /* tmg.tm_hour=tmg.tm_hour + 1; */
1.157 brouard 5688: /* tp.tm_sec = mktime(&tmg); */
1.126 brouard 5689: /* strt=asctime(&tmg); */
5690: /* printf("Time(after) =%s",strstart); */
5691: /* (void) time (&time_value);
5692: * printf("time=%d,t-=%d\n",time_value,time_value-86400);
5693: * tm = *localtime(&time_value);
5694: * strstart=asctime(&tm);
5695: * printf("tim_value=%d,asctime=%s\n",time_value,strstart);
5696: */
5697:
5698: nberr=0; /* Number of errors and warnings */
5699: nbwarn=0;
5700: getcwd(pathcd, size);
5701:
5702: printf("\n%s\n%s",version,fullversion);
5703: if(argc <=1){
5704: printf("\nEnter the parameter file name: ");
5705: fgets(pathr,FILENAMELENGTH,stdin);
5706: i=strlen(pathr);
5707: if(pathr[i-1]=='\n')
5708: pathr[i-1]='\0';
1.156 brouard 5709: i=strlen(pathr);
5710: if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
5711: pathr[i-1]='\0';
1.126 brouard 5712: for (tok = pathr; tok != NULL; ){
5713: printf("Pathr |%s|\n",pathr);
5714: while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
5715: printf("val= |%s| pathr=%s\n",val,pathr);
5716: strcpy (pathtot, val);
5717: if(pathr[0] == '\0') break; /* Dirty */
5718: }
5719: }
5720: else{
5721: strcpy(pathtot,argv[1]);
5722: }
5723: /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
5724: /*cygwin_split_path(pathtot,path,optionfile);
5725: printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
5726: /* cutv(path,optionfile,pathtot,'\\');*/
5727:
5728: /* Split argv[0], imach program to get pathimach */
5729: printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
5730: split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
5731: printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
5732: /* strcpy(pathimach,argv[0]); */
5733: /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
5734: split(pathtot,path,optionfile,optionfilext,optionfilefiname);
5735: printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
5736: chdir(path); /* Can be a relative path */
5737: if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
5738: printf("Current directory %s!\n",pathcd);
5739: strcpy(command,"mkdir ");
5740: strcat(command,optionfilefiname);
5741: if((outcmd=system(command)) != 0){
1.169 brouard 5742: printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126 brouard 5743: /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
5744: /* fclose(ficlog); */
5745: /* exit(1); */
5746: }
5747: /* if((imk=mkdir(optionfilefiname))<0){ */
5748: /* perror("mkdir"); */
5749: /* } */
5750:
5751: /*-------- arguments in the command line --------*/
5752:
5753: /* Log file */
5754: strcat(filelog, optionfilefiname);
5755: strcat(filelog,".log"); /* */
5756: if((ficlog=fopen(filelog,"w"))==NULL) {
5757: printf("Problem with logfile %s\n",filelog);
5758: goto end;
5759: }
5760: fprintf(ficlog,"Log filename:%s\n",filelog);
5761: fprintf(ficlog,"\n%s\n%s",version,fullversion);
5762: fprintf(ficlog,"\nEnter the parameter file name: \n");
5763: fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
5764: path=%s \n\
5765: optionfile=%s\n\
5766: optionfilext=%s\n\
1.156 brouard 5767: optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126 brouard 5768:
1.167 brouard 5769: syscompilerinfo();
5770:
1.126 brouard 5771: printf("Local time (at start):%s",strstart);
5772: fprintf(ficlog,"Local time (at start): %s",strstart);
5773: fflush(ficlog);
5774: /* (void) gettimeofday(&curr_time,&tzp); */
1.157 brouard 5775: /* printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126 brouard 5776:
5777: /* */
5778: strcpy(fileres,"r");
5779: strcat(fileres, optionfilefiname);
5780: strcat(fileres,".txt"); /* Other files have txt extension */
5781:
5782: /*---------arguments file --------*/
5783:
5784: if((ficpar=fopen(optionfile,"r"))==NULL) {
1.155 brouard 5785: printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
5786: fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126 brouard 5787: fflush(ficlog);
1.149 brouard 5788: /* goto end; */
5789: exit(70);
1.126 brouard 5790: }
5791:
5792:
5793:
5794: strcpy(filereso,"o");
5795: strcat(filereso,fileres);
5796: if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
5797: printf("Problem with Output resultfile: %s\n", filereso);
5798: fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
5799: fflush(ficlog);
5800: goto end;
5801: }
5802:
5803: /* Reads comments: lines beginning with '#' */
5804: numlinepar=0;
5805: while((c=getc(ficpar))=='#' && c!= EOF){
5806: ungetc(c,ficpar);
5807: fgets(line, MAXLINE, ficpar);
5808: numlinepar++;
1.141 brouard 5809: fputs(line,stdout);
1.126 brouard 5810: fputs(line,ficparo);
5811: fputs(line,ficlog);
5812: }
5813: ungetc(c,ficpar);
5814:
5815: 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);
5816: numlinepar++;
5817: 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);
5818: 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);
5819: 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);
5820: fflush(ficlog);
5821: while((c=getc(ficpar))=='#' && c!= EOF){
5822: ungetc(c,ficpar);
5823: fgets(line, MAXLINE, ficpar);
5824: numlinepar++;
1.141 brouard 5825: fputs(line, stdout);
5826: //puts(line);
1.126 brouard 5827: fputs(line,ficparo);
5828: fputs(line,ficlog);
5829: }
5830: ungetc(c,ficpar);
5831:
5832:
1.145 brouard 5833: covar=matrix(0,NCOVMAX,1,n); /**< used in readdata */
1.136 brouard 5834: cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
5835: /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
5836: v1+v2*age+v2*v3 makes cptcovn = 3
5837: */
5838: if (strlen(model)>1)
1.145 brouard 5839: 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*/
5840: else
5841: ncovmodel=2;
1.126 brouard 5842: nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
1.133 brouard 5843: nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
5844: npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131 brouard 5845: if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
5846: 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);
5847: 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);
5848: fflush(stdout);
5849: fclose (ficlog);
5850: goto end;
5851: }
1.126 brouard 5852: delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5853: delti=delti3[1][1];
5854: /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
5855: if(mle==-1){ /* Print a wizard for help writing covariance matrix */
5856: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
5857: printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
5858: fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
5859: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
5860: fclose (ficparo);
5861: fclose (ficlog);
5862: goto end;
5863: exit(0);
5864: }
5865: else if(mle==-3) {
5866: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
5867: printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
5868: fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
5869: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5870: matcov=matrix(1,npar,1,npar);
5871: }
5872: else{
1.145 brouard 5873: /* Read guessed parameters */
1.126 brouard 5874: /* Reads comments: lines beginning with '#' */
5875: while((c=getc(ficpar))=='#' && c!= EOF){
5876: ungetc(c,ficpar);
5877: fgets(line, MAXLINE, ficpar);
5878: numlinepar++;
1.141 brouard 5879: fputs(line,stdout);
1.126 brouard 5880: fputs(line,ficparo);
5881: fputs(line,ficlog);
5882: }
5883: ungetc(c,ficpar);
5884:
5885: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5886: for(i=1; i <=nlstate; i++){
5887: j=0;
5888: for(jj=1; jj <=nlstate+ndeath; jj++){
5889: if(jj==i) continue;
5890: j++;
5891: fscanf(ficpar,"%1d%1d",&i1,&j1);
5892: if ((i1 != i) && (j1 != j)){
5893: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
5894: It might be a problem of design; if ncovcol and the model are correct\n \
5895: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
5896: exit(1);
5897: }
5898: fprintf(ficparo,"%1d%1d",i1,j1);
5899: if(mle==1)
5900: printf("%1d%1d",i,j);
5901: fprintf(ficlog,"%1d%1d",i,j);
5902: for(k=1; k<=ncovmodel;k++){
5903: fscanf(ficpar," %lf",¶m[i][j][k]);
5904: if(mle==1){
5905: printf(" %lf",param[i][j][k]);
5906: fprintf(ficlog," %lf",param[i][j][k]);
5907: }
5908: else
5909: fprintf(ficlog," %lf",param[i][j][k]);
5910: fprintf(ficparo," %lf",param[i][j][k]);
5911: }
5912: fscanf(ficpar,"\n");
5913: numlinepar++;
5914: if(mle==1)
5915: printf("\n");
5916: fprintf(ficlog,"\n");
5917: fprintf(ficparo,"\n");
5918: }
5919: }
5920: fflush(ficlog);
5921:
1.145 brouard 5922: /* Reads scales values */
1.126 brouard 5923: p=param[1][1];
5924:
5925: /* Reads comments: lines beginning with '#' */
5926: while((c=getc(ficpar))=='#' && c!= EOF){
5927: ungetc(c,ficpar);
5928: fgets(line, MAXLINE, ficpar);
5929: numlinepar++;
1.141 brouard 5930: fputs(line,stdout);
1.126 brouard 5931: fputs(line,ficparo);
5932: fputs(line,ficlog);
5933: }
5934: ungetc(c,ficpar);
5935:
5936: for(i=1; i <=nlstate; i++){
5937: for(j=1; j <=nlstate+ndeath-1; j++){
5938: fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164 brouard 5939: if ( (i1-i) * (j1-j) != 0){
1.126 brouard 5940: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
5941: exit(1);
5942: }
5943: printf("%1d%1d",i,j);
5944: fprintf(ficparo,"%1d%1d",i1,j1);
5945: fprintf(ficlog,"%1d%1d",i1,j1);
5946: for(k=1; k<=ncovmodel;k++){
5947: fscanf(ficpar,"%le",&delti3[i][j][k]);
5948: printf(" %le",delti3[i][j][k]);
5949: fprintf(ficparo," %le",delti3[i][j][k]);
5950: fprintf(ficlog," %le",delti3[i][j][k]);
5951: }
5952: fscanf(ficpar,"\n");
5953: numlinepar++;
5954: printf("\n");
5955: fprintf(ficparo,"\n");
5956: fprintf(ficlog,"\n");
5957: }
5958: }
5959: fflush(ficlog);
5960:
1.145 brouard 5961: /* Reads covariance matrix */
1.126 brouard 5962: delti=delti3[1][1];
5963:
5964:
5965: /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
5966:
5967: /* Reads comments: lines beginning with '#' */
5968: while((c=getc(ficpar))=='#' && c!= EOF){
5969: ungetc(c,ficpar);
5970: fgets(line, MAXLINE, ficpar);
5971: numlinepar++;
1.141 brouard 5972: fputs(line,stdout);
1.126 brouard 5973: fputs(line,ficparo);
5974: fputs(line,ficlog);
5975: }
5976: ungetc(c,ficpar);
5977:
5978: matcov=matrix(1,npar,1,npar);
1.131 brouard 5979: for(i=1; i <=npar; i++)
5980: for(j=1; j <=npar; j++) matcov[i][j]=0.;
5981:
1.126 brouard 5982: for(i=1; i <=npar; i++){
1.145 brouard 5983: fscanf(ficpar,"%s",str);
1.126 brouard 5984: if(mle==1)
5985: printf("%s",str);
5986: fprintf(ficlog,"%s",str);
5987: fprintf(ficparo,"%s",str);
5988: for(j=1; j <=i; j++){
5989: fscanf(ficpar," %le",&matcov[i][j]);
5990: if(mle==1){
5991: printf(" %.5le",matcov[i][j]);
5992: }
5993: fprintf(ficlog," %.5le",matcov[i][j]);
5994: fprintf(ficparo," %.5le",matcov[i][j]);
5995: }
5996: fscanf(ficpar,"\n");
5997: numlinepar++;
5998: if(mle==1)
5999: printf("\n");
6000: fprintf(ficlog,"\n");
6001: fprintf(ficparo,"\n");
6002: }
6003: for(i=1; i <=npar; i++)
6004: for(j=i+1;j<=npar;j++)
6005: matcov[i][j]=matcov[j][i];
6006:
6007: if(mle==1)
6008: printf("\n");
6009: fprintf(ficlog,"\n");
6010:
6011: fflush(ficlog);
6012:
6013: /*-------- Rewriting parameter file ----------*/
6014: strcpy(rfileres,"r"); /* "Rparameterfile */
6015: strcat(rfileres,optionfilefiname); /* Parameter file first name*/
6016: strcat(rfileres,"."); /* */
6017: strcat(rfileres,optionfilext); /* Other files have txt extension */
6018: if((ficres =fopen(rfileres,"w"))==NULL) {
6019: printf("Problem writing new parameter file: %s\n", fileres);goto end;
6020: fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
6021: }
6022: fprintf(ficres,"#%s\n",version);
6023: } /* End of mle != -3 */
6024:
6025:
6026: n= lastobs;
6027: num=lvector(1,n);
6028: moisnais=vector(1,n);
6029: annais=vector(1,n);
6030: moisdc=vector(1,n);
6031: andc=vector(1,n);
6032: agedc=vector(1,n);
6033: cod=ivector(1,n);
6034: weight=vector(1,n);
6035: for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
6036: mint=matrix(1,maxwav,1,n);
6037: anint=matrix(1,maxwav,1,n);
1.131 brouard 6038: s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */
1.126 brouard 6039: tab=ivector(1,NCOVMAX);
1.144 brouard 6040: ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.126 brouard 6041:
1.136 brouard 6042: /* Reads data from file datafile */
6043: if (readdata(datafile, firstobs, lastobs, &imx)==1)
6044: goto end;
6045:
6046: /* Calculation of the number of parameters from char model */
1.137 brouard 6047: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4
6048: k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
6049: k=3 V4 Tvar[k=3]= 4 (from V4)
6050: k=2 V1 Tvar[k=2]= 1 (from V1)
6051: k=1 Tvar[1]=2 (from V2)
6052: */
6053: Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
6054: /* V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs).
6055: For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4,
6056: Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
6057: */
6058: /* For model-covariate k tells which data-covariate to use but
6059: because this model-covariate is a construction we invent a new column
6060: ncovcol + k1
6061: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
6062: Tvar[3=V1*V4]=4+1 etc */
1.145 brouard 6063: Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137 brouard 6064: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
6065: if V2+V1+V1*V4+age*V3+V3*V2 TProd[k1=2]=5 (V3*V2)
6066: */
1.145 brouard 6067: Tvaraff=ivector(1,NCOVMAX); /* Unclear */
6068: 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 6069: * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd.
6070: * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145 brouard 6071: Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137 brouard 6072: 4 covariates (3 plus signs)
6073: Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
6074: */
1.136 brouard 6075:
6076: if(decodemodel(model, lastobs) == 1)
6077: goto end;
6078:
1.137 brouard 6079: if((double)(lastobs-imx)/(double)imx > 1.10){
6080: nbwarn++;
6081: 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);
6082: 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);
6083: }
1.136 brouard 6084: /* if(mle==1){*/
1.137 brouard 6085: if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
6086: for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136 brouard 6087: }
6088:
6089: /*-calculation of age at interview from date of interview and age at death -*/
6090: agev=matrix(1,maxwav,1,imx);
6091:
6092: if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
6093: goto end;
6094:
1.126 brouard 6095:
1.136 brouard 6096: agegomp=(int)agemin;
6097: free_vector(moisnais,1,n);
6098: free_vector(annais,1,n);
1.126 brouard 6099: /* free_matrix(mint,1,maxwav,1,n);
6100: free_matrix(anint,1,maxwav,1,n);*/
6101: free_vector(moisdc,1,n);
6102: free_vector(andc,1,n);
1.145 brouard 6103: /* */
6104:
1.126 brouard 6105: wav=ivector(1,imx);
6106: dh=imatrix(1,lastpass-firstpass+1,1,imx);
6107: bh=imatrix(1,lastpass-firstpass+1,1,imx);
6108: mw=imatrix(1,lastpass-firstpass+1,1,imx);
6109:
6110: /* Concatenates waves */
6111: concatwav(wav, dh, bh, mw, s, agedc, agev, firstpass, lastpass, imx, nlstate, stepm);
1.145 brouard 6112: /* */
6113:
1.126 brouard 6114: /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
6115:
6116: nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
6117: ncodemax[1]=1;
1.145 brouard 6118: Ndum =ivector(-1,NCOVMAX);
6119: if (ncovmodel > 2)
6120: tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
6121:
6122: codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
6123: /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
6124: h=0;
6125:
6126:
6127: /*if (cptcovn > 0) */
1.126 brouard 6128:
1.145 brouard 6129:
1.126 brouard 6130: m=pow(2,cptcoveff);
6131:
1.131 brouard 6132: for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
1.143 brouard 6133: 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 */
6134: for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
6135: 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 6136: h++;
1.141 brouard 6137: if (h>m)
1.136 brouard 6138: h=1;
1.144 brouard 6139: /**< codtab(h,k) k = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.143 brouard 6140: * h 1 2 3 4
6141: *______________________________
6142: * 1 i=1 1 i=1 1 i=1 1 i=1 1
6143: * 2 2 1 1 1
6144: * 3 i=2 1 2 1 1
6145: * 4 2 2 1 1
6146: * 5 i=3 1 i=2 1 2 1
6147: * 6 2 1 2 1
6148: * 7 i=4 1 2 2 1
6149: * 8 2 2 2 1
6150: * 9 i=5 1 i=3 1 i=2 1 1
6151: * 10 2 1 1 1
6152: * 11 i=6 1 2 1 1
6153: * 12 2 2 1 1
6154: * 13 i=7 1 i=4 1 2 1
6155: * 14 2 1 2 1
6156: * 15 i=8 1 2 2 1
6157: * 16 2 2 2 1
6158: */
1.141 brouard 6159: codtab[h][k]=j;
1.145 brouard 6160: /*codtab[h][Tvar[k]]=j;*/
1.130 brouard 6161: 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 6162: }
6163: }
6164: }
6165: }
6166: /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
6167: codtab[1][2]=1;codtab[2][2]=2; */
6168: /* for(i=1; i <=m ;i++){
6169: for(k=1; k <=cptcovn; k++){
1.131 brouard 6170: printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
1.126 brouard 6171: }
6172: printf("\n");
6173: }
6174: scanf("%d",i);*/
1.145 brouard 6175:
6176: free_ivector(Ndum,-1,NCOVMAX);
6177:
6178:
1.126 brouard 6179:
6180: /*------------ gnuplot -------------*/
6181: strcpy(optionfilegnuplot,optionfilefiname);
6182: if(mle==-3)
6183: strcat(optionfilegnuplot,"-mort");
6184: strcat(optionfilegnuplot,".gp");
6185:
6186: if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
6187: printf("Problem with file %s",optionfilegnuplot);
6188: }
6189: else{
6190: fprintf(ficgp,"\n# %s\n", version);
6191: fprintf(ficgp,"# %s\n", optionfilegnuplot);
1.141 brouard 6192: //fprintf(ficgp,"set missing 'NaNq'\n");
6193: fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126 brouard 6194: }
6195: /* fclose(ficgp);*/
6196: /*--------- index.htm --------*/
6197:
6198: strcpy(optionfilehtm,optionfilefiname); /* Main html file */
6199: if(mle==-3)
6200: strcat(optionfilehtm,"-mort");
6201: strcat(optionfilehtm,".htm");
6202: if((fichtm=fopen(optionfilehtm,"w"))==NULL) {
1.131 brouard 6203: printf("Problem with %s \n",optionfilehtm);
6204: exit(0);
1.126 brouard 6205: }
6206:
6207: strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
6208: strcat(optionfilehtmcov,"-cov.htm");
6209: if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL) {
6210: printf("Problem with %s \n",optionfilehtmcov), exit(0);
6211: }
6212: else{
6213: fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6214: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6215: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
6216: optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
6217: }
6218:
6219: fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6220: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6221: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
6222: \n\
6223: <hr size=\"2\" color=\"#EC5E5E\">\
6224: <ul><li><h4>Parameter files</h4>\n\
6225: - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
6226: - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
6227: - Log file of the run: <a href=\"%s\">%s</a><br>\n\
6228: - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
6229: - Date and time at start: %s</ul>\n",\
6230: optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
6231: optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
6232: fileres,fileres,\
6233: filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
6234: fflush(fichtm);
6235:
6236: strcpy(pathr,path);
6237: strcat(pathr,optionfilefiname);
6238: chdir(optionfilefiname); /* Move to directory named optionfile */
6239:
6240: /* Calculates basic frequencies. Computes observed prevalence at single age
6241: and prints on file fileres'p'. */
6242: freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
6243:
6244: fprintf(fichtm,"\n");
6245: fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
6246: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
6247: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
6248: imx,agemin,agemax,jmin,jmax,jmean);
6249: pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6250: oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6251: newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6252: savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6253: oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
6254:
6255:
6256: /* For Powell, parameters are in a vector p[] starting at p[1]
6257: so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
6258: p=param[1][1]; /* *(*(*(param +1)+1)+0) */
6259:
6260: globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
6261:
6262: if (mle==-3){
1.136 brouard 6263: ximort=matrix(1,NDIM,1,NDIM);
6264: /* ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126 brouard 6265: cens=ivector(1,n);
6266: ageexmed=vector(1,n);
6267: agecens=vector(1,n);
6268: dcwave=ivector(1,n);
6269:
6270: for (i=1; i<=imx; i++){
6271: dcwave[i]=-1;
6272: for (m=firstpass; m<=lastpass; m++)
6273: if (s[m][i]>nlstate) {
6274: dcwave[i]=m;
6275: /* printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
6276: break;
6277: }
6278: }
6279:
6280: for (i=1; i<=imx; i++) {
6281: if (wav[i]>0){
6282: ageexmed[i]=agev[mw[1][i]][i];
6283: j=wav[i];
6284: agecens[i]=1.;
6285:
6286: if (ageexmed[i]> 1 && wav[i] > 0){
6287: agecens[i]=agev[mw[j][i]][i];
6288: cens[i]= 1;
6289: }else if (ageexmed[i]< 1)
6290: cens[i]= -1;
6291: if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
6292: cens[i]=0 ;
6293: }
6294: else cens[i]=-1;
6295: }
6296:
6297: for (i=1;i<=NDIM;i++) {
6298: for (j=1;j<=NDIM;j++)
6299: ximort[i][j]=(i == j ? 1.0 : 0.0);
6300: }
6301:
1.145 brouard 6302: /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126 brouard 6303: /*printf("%lf %lf", p[1], p[2]);*/
6304:
6305:
1.136 brouard 6306: #ifdef GSL
6307: printf("GSL optimization\n"); fprintf(ficlog,"Powell\n");
1.162 brouard 6308: #else
1.126 brouard 6309: printf("Powell\n"); fprintf(ficlog,"Powell\n");
1.136 brouard 6310: #endif
1.126 brouard 6311: strcpy(filerespow,"pow-mort");
6312: strcat(filerespow,fileres);
6313: if((ficrespow=fopen(filerespow,"w"))==NULL) {
6314: printf("Problem with resultfile: %s\n", filerespow);
6315: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
6316: }
1.136 brouard 6317: #ifdef GSL
6318: fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162 brouard 6319: #else
1.126 brouard 6320: fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136 brouard 6321: #endif
1.126 brouard 6322: /* for (i=1;i<=nlstate;i++)
6323: for(j=1;j<=nlstate+ndeath;j++)
6324: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
6325: */
6326: fprintf(ficrespow,"\n");
1.136 brouard 6327: #ifdef GSL
6328: /* gsl starts here */
6329: T = gsl_multimin_fminimizer_nmsimplex;
6330: gsl_multimin_fminimizer *sfm = NULL;
6331: gsl_vector *ss, *x;
6332: gsl_multimin_function minex_func;
6333:
6334: /* Initial vertex size vector */
6335: ss = gsl_vector_alloc (NDIM);
6336:
6337: if (ss == NULL){
6338: GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
6339: }
6340: /* Set all step sizes to 1 */
6341: gsl_vector_set_all (ss, 0.001);
6342:
6343: /* Starting point */
1.126 brouard 6344:
1.136 brouard 6345: x = gsl_vector_alloc (NDIM);
6346:
6347: if (x == NULL){
6348: gsl_vector_free(ss);
6349: GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
6350: }
6351:
6352: /* Initialize method and iterate */
6353: /* p[1]=0.0268; p[NDIM]=0.083; */
6354: /* gsl_vector_set(x, 0, 0.0268); */
6355: /* gsl_vector_set(x, 1, 0.083); */
6356: gsl_vector_set(x, 0, p[1]);
6357: gsl_vector_set(x, 1, p[2]);
6358:
6359: minex_func.f = &gompertz_f;
6360: minex_func.n = NDIM;
6361: minex_func.params = (void *)&p; /* ??? */
6362:
6363: sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
6364: gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
6365:
6366: printf("Iterations beginning .....\n\n");
6367: printf("Iter. # Intercept Slope -Log Likelihood Simplex size\n");
6368:
6369: iteri=0;
6370: while (rval == GSL_CONTINUE){
6371: iteri++;
6372: status = gsl_multimin_fminimizer_iterate(sfm);
6373:
6374: if (status) printf("error: %s\n", gsl_strerror (status));
6375: fflush(0);
6376:
6377: if (status)
6378: break;
6379:
6380: rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
6381: ssval = gsl_multimin_fminimizer_size (sfm);
6382:
6383: if (rval == GSL_SUCCESS)
6384: printf ("converged to a local maximum at\n");
6385:
6386: printf("%5d ", iteri);
6387: for (it = 0; it < NDIM; it++){
6388: printf ("%10.5f ", gsl_vector_get (sfm->x, it));
6389: }
6390: printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
6391: }
6392:
6393: printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
6394:
6395: gsl_vector_free(x); /* initial values */
6396: gsl_vector_free(ss); /* inital step size */
6397: for (it=0; it<NDIM; it++){
6398: p[it+1]=gsl_vector_get(sfm->x,it);
6399: fprintf(ficrespow," %.12lf", p[it]);
6400: }
6401: gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1) */
6402: #endif
6403: #ifdef POWELL
6404: powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
6405: #endif
1.126 brouard 6406: fclose(ficrespow);
6407:
6408: hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);
6409:
6410: for(i=1; i <=NDIM; i++)
6411: for(j=i+1;j<=NDIM;j++)
6412: matcov[i][j]=matcov[j][i];
6413:
6414: printf("\nCovariance matrix\n ");
6415: for(i=1; i <=NDIM; i++) {
6416: for(j=1;j<=NDIM;j++){
6417: printf("%f ",matcov[i][j]);
6418: }
6419: printf("\n ");
6420: }
6421:
6422: printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
6423: for (i=1;i<=NDIM;i++)
6424: printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
6425:
6426: lsurv=vector(1,AGESUP);
6427: lpop=vector(1,AGESUP);
6428: tpop=vector(1,AGESUP);
6429: lsurv[agegomp]=100000;
6430:
6431: for (k=agegomp;k<=AGESUP;k++) {
6432: agemortsup=k;
6433: if (p[1]*exp(p[2]*(k-agegomp))>1) break;
6434: }
6435:
6436: for (k=agegomp;k<agemortsup;k++)
6437: lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
6438:
6439: for (k=agegomp;k<agemortsup;k++){
6440: lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
6441: sumlpop=sumlpop+lpop[k];
6442: }
6443:
6444: tpop[agegomp]=sumlpop;
6445: for (k=agegomp;k<(agemortsup-3);k++){
6446: /* tpop[k+1]=2;*/
6447: tpop[k+1]=tpop[k]-lpop[k];
6448: }
6449:
6450:
6451: printf("\nAge lx qx dx Lx Tx e(x)\n");
6452: for (k=agegomp;k<(agemortsup-2);k++)
6453: 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]);
6454:
6455:
6456: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6457: printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6458:
6459: printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
6460: stepm, weightopt,\
6461: model,imx,p,matcov,agemortsup);
6462:
6463: free_vector(lsurv,1,AGESUP);
6464: free_vector(lpop,1,AGESUP);
6465: free_vector(tpop,1,AGESUP);
1.136 brouard 6466: #ifdef GSL
6467: free_ivector(cens,1,n);
6468: free_vector(agecens,1,n);
6469: free_ivector(dcwave,1,n);
6470: free_matrix(ximort,1,NDIM,1,NDIM);
6471: #endif
1.126 brouard 6472: } /* Endof if mle==-3 */
6473:
6474: else{ /* For mle >=1 */
1.132 brouard 6475: globpr=0;/* debug */
6476: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126 brouard 6477: printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6478: for (k=1; k<=npar;k++)
6479: printf(" %d %8.5f",k,p[k]);
6480: printf("\n");
6481: globpr=1; /* to print the contributions */
6482: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
6483: printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6484: for (k=1; k<=npar;k++)
6485: printf(" %d %8.5f",k,p[k]);
6486: printf("\n");
6487: if(mle>=1){ /* Could be 1 or 2 */
6488: mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
6489: }
6490:
6491: /*--------- results files --------------*/
6492: 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);
6493:
6494:
6495: fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6496: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6497: fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6498: for(i=1,jk=1; i <=nlstate; i++){
6499: for(k=1; k <=(nlstate+ndeath); k++){
6500: if (k != i) {
6501: printf("%d%d ",i,k);
6502: fprintf(ficlog,"%d%d ",i,k);
6503: fprintf(ficres,"%1d%1d ",i,k);
6504: for(j=1; j <=ncovmodel; j++){
6505: printf("%lf ",p[jk]);
6506: fprintf(ficlog,"%lf ",p[jk]);
6507: fprintf(ficres,"%lf ",p[jk]);
6508: jk++;
6509: }
6510: printf("\n");
6511: fprintf(ficlog,"\n");
6512: fprintf(ficres,"\n");
6513: }
6514: }
6515: }
6516: if(mle!=0){
6517: /* Computing hessian and covariance matrix */
6518: ftolhess=ftol; /* Usually correct */
6519: hesscov(matcov, p, npar, delti, ftolhess, func);
6520: }
6521: fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
6522: printf("# Scales (for hessian or gradient estimation)\n");
6523: fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
6524: for(i=1,jk=1; i <=nlstate; i++){
6525: for(j=1; j <=nlstate+ndeath; j++){
6526: if (j!=i) {
6527: fprintf(ficres,"%1d%1d",i,j);
6528: printf("%1d%1d",i,j);
6529: fprintf(ficlog,"%1d%1d",i,j);
6530: for(k=1; k<=ncovmodel;k++){
6531: printf(" %.5e",delti[jk]);
6532: fprintf(ficlog," %.5e",delti[jk]);
6533: fprintf(ficres," %.5e",delti[jk]);
6534: jk++;
6535: }
6536: printf("\n");
6537: fprintf(ficlog,"\n");
6538: fprintf(ficres,"\n");
6539: }
6540: }
6541: }
6542:
6543: 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");
6544: if(mle>=1)
6545: 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");
6546: 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");
6547: /* # 121 Var(a12)\n\ */
6548: /* # 122 Cov(b12,a12) Var(b12)\n\ */
6549: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
6550: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
6551: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
6552: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
6553: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
6554: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
6555:
6556:
6557: /* Just to have a covariance matrix which will be more understandable
6558: even is we still don't want to manage dictionary of variables
6559: */
6560: for(itimes=1;itimes<=2;itimes++){
6561: jj=0;
6562: for(i=1; i <=nlstate; i++){
6563: for(j=1; j <=nlstate+ndeath; j++){
6564: if(j==i) continue;
6565: for(k=1; k<=ncovmodel;k++){
6566: jj++;
6567: ca[0]= k+'a'-1;ca[1]='\0';
6568: if(itimes==1){
6569: if(mle>=1)
6570: printf("#%1d%1d%d",i,j,k);
6571: fprintf(ficlog,"#%1d%1d%d",i,j,k);
6572: fprintf(ficres,"#%1d%1d%d",i,j,k);
6573: }else{
6574: if(mle>=1)
6575: printf("%1d%1d%d",i,j,k);
6576: fprintf(ficlog,"%1d%1d%d",i,j,k);
6577: fprintf(ficres,"%1d%1d%d",i,j,k);
6578: }
6579: ll=0;
6580: for(li=1;li <=nlstate; li++){
6581: for(lj=1;lj <=nlstate+ndeath; lj++){
6582: if(lj==li) continue;
6583: for(lk=1;lk<=ncovmodel;lk++){
6584: ll++;
6585: if(ll<=jj){
6586: cb[0]= lk +'a'-1;cb[1]='\0';
6587: if(ll<jj){
6588: if(itimes==1){
6589: if(mle>=1)
6590: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6591: fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6592: fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6593: }else{
6594: if(mle>=1)
6595: printf(" %.5e",matcov[jj][ll]);
6596: fprintf(ficlog," %.5e",matcov[jj][ll]);
6597: fprintf(ficres," %.5e",matcov[jj][ll]);
6598: }
6599: }else{
6600: if(itimes==1){
6601: if(mle>=1)
6602: printf(" Var(%s%1d%1d)",ca,i,j);
6603: fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
6604: fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
6605: }else{
6606: if(mle>=1)
6607: printf(" %.5e",matcov[jj][ll]);
6608: fprintf(ficlog," %.5e",matcov[jj][ll]);
6609: fprintf(ficres," %.5e",matcov[jj][ll]);
6610: }
6611: }
6612: }
6613: } /* end lk */
6614: } /* end lj */
6615: } /* end li */
6616: if(mle>=1)
6617: printf("\n");
6618: fprintf(ficlog,"\n");
6619: fprintf(ficres,"\n");
6620: numlinepar++;
6621: } /* end k*/
6622: } /*end j */
6623: } /* end i */
6624: } /* end itimes */
6625:
6626: fflush(ficlog);
6627: fflush(ficres);
6628:
6629: while((c=getc(ficpar))=='#' && c!= EOF){
6630: ungetc(c,ficpar);
6631: fgets(line, MAXLINE, ficpar);
1.141 brouard 6632: fputs(line,stdout);
1.126 brouard 6633: fputs(line,ficparo);
6634: }
6635: ungetc(c,ficpar);
6636:
6637: estepm=0;
6638: fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
6639: if (estepm==0 || estepm < stepm) estepm=stepm;
6640: if (fage <= 2) {
6641: bage = ageminpar;
6642: fage = agemaxpar;
6643: }
6644:
6645: fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
6646: fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6647: fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6648:
6649: while((c=getc(ficpar))=='#' && c!= EOF){
6650: ungetc(c,ficpar);
6651: fgets(line, MAXLINE, ficpar);
1.141 brouard 6652: fputs(line,stdout);
1.126 brouard 6653: fputs(line,ficparo);
6654: }
6655: ungetc(c,ficpar);
6656:
6657: 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);
6658: 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);
6659: 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);
6660: printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
6661: 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);
6662:
6663: while((c=getc(ficpar))=='#' && c!= EOF){
6664: ungetc(c,ficpar);
6665: fgets(line, MAXLINE, ficpar);
1.141 brouard 6666: fputs(line,stdout);
1.126 brouard 6667: fputs(line,ficparo);
6668: }
6669: ungetc(c,ficpar);
6670:
6671:
6672: dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
6673: dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
6674:
6675: fscanf(ficpar,"pop_based=%d\n",&popbased);
6676: fprintf(ficparo,"pop_based=%d\n",popbased);
6677: fprintf(ficres,"pop_based=%d\n",popbased);
6678:
6679: while((c=getc(ficpar))=='#' && c!= EOF){
6680: ungetc(c,ficpar);
6681: fgets(line, MAXLINE, ficpar);
1.141 brouard 6682: fputs(line,stdout);
1.126 brouard 6683: fputs(line,ficparo);
6684: }
6685: ungetc(c,ficpar);
6686:
6687: 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);
6688: 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);
6689: 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);
6690: 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);
6691: 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);
6692: /* day and month of proj2 are not used but only year anproj2.*/
6693:
6694:
6695:
1.145 brouard 6696: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
6697: /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126 brouard 6698:
6699: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6700: printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6701:
6702: printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
6703: model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
6704: jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
6705:
6706: /*------------ free_vector -------------*/
6707: /* chdir(path); */
6708:
6709: free_ivector(wav,1,imx);
6710: free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
6711: free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
6712: free_imatrix(mw,1,lastpass-firstpass+1,1,imx);
6713: free_lvector(num,1,n);
6714: free_vector(agedc,1,n);
6715: /*free_matrix(covar,0,NCOVMAX,1,n);*/
6716: /*free_matrix(covar,1,NCOVMAX,1,n);*/
6717: fclose(ficparo);
6718: fclose(ficres);
6719:
6720:
6721: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
1.145 brouard 6722: #include "prevlim.h" /* Use ficrespl, ficlog */
1.126 brouard 6723: fclose(ficrespl);
6724:
1.145 brouard 6725: #ifdef FREEEXIT2
6726: #include "freeexit2.h"
6727: #endif
6728:
1.126 brouard 6729: /*------------- h Pij x at various ages ------------*/
1.145 brouard 6730: #include "hpijx.h"
6731: fclose(ficrespij);
1.126 brouard 6732:
1.145 brouard 6733: /*-------------- Variance of one-step probabilities---*/
6734: k=1;
1.126 brouard 6735: varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
6736:
6737:
6738: probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
6739: for(i=1;i<=AGESUP;i++)
6740: for(j=1;j<=NCOVMAX;j++)
6741: for(k=1;k<=NCOVMAX;k++)
6742: probs[i][j][k]=0.;
6743:
6744: /*---------- Forecasting ------------------*/
6745: /*if((stepm == 1) && (strcmp(model,".")==0)){*/
6746: if(prevfcast==1){
6747: /* if(stepm ==1){*/
6748: prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
6749: /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
6750: /* } */
6751: /* else{ */
6752: /* erreur=108; */
6753: /* 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); */
6754: /* 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); */
6755: /* } */
6756: }
6757:
6758:
1.127 brouard 6759: /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
6760:
6761: prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
6762: /* 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",\
6763: ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
6764: */
1.126 brouard 6765:
1.127 brouard 6766: if (mobilav!=0) {
6767: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
6768: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
6769: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
6770: printf(" Error in movingaverage mobilav=%d\n",mobilav);
6771: }
1.126 brouard 6772: }
6773:
6774:
1.127 brouard 6775: /*---------- Health expectancies, no variances ------------*/
6776:
1.126 brouard 6777: strcpy(filerese,"e");
6778: strcat(filerese,fileres);
6779: if((ficreseij=fopen(filerese,"w"))==NULL) {
6780: printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
6781: fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
6782: }
6783: printf("Computing Health Expectancies: result on file '%s' \n", filerese);
6784: fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
1.145 brouard 6785: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6786: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6787:
6788: for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127 brouard 6789: fprintf(ficreseij,"\n#****** ");
6790: for(j=1;j<=cptcoveff;j++) {
6791: fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6792: }
6793: fprintf(ficreseij,"******\n");
6794:
6795: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6796: oldm=oldms;savm=savms;
6797: evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);
6798:
6799: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145 brouard 6800: /*}*/
1.127 brouard 6801: }
6802: fclose(ficreseij);
6803:
6804:
6805: /*---------- Health expectancies and variances ------------*/
6806:
6807:
6808: strcpy(filerest,"t");
6809: strcat(filerest,fileres);
6810: if((ficrest=fopen(filerest,"w"))==NULL) {
6811: printf("Problem with total LE resultfile: %s\n", filerest);goto end;
6812: fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
6813: }
6814: printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
6815: fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
6816:
1.126 brouard 6817:
6818: strcpy(fileresstde,"stde");
6819: strcat(fileresstde,fileres);
6820: if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
6821: printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
6822: fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
6823: }
6824: printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
6825: fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
6826:
6827: strcpy(filerescve,"cve");
6828: strcat(filerescve,fileres);
6829: if((ficrescveij=fopen(filerescve,"w"))==NULL) {
6830: printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
6831: fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
6832: }
6833: printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
6834: fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
6835:
6836: strcpy(fileresv,"v");
6837: strcat(fileresv,fileres);
6838: if((ficresvij=fopen(fileresv,"w"))==NULL) {
6839: printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
6840: fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
6841: }
6842: printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
6843: fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
6844:
1.145 brouard 6845: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6846: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6847:
6848: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6849: fprintf(ficrest,"\n#****** ");
1.126 brouard 6850: for(j=1;j<=cptcoveff;j++)
6851: fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6852: fprintf(ficrest,"******\n");
6853:
6854: fprintf(ficresstdeij,"\n#****** ");
6855: fprintf(ficrescveij,"\n#****** ");
6856: for(j=1;j<=cptcoveff;j++) {
6857: fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6858: fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6859: }
6860: fprintf(ficresstdeij,"******\n");
6861: fprintf(ficrescveij,"******\n");
6862:
6863: fprintf(ficresvij,"\n#****** ");
6864: for(j=1;j<=cptcoveff;j++)
6865: fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6866: fprintf(ficresvij,"******\n");
6867:
6868: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6869: oldm=oldms;savm=savms;
1.127 brouard 6870: cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
1.145 brouard 6871: /*
6872: */
6873: /* goto endfree; */
1.126 brouard 6874:
6875: vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6876: pstamp(ficrest);
1.145 brouard 6877:
6878:
1.128 brouard 6879: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.145 brouard 6880: oldm=oldms;savm=savms; /* Segmentation fault */
1.161 brouard 6881: cptcod= 0; /* To be deleted */
6882: 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 6883: 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 6884: if(vpopbased==1)
6885: 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);
6886: else
6887: fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
6888: fprintf(ficrest,"# Age e.. (std) ");
6889: for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
6890: fprintf(ficrest,"\n");
1.126 brouard 6891:
1.128 brouard 6892: epj=vector(1,nlstate+1);
6893: for(age=bage; age <=fage ;age++){
6894: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
6895: if (vpopbased==1) {
6896: if(mobilav ==0){
6897: for(i=1; i<=nlstate;i++)
6898: prlim[i][i]=probs[(int)age][i][k];
6899: }else{ /* mobilav */
6900: for(i=1; i<=nlstate;i++)
6901: prlim[i][i]=mobaverage[(int)age][i][k];
6902: }
1.126 brouard 6903: }
6904:
1.128 brouard 6905: fprintf(ficrest," %4.0f",age);
6906: for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
6907: for(i=1, epj[j]=0.;i <=nlstate;i++) {
6908: epj[j] += prlim[i][i]*eij[i][j][(int)age];
6909: /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
6910: }
6911: epj[nlstate+1] +=epj[j];
1.126 brouard 6912: }
6913:
1.128 brouard 6914: for(i=1, vepp=0.;i <=nlstate;i++)
6915: for(j=1;j <=nlstate;j++)
6916: vepp += vareij[i][j][(int)age];
6917: fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
6918: for(j=1;j <=nlstate;j++){
6919: fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
6920: }
6921: fprintf(ficrest,"\n");
1.126 brouard 6922: }
6923: }
6924: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
6925: free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
6926: free_vector(epj,1,nlstate+1);
1.145 brouard 6927: /*}*/
1.126 brouard 6928: }
6929: free_vector(weight,1,n);
1.145 brouard 6930: free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126 brouard 6931: free_imatrix(s,1,maxwav+1,1,n);
6932: free_matrix(anint,1,maxwav,1,n);
6933: free_matrix(mint,1,maxwav,1,n);
6934: free_ivector(cod,1,n);
6935: free_ivector(tab,1,NCOVMAX);
6936: fclose(ficresstdeij);
6937: fclose(ficrescveij);
6938: fclose(ficresvij);
6939: fclose(ficrest);
6940: fclose(ficpar);
6941:
6942: /*------- Variance of period (stable) prevalence------*/
6943:
6944: strcpy(fileresvpl,"vpl");
6945: strcat(fileresvpl,fileres);
6946: if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
6947: printf("Problem with variance of period (stable) prevalence resultfile: %s\n", fileresvpl);
6948: exit(0);
6949: }
6950: printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
6951:
1.145 brouard 6952: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6953: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6954:
6955: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6956: fprintf(ficresvpl,"\n#****** ");
1.126 brouard 6957: for(j=1;j<=cptcoveff;j++)
6958: fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6959: fprintf(ficresvpl,"******\n");
6960:
6961: varpl=matrix(1,nlstate,(int) bage, (int) fage);
6962: oldm=oldms;savm=savms;
6963: varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
6964: free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145 brouard 6965: /*}*/
1.126 brouard 6966: }
6967:
6968: fclose(ficresvpl);
6969:
6970: /*---------- End : free ----------------*/
6971: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
6972: free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
6973: } /* mle==-3 arrives here for freeing */
1.164 brouard 6974: /* endfree:*/
1.141 brouard 6975: free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126 brouard 6976: free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
6977: free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
6978: free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
6979: free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
6980: free_matrix(covar,0,NCOVMAX,1,n);
6981: free_matrix(matcov,1,npar,1,npar);
6982: /*free_vector(delti,1,npar);*/
6983: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
6984: free_matrix(agev,1,maxwav,1,imx);
6985: free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
6986:
1.145 brouard 6987: free_ivector(ncodemax,1,NCOVMAX);
6988: free_ivector(Tvar,1,NCOVMAX);
6989: free_ivector(Tprod,1,NCOVMAX);
6990: free_ivector(Tvaraff,1,NCOVMAX);
6991: free_ivector(Tage,1,NCOVMAX);
1.126 brouard 6992:
6993: free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
6994: free_imatrix(codtab,1,100,1,10);
6995: fflush(fichtm);
6996: fflush(ficgp);
6997:
6998:
6999: if((nberr >0) || (nbwarn>0)){
7000: printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
7001: fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
7002: }else{
7003: printf("End of Imach\n");
7004: fprintf(ficlog,"End of Imach\n");
7005: }
7006: printf("See log file on %s\n",filelog);
7007: /* gettimeofday(&end_time, (struct timezone*)0);*/ /* after time */
1.157 brouard 7008: /*(void) gettimeofday(&end_time,&tzp);*/
7009: rend_time = time(NULL);
7010: end_time = *localtime(&rend_time);
7011: /* tml = *localtime(&end_time.tm_sec); */
7012: strcpy(strtend,asctime(&end_time));
1.126 brouard 7013: printf("Local time at start %s\nLocal time at end %s",strstart, strtend);
7014: fprintf(ficlog,"Local time at start %s\nLocal time at end %s\n",strstart, strtend);
1.157 brouard 7015: printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126 brouard 7016:
1.157 brouard 7017: printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
7018: fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
7019: fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126 brouard 7020: /* printf("Total time was %d uSec.\n", total_usecs);*/
7021: /* if(fileappend(fichtm,optionfilehtm)){ */
7022: fprintf(fichtm,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
7023: fclose(fichtm);
7024: fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
7025: fclose(fichtmcov);
7026: fclose(ficgp);
7027: fclose(ficlog);
7028: /*------ End -----------*/
7029:
7030:
7031: printf("Before Current directory %s!\n",pathcd);
7032: if(chdir(pathcd) != 0)
7033: printf("Can't move to directory %s!\n",path);
7034: if(getcwd(pathcd,MAXLINE) > 0)
7035: printf("Current directory %s!\n",pathcd);
7036: /*strcat(plotcmd,CHARSEPARATOR);*/
7037: sprintf(plotcmd,"gnuplot");
1.157 brouard 7038: #ifdef _WIN32
1.126 brouard 7039: sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
7040: #endif
7041: if(!stat(plotcmd,&info)){
1.158 brouard 7042: printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 7043: if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158 brouard 7044: printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126 brouard 7045: }else
7046: strcpy(pplotcmd,plotcmd);
1.157 brouard 7047: #ifdef __unix
1.126 brouard 7048: strcpy(plotcmd,GNUPLOTPROGRAM);
7049: if(!stat(plotcmd,&info)){
1.158 brouard 7050: printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 7051: }else
7052: strcpy(pplotcmd,plotcmd);
7053: #endif
7054: }else
7055: strcpy(pplotcmd,plotcmd);
7056:
7057: sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158 brouard 7058: printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 7059:
7060: if((outcmd=system(plotcmd)) != 0){
1.158 brouard 7061: printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154 brouard 7062: printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152 brouard 7063: sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150 brouard 7064: if((outcmd=system(plotcmd)) != 0)
1.153 brouard 7065: printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126 brouard 7066: }
1.158 brouard 7067: printf(" Successful, please wait...");
1.126 brouard 7068: while (z[0] != 'q') {
7069: /* chdir(path); */
1.154 brouard 7070: printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126 brouard 7071: scanf("%s",z);
7072: /* if (z[0] == 'c') system("./imach"); */
7073: if (z[0] == 'e') {
1.158 brouard 7074: #ifdef __APPLE__
1.152 brouard 7075: sprintf(pplotcmd, "open %s", optionfilehtm);
1.157 brouard 7076: #elif __linux
7077: sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153 brouard 7078: #else
1.152 brouard 7079: sprintf(pplotcmd, "%s", optionfilehtm);
1.153 brouard 7080: #endif
7081: printf("Starting browser with: %s",pplotcmd);fflush(stdout);
7082: system(pplotcmd);
1.126 brouard 7083: }
7084: else if (z[0] == 'g') system(plotcmd);
7085: else if (z[0] == 'q') exit(0);
7086: }
7087: end:
7088: while (z[0] != 'q') {
7089: printf("\nType q for exiting: ");
7090: scanf("%s",z);
7091: }
7092: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>