Annotation of imach/src/imach.c, revision 1.173
1.173 ! brouard 1: /* $Id: imach.c,v 1.172 2014/12/27 12:07:47 brouard Exp $
1.126 brouard 2: $State: Exp $
1.163 brouard 3: $Log: imach.c,v $
1.173 ! brouard 4: Revision 1.172 2014/12/27 12:07:47 brouard
! 5: Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
! 6:
1.172 brouard 7: Revision 1.171 2014/12/23 13:26:59 brouard
8: Summary: Back from Visual C
9:
10: Still problem with utsname.h on Windows
11:
1.171 brouard 12: Revision 1.170 2014/12/23 11:17:12 brouard
13: Summary: Cleaning some \%% back to %%
14:
15: The escape was mandatory for a specific compiler (which one?), but too many warnings.
16:
1.170 brouard 17: Revision 1.169 2014/12/22 23:08:31 brouard
18: Summary: 0.98p
19:
20: Outputs some informations on compiler used, OS etc. Testing on different platforms.
21:
1.169 brouard 22: Revision 1.168 2014/12/22 15:17:42 brouard
1.170 brouard 23: Summary: update
1.169 brouard 24:
1.168 brouard 25: Revision 1.167 2014/12/22 13:50:56 brouard
26: Summary: Testing uname and compiler version and if compiled 32 or 64
27:
28: Testing on Linux 64
29:
1.167 brouard 30: Revision 1.166 2014/12/22 11:40:47 brouard
31: *** empty log message ***
32:
1.166 brouard 33: Revision 1.165 2014/12/16 11:20:36 brouard
34: Summary: After compiling on Visual C
35:
36: * imach.c (Module): Merging 1.61 to 1.162
37:
1.165 brouard 38: Revision 1.164 2014/12/16 10:52:11 brouard
39: Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
40:
41: * imach.c (Module): Merging 1.61 to 1.162
42:
1.164 brouard 43: Revision 1.163 2014/12/16 10:30:11 brouard
44: * imach.c (Module): Merging 1.61 to 1.162
45:
1.163 brouard 46: Revision 1.162 2014/09/25 11:43:39 brouard
47: Summary: temporary backup 0.99!
48:
1.162 brouard 49: Revision 1.1 2014/09/16 11:06:58 brouard
50: Summary: With some code (wrong) for nlopt
51:
52: Author:
53:
54: Revision 1.161 2014/09/15 20:41:41 brouard
55: Summary: Problem with macro SQR on Intel compiler
56:
1.161 brouard 57: Revision 1.160 2014/09/02 09:24:05 brouard
58: *** empty log message ***
59:
1.160 brouard 60: Revision 1.159 2014/09/01 10:34:10 brouard
61: Summary: WIN32
62: Author: Brouard
63:
1.159 brouard 64: Revision 1.158 2014/08/27 17:11:51 brouard
65: *** empty log message ***
66:
1.158 brouard 67: Revision 1.157 2014/08/27 16:26:55 brouard
68: Summary: Preparing windows Visual studio version
69: Author: Brouard
70:
71: In order to compile on Visual studio, time.h is now correct and time_t
72: and tm struct should be used. difftime should be used but sometimes I
73: just make the differences in raw time format (time(&now).
74: Trying to suppress #ifdef LINUX
75: Add xdg-open for __linux in order to open default browser.
76:
1.157 brouard 77: Revision 1.156 2014/08/25 20:10:10 brouard
78: *** empty log message ***
79:
1.156 brouard 80: Revision 1.155 2014/08/25 18:32:34 brouard
81: Summary: New compile, minor changes
82: Author: Brouard
83:
1.155 brouard 84: Revision 1.154 2014/06/20 17:32:08 brouard
85: Summary: Outputs now all graphs of convergence to period prevalence
86:
1.154 brouard 87: Revision 1.153 2014/06/20 16:45:46 brouard
88: Summary: If 3 live state, convergence to period prevalence on same graph
89: Author: Brouard
90:
1.153 brouard 91: Revision 1.152 2014/06/18 17:54:09 brouard
92: Summary: open browser, use gnuplot on same dir than imach if not found in the path
93:
1.152 brouard 94: Revision 1.151 2014/06/18 16:43:30 brouard
95: *** empty log message ***
96:
1.151 brouard 97: Revision 1.150 2014/06/18 16:42:35 brouard
98: Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
99: Author: brouard
100:
1.150 brouard 101: Revision 1.149 2014/06/18 15:51:14 brouard
102: Summary: Some fixes in parameter files errors
103: Author: Nicolas Brouard
104:
1.149 brouard 105: Revision 1.148 2014/06/17 17:38:48 brouard
106: Summary: Nothing new
107: Author: Brouard
108:
109: Just a new packaging for OS/X version 0.98nS
110:
1.148 brouard 111: Revision 1.147 2014/06/16 10:33:11 brouard
112: *** empty log message ***
113:
1.147 brouard 114: Revision 1.146 2014/06/16 10:20:28 brouard
115: Summary: Merge
116: Author: Brouard
117:
118: Merge, before building revised version.
119:
1.146 brouard 120: Revision 1.145 2014/06/10 21:23:15 brouard
121: Summary: Debugging with valgrind
122: Author: Nicolas Brouard
123:
124: Lot of changes in order to output the results with some covariates
125: After the Edimburgh REVES conference 2014, it seems mandatory to
126: improve the code.
127: No more memory valgrind error but a lot has to be done in order to
128: continue the work of splitting the code into subroutines.
129: Also, decodemodel has been improved. Tricode is still not
130: optimal. nbcode should be improved. Documentation has been added in
131: the source code.
132:
1.144 brouard 133: Revision 1.143 2014/01/26 09:45:38 brouard
134: Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
135:
136: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
137: (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
138:
1.143 brouard 139: Revision 1.142 2014/01/26 03:57:36 brouard
140: Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
141:
142: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
143:
1.142 brouard 144: Revision 1.141 2014/01/26 02:42:01 brouard
145: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
146:
1.141 brouard 147: Revision 1.140 2011/09/02 10:37:54 brouard
148: Summary: times.h is ok with mingw32 now.
149:
1.140 brouard 150: Revision 1.139 2010/06/14 07:50:17 brouard
151: After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
152: I remember having already fixed agemin agemax which are pointers now but not cvs saved.
153:
1.139 brouard 154: Revision 1.138 2010/04/30 18:19:40 brouard
155: *** empty log message ***
156:
1.138 brouard 157: Revision 1.137 2010/04/29 18:11:38 brouard
158: (Module): Checking covariates for more complex models
159: than V1+V2. A lot of change to be done. Unstable.
160:
1.137 brouard 161: Revision 1.136 2010/04/26 20:30:53 brouard
162: (Module): merging some libgsl code. Fixing computation
163: of likelione (using inter/intrapolation if mle = 0) in order to
164: get same likelihood as if mle=1.
165: Some cleaning of code and comments added.
166:
1.136 brouard 167: Revision 1.135 2009/10/29 15:33:14 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.135 brouard 170: Revision 1.134 2009/10/29 13:18:53 brouard
171: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
172:
1.134 brouard 173: Revision 1.133 2009/07/06 10:21:25 brouard
174: just nforces
175:
1.133 brouard 176: Revision 1.132 2009/07/06 08:22:05 brouard
177: Many tings
178:
1.132 brouard 179: Revision 1.131 2009/06/20 16:22:47 brouard
180: Some dimensions resccaled
181:
1.131 brouard 182: Revision 1.130 2009/05/26 06:44:34 brouard
183: (Module): Max Covariate is now set to 20 instead of 8. A
184: lot of cleaning with variables initialized to 0. Trying to make
185: V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
186:
1.130 brouard 187: Revision 1.129 2007/08/31 13:49:27 lievre
188: Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
189:
1.129 lievre 190: Revision 1.128 2006/06/30 13:02:05 brouard
191: (Module): Clarifications on computing e.j
192:
1.128 brouard 193: Revision 1.127 2006/04/28 18:11:50 brouard
194: (Module): Yes the sum of survivors was wrong since
195: imach-114 because nhstepm was no more computed in the age
196: loop. Now we define nhstepma in the age loop.
197: (Module): In order to speed up (in case of numerous covariates) we
198: compute health expectancies (without variances) in a first step
199: and then all the health expectancies with variances or standard
200: deviation (needs data from the Hessian matrices) which slows the
201: computation.
202: In the future we should be able to stop the program is only health
203: expectancies and graph are needed without standard deviations.
204:
1.127 brouard 205: Revision 1.126 2006/04/28 17:23:28 brouard
206: (Module): Yes the sum of survivors was wrong since
207: imach-114 because nhstepm was no more computed in the age
208: loop. Now we define nhstepma in the age loop.
209: Version 0.98h
210:
1.126 brouard 211: Revision 1.125 2006/04/04 15:20:31 lievre
212: Errors in calculation of health expectancies. Age was not initialized.
213: Forecasting file added.
214:
215: Revision 1.124 2006/03/22 17:13:53 lievre
216: Parameters are printed with %lf instead of %f (more numbers after the comma).
217: The log-likelihood is printed in the log file
218:
219: Revision 1.123 2006/03/20 10:52:43 brouard
220: * imach.c (Module): <title> changed, corresponds to .htm file
221: name. <head> headers where missing.
222:
223: * imach.c (Module): Weights can have a decimal point as for
224: English (a comma might work with a correct LC_NUMERIC environment,
225: otherwise the weight is truncated).
226: Modification of warning when the covariates values are not 0 or
227: 1.
228: Version 0.98g
229:
230: Revision 1.122 2006/03/20 09:45:41 brouard
231: (Module): Weights can have a decimal point as for
232: English (a comma might work with a correct LC_NUMERIC environment,
233: otherwise the weight is truncated).
234: Modification of warning when the covariates values are not 0 or
235: 1.
236: Version 0.98g
237:
238: Revision 1.121 2006/03/16 17:45:01 lievre
239: * imach.c (Module): Comments concerning covariates added
240:
241: * imach.c (Module): refinements in the computation of lli if
242: status=-2 in order to have more reliable computation if stepm is
243: not 1 month. Version 0.98f
244:
245: Revision 1.120 2006/03/16 15:10:38 lievre
246: (Module): refinements in the computation of lli if
247: status=-2 in order to have more reliable computation if stepm is
248: not 1 month. Version 0.98f
249:
250: Revision 1.119 2006/03/15 17:42:26 brouard
251: (Module): Bug if status = -2, the loglikelihood was
252: computed as likelihood omitting the logarithm. Version O.98e
253:
254: Revision 1.118 2006/03/14 18:20:07 brouard
255: (Module): varevsij Comments added explaining the second
256: table of variances if popbased=1 .
257: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
258: (Module): Function pstamp added
259: (Module): Version 0.98d
260:
261: Revision 1.117 2006/03/14 17:16:22 brouard
262: (Module): varevsij Comments added explaining the second
263: table of variances if popbased=1 .
264: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
265: (Module): Function pstamp added
266: (Module): Version 0.98d
267:
268: Revision 1.116 2006/03/06 10:29:27 brouard
269: (Module): Variance-covariance wrong links and
270: varian-covariance of ej. is needed (Saito).
271:
272: Revision 1.115 2006/02/27 12:17:45 brouard
273: (Module): One freematrix added in mlikeli! 0.98c
274:
275: Revision 1.114 2006/02/26 12:57:58 brouard
276: (Module): Some improvements in processing parameter
277: filename with strsep.
278:
279: Revision 1.113 2006/02/24 14:20:24 brouard
280: (Module): Memory leaks checks with valgrind and:
281: datafile was not closed, some imatrix were not freed and on matrix
282: allocation too.
283:
284: Revision 1.112 2006/01/30 09:55:26 brouard
285: (Module): Back to gnuplot.exe instead of wgnuplot.exe
286:
287: Revision 1.111 2006/01/25 20:38:18 brouard
288: (Module): Lots of cleaning and bugs added (Gompertz)
289: (Module): Comments can be added in data file. Missing date values
290: can be a simple dot '.'.
291:
292: Revision 1.110 2006/01/25 00:51:50 brouard
293: (Module): Lots of cleaning and bugs added (Gompertz)
294:
295: Revision 1.109 2006/01/24 19:37:15 brouard
296: (Module): Comments (lines starting with a #) are allowed in data.
297:
298: Revision 1.108 2006/01/19 18:05:42 lievre
299: Gnuplot problem appeared...
300: To be fixed
301:
302: Revision 1.107 2006/01/19 16:20:37 brouard
303: Test existence of gnuplot in imach path
304:
305: Revision 1.106 2006/01/19 13:24:36 brouard
306: Some cleaning and links added in html output
307:
308: Revision 1.105 2006/01/05 20:23:19 lievre
309: *** empty log message ***
310:
311: Revision 1.104 2005/09/30 16:11:43 lievre
312: (Module): sump fixed, loop imx fixed, and simplifications.
313: (Module): If the status is missing at the last wave but we know
314: that the person is alive, then we can code his/her status as -2
315: (instead of missing=-1 in earlier versions) and his/her
316: contributions to the likelihood is 1 - Prob of dying from last
317: health status (= 1-p13= p11+p12 in the easiest case of somebody in
318: the healthy state at last known wave). Version is 0.98
319:
320: Revision 1.103 2005/09/30 15:54:49 lievre
321: (Module): sump fixed, loop imx fixed, and simplifications.
322:
323: Revision 1.102 2004/09/15 17:31:30 brouard
324: Add the possibility to read data file including tab characters.
325:
326: Revision 1.101 2004/09/15 10:38:38 brouard
327: Fix on curr_time
328:
329: Revision 1.100 2004/07/12 18:29:06 brouard
330: Add version for Mac OS X. Just define UNIX in Makefile
331:
332: Revision 1.99 2004/06/05 08:57:40 brouard
333: *** empty log message ***
334:
335: Revision 1.98 2004/05/16 15:05:56 brouard
336: New version 0.97 . First attempt to estimate force of mortality
337: directly from the data i.e. without the need of knowing the health
338: state at each age, but using a Gompertz model: log u =a + b*age .
339: This is the basic analysis of mortality and should be done before any
340: other analysis, in order to test if the mortality estimated from the
341: cross-longitudinal survey is different from the mortality estimated
342: from other sources like vital statistic data.
343:
344: The same imach parameter file can be used but the option for mle should be -3.
345:
1.133 brouard 346: Agnès, who wrote this part of the code, tried to keep most of the
1.126 brouard 347: former routines in order to include the new code within the former code.
348:
349: The output is very simple: only an estimate of the intercept and of
350: the slope with 95% confident intervals.
351:
352: Current limitations:
353: A) Even if you enter covariates, i.e. with the
354: model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
355: B) There is no computation of Life Expectancy nor Life Table.
356:
357: Revision 1.97 2004/02/20 13:25:42 lievre
358: Version 0.96d. Population forecasting command line is (temporarily)
359: suppressed.
360:
361: Revision 1.96 2003/07/15 15:38:55 brouard
362: * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
363: rewritten within the same printf. Workaround: many printfs.
364:
365: Revision 1.95 2003/07/08 07:54:34 brouard
366: * imach.c (Repository):
367: (Repository): Using imachwizard code to output a more meaningful covariance
368: matrix (cov(a12,c31) instead of numbers.
369:
370: Revision 1.94 2003/06/27 13:00:02 brouard
371: Just cleaning
372:
373: Revision 1.93 2003/06/25 16:33:55 brouard
374: (Module): On windows (cygwin) function asctime_r doesn't
375: exist so I changed back to asctime which exists.
376: (Module): Version 0.96b
377:
378: Revision 1.92 2003/06/25 16:30:45 brouard
379: (Module): On windows (cygwin) function asctime_r doesn't
380: exist so I changed back to asctime which exists.
381:
382: Revision 1.91 2003/06/25 15:30:29 brouard
383: * imach.c (Repository): Duplicated warning errors corrected.
384: (Repository): Elapsed time after each iteration is now output. It
385: helps to forecast when convergence will be reached. Elapsed time
386: is stamped in powell. We created a new html file for the graphs
387: concerning matrix of covariance. It has extension -cov.htm.
388:
389: Revision 1.90 2003/06/24 12:34:15 brouard
390: (Module): Some bugs corrected for windows. Also, when
391: mle=-1 a template is output in file "or"mypar.txt with the design
392: of the covariance matrix to be input.
393:
394: Revision 1.89 2003/06/24 12:30:52 brouard
395: (Module): Some bugs corrected for windows. Also, when
396: mle=-1 a template is output in file "or"mypar.txt with the design
397: of the covariance matrix to be input.
398:
399: Revision 1.88 2003/06/23 17:54:56 brouard
400: * 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.
401:
402: Revision 1.87 2003/06/18 12:26:01 brouard
403: Version 0.96
404:
405: Revision 1.86 2003/06/17 20:04:08 brouard
406: (Module): Change position of html and gnuplot routines and added
407: routine fileappend.
408:
409: Revision 1.85 2003/06/17 13:12:43 brouard
410: * imach.c (Repository): Check when date of death was earlier that
411: current date of interview. It may happen when the death was just
412: prior to the death. In this case, dh was negative and likelihood
413: was wrong (infinity). We still send an "Error" but patch by
414: assuming that the date of death was just one stepm after the
415: interview.
416: (Repository): Because some people have very long ID (first column)
417: we changed int to long in num[] and we added a new lvector for
418: memory allocation. But we also truncated to 8 characters (left
419: truncation)
420: (Repository): No more line truncation errors.
421:
422: Revision 1.84 2003/06/13 21:44:43 brouard
423: * imach.c (Repository): Replace "freqsummary" at a correct
424: place. It differs from routine "prevalence" which may be called
425: many times. Probs is memory consuming and must be used with
426: parcimony.
427: Version 0.95a3 (should output exactly the same maximization than 0.8a2)
428:
429: Revision 1.83 2003/06/10 13:39:11 lievre
430: *** empty log message ***
431:
432: Revision 1.82 2003/06/05 15:57:20 brouard
433: Add log in imach.c and fullversion number is now printed.
434:
435: */
436: /*
437: Interpolated Markov Chain
438:
439: Short summary of the programme:
440:
441: This program computes Healthy Life Expectancies from
442: cross-longitudinal data. Cross-longitudinal data consist in: -1- a
443: first survey ("cross") where individuals from different ages are
444: interviewed on their health status or degree of disability (in the
445: case of a health survey which is our main interest) -2- at least a
446: second wave of interviews ("longitudinal") which measure each change
447: (if any) in individual health status. Health expectancies are
448: computed from the time spent in each health state according to a
449: model. More health states you consider, more time is necessary to reach the
450: Maximum Likelihood of the parameters involved in the model. The
451: simplest model is the multinomial logistic model where pij is the
452: probability to be observed in state j at the second wave
453: conditional to be observed in state i at the first wave. Therefore
454: the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
455: 'age' is age and 'sex' is a covariate. If you want to have a more
456: complex model than "constant and age", you should modify the program
457: where the markup *Covariates have to be included here again* invites
458: you to do it. More covariates you add, slower the
459: convergence.
460:
461: The advantage of this computer programme, compared to a simple
462: multinomial logistic model, is clear when the delay between waves is not
463: identical for each individual. Also, if a individual missed an
464: intermediate interview, the information is lost, but taken into
465: account using an interpolation or extrapolation.
466:
467: hPijx is the probability to be observed in state i at age x+h
468: conditional to the observed state i at age x. The delay 'h' can be
469: split into an exact number (nh*stepm) of unobserved intermediate
470: states. This elementary transition (by month, quarter,
471: semester or year) is modelled as a multinomial logistic. The hPx
472: matrix is simply the matrix product of nh*stepm elementary matrices
473: and the contribution of each individual to the likelihood is simply
474: hPijx.
475:
476: Also this programme outputs the covariance matrix of the parameters but also
477: of the life expectancies. It also computes the period (stable) prevalence.
478:
1.133 brouard 479: Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
480: Institut national d'études démographiques, Paris.
1.126 brouard 481: This software have been partly granted by Euro-REVES, a concerted action
482: from the European Union.
483: It is copyrighted identically to a GNU software product, ie programme and
484: software can be distributed freely for non commercial use. Latest version
485: can be accessed at http://euroreves.ined.fr/imach .
486:
487: Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
488: or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
489:
490: **********************************************************************/
491: /*
492: main
493: read parameterfile
494: read datafile
495: concatwav
496: freqsummary
497: if (mle >= 1)
498: mlikeli
499: print results files
500: if mle==1
501: computes hessian
502: read end of parameter file: agemin, agemax, bage, fage, estepm
503: begin-prev-date,...
504: open gnuplot file
505: open html file
1.145 brouard 506: period (stable) prevalence | pl_nom 1-1 2-2 etc by covariate
507: for age prevalim() | #****** V1=0 V2=1 V3=1 V4=0 ******
508: | 65 1 0 2 1 3 1 4 0 0.96326 0.03674
509: freexexit2 possible for memory heap.
510:
511: h Pij x | pij_nom ficrestpij
512: # Cov Agex agex+h hpijx with i,j= 1-1 1-2 1-3 2-1 2-2 2-3
513: 1 85 85 1.00000 0.00000 0.00000 0.00000 1.00000 0.00000
514: 1 85 86 0.68299 0.22291 0.09410 0.71093 0.00000 0.28907
515:
516: 1 65 99 0.00364 0.00322 0.99314 0.00350 0.00310 0.99340
517: 1 65 100 0.00214 0.00204 0.99581 0.00206 0.00196 0.99597
518: variance of p one-step probabilities varprob | prob_nom ficresprob #One-step probabilities and stand. devi in ()
519: Standard deviation of one-step probabilities | probcor_nom ficresprobcor #One-step probabilities and correlation matrix
520: Matrix of variance covariance of one-step probabilities | probcov_nom ficresprobcov #One-step probabilities and covariance matrix
521:
1.126 brouard 522: forecasting if prevfcast==1 prevforecast call prevalence()
523: health expectancies
524: Variance-covariance of DFLE
525: prevalence()
526: movingaverage()
527: varevsij()
528: if popbased==1 varevsij(,popbased)
529: total life expectancies
530: Variance of period (stable) prevalence
531: end
532: */
533:
1.165 brouard 534: #define POWELL /* Instead of NLOPT */
1.126 brouard 535:
536: #include <math.h>
537: #include <stdio.h>
538: #include <stdlib.h>
539: #include <string.h>
1.159 brouard 540:
541: #ifdef _WIN32
542: #include <io.h>
1.172 brouard 543: #include <windows.h>
544: #include <tchar.h>
1.159 brouard 545: #else
1.126 brouard 546: #include <unistd.h>
1.159 brouard 547: #endif
1.126 brouard 548:
549: #include <limits.h>
550: #include <sys/types.h>
1.171 brouard 551:
552: #if defined(__GNUC__)
553: #include <sys/utsname.h> /* Doesn't work on Windows */
554: #endif
555:
1.126 brouard 556: #include <sys/stat.h>
557: #include <errno.h>
1.159 brouard 558: /* extern int errno; */
1.126 brouard 559:
1.157 brouard 560: /* #ifdef LINUX */
561: /* #include <time.h> */
562: /* #include "timeval.h" */
563: /* #else */
564: /* #include <sys/time.h> */
565: /* #endif */
566:
1.126 brouard 567: #include <time.h>
568:
1.136 brouard 569: #ifdef GSL
570: #include <gsl/gsl_errno.h>
571: #include <gsl/gsl_multimin.h>
572: #endif
573:
1.167 brouard 574:
1.162 brouard 575: #ifdef NLOPT
576: #include <nlopt.h>
577: typedef struct {
578: double (* function)(double [] );
579: } myfunc_data ;
580: #endif
581:
1.126 brouard 582: /* #include <libintl.h> */
583: /* #define _(String) gettext (String) */
584:
1.141 brouard 585: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126 brouard 586:
587: #define GNUPLOTPROGRAM "gnuplot"
588: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
589: #define FILENAMELENGTH 132
590:
591: #define GLOCK_ERROR_NOPATH -1 /* empty path */
592: #define GLOCK_ERROR_GETCWD -2 /* cannot get cwd */
593:
1.144 brouard 594: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
595: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126 brouard 596:
597: #define NINTERVMAX 8
1.144 brouard 598: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
599: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
600: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.145 brouard 601: #define codtabm(h,k) 1 & (h-1) >> (k-1) ;
1.126 brouard 602: #define MAXN 20000
1.144 brouard 603: #define YEARM 12. /**< Number of months per year */
1.126 brouard 604: #define AGESUP 130
605: #define AGEBASE 40
1.164 brouard 606: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157 brouard 607: #ifdef _WIN32
608: #define DIRSEPARATOR '\\'
609: #define CHARSEPARATOR "\\"
610: #define ODIRSEPARATOR '/'
611: #else
1.126 brouard 612: #define DIRSEPARATOR '/'
613: #define CHARSEPARATOR "/"
614: #define ODIRSEPARATOR '\\'
615: #endif
616:
1.173 ! brouard 617: /* $Id: imach.c,v 1.172 2014/12/27 12:07:47 brouard Exp $ */
1.126 brouard 618: /* $State: Exp $ */
619:
1.169 brouard 620: 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.173 ! brouard 621: char fullversion[]="$Revision: 1.172 $ $Date: 2014/12/27 12:07:47 $";
1.126 brouard 622: char strstart[80];
623: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130 brouard 624: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings */
1.133 brouard 625: int nvar=0, nforce=0; /* Number of variables, number of forces */
1.145 brouard 626: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
627: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
628: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
629: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
630: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
631: int cptcovprodnoage=0; /**< Number of covariate products without age */
632: int cptcoveff=0; /* Total number of covariates to vary for printing results */
633: int cptcov=0; /* Working variable */
1.126 brouard 634: int npar=NPARMAX;
635: int nlstate=2; /* Number of live states */
636: int ndeath=1; /* Number of dead states */
1.130 brouard 637: int ncovmodel=0, ncovcol=0; /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126 brouard 638: int popbased=0;
639:
640: int *wav; /* Number of waves for this individuual 0 is possible */
1.130 brouard 641: int maxwav=0; /* Maxim number of waves */
642: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
643: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */
644: int gipmx=0, gsw=0; /* Global variables on the number of contributions
1.126 brouard 645: to the likelihood and the sum of weights (done by funcone)*/
1.130 brouard 646: int mle=1, weightopt=0;
1.126 brouard 647: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
648: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
649: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
650: * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162 brouard 651: int countcallfunc=0; /* Count the number of calls to func */
1.130 brouard 652: double jmean=1; /* Mean space between 2 waves */
1.145 brouard 653: double **matprod2(); /* test */
1.126 brouard 654: double **oldm, **newm, **savm; /* Working pointers to matrices */
655: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136 brouard 656: /*FILE *fic ; */ /* Used in readdata only */
657: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126 brouard 658: FILE *ficlog, *ficrespow;
1.130 brouard 659: int globpr=0; /* Global variable for printing or not */
1.126 brouard 660: double fretone; /* Only one call to likelihood */
1.130 brouard 661: long ipmx=0; /* Number of contributions */
1.126 brouard 662: double sw; /* Sum of weights */
663: char filerespow[FILENAMELENGTH];
664: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
665: FILE *ficresilk;
666: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
667: FILE *ficresprobmorprev;
668: FILE *fichtm, *fichtmcov; /* Html File */
669: FILE *ficreseij;
670: char filerese[FILENAMELENGTH];
671: FILE *ficresstdeij;
672: char fileresstde[FILENAMELENGTH];
673: FILE *ficrescveij;
674: char filerescve[FILENAMELENGTH];
675: FILE *ficresvij;
676: char fileresv[FILENAMELENGTH];
677: FILE *ficresvpl;
678: char fileresvpl[FILENAMELENGTH];
679: char title[MAXLINE];
680: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH], filerespl[FILENAMELENGTH];
681: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
682: char tmpout[FILENAMELENGTH], tmpout2[FILENAMELENGTH];
683: char command[FILENAMELENGTH];
684: int outcmd=0;
685:
686: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
687:
688: char filelog[FILENAMELENGTH]; /* Log file */
689: char filerest[FILENAMELENGTH];
690: char fileregp[FILENAMELENGTH];
691: char popfile[FILENAMELENGTH];
692:
693: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
694:
1.157 brouard 695: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
696: /* struct timezone tzp; */
697: /* extern int gettimeofday(); */
698: struct tm tml, *gmtime(), *localtime();
699:
700: extern time_t time();
701:
702: struct tm start_time, end_time, curr_time, last_time, forecast_time;
703: time_t rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
704: struct tm tm;
705:
1.126 brouard 706: char strcurr[80], strfor[80];
707:
708: char *endptr;
709: long lval;
710: double dval;
711:
712: #define NR_END 1
713: #define FREE_ARG char*
714: #define FTOL 1.0e-10
715:
716: #define NRANSI
717: #define ITMAX 200
718:
719: #define TOL 2.0e-4
720:
721: #define CGOLD 0.3819660
722: #define ZEPS 1.0e-10
723: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
724:
725: #define GOLD 1.618034
726: #define GLIMIT 100.0
727: #define TINY 1.0e-20
728:
729: static double maxarg1,maxarg2;
730: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
731: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
732:
733: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
734: #define rint(a) floor(a+0.5)
1.166 brouard 735: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
736: /* #define mytinydouble 1.0e-16 */
737: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
738: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
739: /* static double dsqrarg; */
740: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126 brouard 741: static double sqrarg;
742: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
743: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
744: int agegomp= AGEGOMP;
745:
746: int imx;
747: int stepm=1;
748: /* Stepm, step in month: minimum step interpolation*/
749:
750: int estepm;
751: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
752:
753: int m,nb;
754: long *num;
755: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
756: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
757: double **pmmij, ***probs;
758: double *ageexmed,*agecens;
759: double dateintmean=0;
760:
761: double *weight;
762: int **s; /* Status */
1.141 brouard 763: double *agedc;
1.145 brouard 764: double **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141 brouard 765: * covar=matrix(0,NCOVMAX,1,n);
766: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; */
767: double idx;
768: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.145 brouard 769: int *Ndum; /** Freq of modality (tricode */
1.141 brouard 770: int **codtab; /**< codtab=imatrix(1,100,1,10); */
771: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126 brouard 772: double *lsurv, *lpop, *tpop;
773:
1.143 brouard 774: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
775: double ftolhess; /**< Tolerance for computing hessian */
1.126 brouard 776:
777: /**************** split *************************/
778: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
779: {
780: /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
781: the name of the file (name), its extension only (ext) and its first part of the name (finame)
782: */
783: char *ss; /* pointer */
784: int l1, l2; /* length counters */
785:
786: l1 = strlen(path ); /* length of path */
787: if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
788: ss= strrchr( path, DIRSEPARATOR ); /* find last / */
789: if ( ss == NULL ) { /* no directory, so determine current directory */
790: strcpy( name, path ); /* we got the fullname name because no directory */
791: /*if(strrchr(path, ODIRSEPARATOR )==NULL)
792: printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
793: /* get current working directory */
794: /* extern char* getcwd ( char *buf , int len);*/
795: if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
796: return( GLOCK_ERROR_GETCWD );
797: }
798: /* got dirc from getcwd*/
799: printf(" DIRC = %s \n",dirc);
800: } else { /* strip direcotry from path */
801: ss++; /* after this, the filename */
802: l2 = strlen( ss ); /* length of filename */
803: if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
804: strcpy( name, ss ); /* save file name */
805: strncpy( dirc, path, l1 - l2 ); /* now the directory */
806: dirc[l1-l2] = 0; /* add zero */
807: printf(" DIRC2 = %s \n",dirc);
808: }
809: /* We add a separator at the end of dirc if not exists */
810: l1 = strlen( dirc ); /* length of directory */
811: if( dirc[l1-1] != DIRSEPARATOR ){
812: dirc[l1] = DIRSEPARATOR;
813: dirc[l1+1] = 0;
814: printf(" DIRC3 = %s \n",dirc);
815: }
816: ss = strrchr( name, '.' ); /* find last / */
817: if (ss >0){
818: ss++;
819: strcpy(ext,ss); /* save extension */
820: l1= strlen( name);
821: l2= strlen(ss)+1;
822: strncpy( finame, name, l1-l2);
823: finame[l1-l2]= 0;
824: }
825:
826: return( 0 ); /* we're done */
827: }
828:
829:
830: /******************************************/
831:
832: void replace_back_to_slash(char *s, char*t)
833: {
834: int i;
835: int lg=0;
836: i=0;
837: lg=strlen(t);
838: for(i=0; i<= lg; i++) {
839: (s[i] = t[i]);
840: if (t[i]== '\\') s[i]='/';
841: }
842: }
843:
1.132 brouard 844: char *trimbb(char *out, char *in)
1.137 brouard 845: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132 brouard 846: char *s;
847: s=out;
848: while (*in != '\0'){
1.137 brouard 849: while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132 brouard 850: in++;
851: }
852: *out++ = *in++;
853: }
854: *out='\0';
855: return s;
856: }
857:
1.145 brouard 858: char *cutl(char *blocc, char *alocc, char *in, char occ)
859: {
860: /* cuts string in into blocc and alocc where blocc ends before first occurence of char 'occ'
861: and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
862: gives blocc="abcdef2ghi" and alocc="j".
863: If occ is not found blocc is null and alocc is equal to in. Returns blocc
864: */
1.160 brouard 865: char *s, *t;
1.145 brouard 866: t=in;s=in;
867: while ((*in != occ) && (*in != '\0')){
868: *alocc++ = *in++;
869: }
870: if( *in == occ){
871: *(alocc)='\0';
872: s=++in;
873: }
874:
875: if (s == t) {/* occ not found */
876: *(alocc-(in-s))='\0';
877: in=s;
878: }
879: while ( *in != '\0'){
880: *blocc++ = *in++;
881: }
882:
883: *blocc='\0';
884: return t;
885: }
1.137 brouard 886: char *cutv(char *blocc, char *alocc, char *in, char occ)
887: {
888: /* cuts string in into blocc and alocc where blocc ends before last occurence of char 'occ'
889: and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
890: gives blocc="abcdef2ghi" and alocc="j".
891: If occ is not found blocc is null and alocc is equal to in. Returns alocc
892: */
893: char *s, *t;
894: t=in;s=in;
895: while (*in != '\0'){
896: while( *in == occ){
897: *blocc++ = *in++;
898: s=in;
899: }
900: *blocc++ = *in++;
901: }
902: if (s == t) /* occ not found */
903: *(blocc-(in-s))='\0';
904: else
905: *(blocc-(in-s)-1)='\0';
906: in=s;
907: while ( *in != '\0'){
908: *alocc++ = *in++;
909: }
910:
911: *alocc='\0';
912: return s;
913: }
914:
1.126 brouard 915: int nbocc(char *s, char occ)
916: {
917: int i,j=0;
918: int lg=20;
919: i=0;
920: lg=strlen(s);
921: for(i=0; i<= lg; i++) {
922: if (s[i] == occ ) j++;
923: }
924: return j;
925: }
926:
1.137 brouard 927: /* void cutv(char *u,char *v, char*t, char occ) */
928: /* { */
929: /* /\* cuts string t into u and v where u ends before last occurence of char 'occ' */
930: /* and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
931: /* gives u="abcdef2ghi" and v="j" *\/ */
932: /* int i,lg,j,p=0; */
933: /* i=0; */
934: /* lg=strlen(t); */
935: /* for(j=0; j<=lg-1; j++) { */
936: /* if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
937: /* } */
1.126 brouard 938:
1.137 brouard 939: /* for(j=0; j<p; j++) { */
940: /* (u[j] = t[j]); */
941: /* } */
942: /* u[p]='\0'; */
1.126 brouard 943:
1.137 brouard 944: /* for(j=0; j<= lg; j++) { */
945: /* if (j>=(p+1))(v[j-p-1] = t[j]); */
946: /* } */
947: /* } */
1.126 brouard 948:
1.160 brouard 949: #ifdef _WIN32
950: char * strsep(char **pp, const char *delim)
951: {
952: char *p, *q;
953:
954: if ((p = *pp) == NULL)
955: return 0;
956: if ((q = strpbrk (p, delim)) != NULL)
957: {
958: *pp = q + 1;
959: *q = '\0';
960: }
961: else
962: *pp = 0;
963: return p;
964: }
965: #endif
966:
1.126 brouard 967: /********************** nrerror ********************/
968:
969: void nrerror(char error_text[])
970: {
971: fprintf(stderr,"ERREUR ...\n");
972: fprintf(stderr,"%s\n",error_text);
973: exit(EXIT_FAILURE);
974: }
975: /*********************** vector *******************/
976: double *vector(int nl, int nh)
977: {
978: double *v;
979: v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
980: if (!v) nrerror("allocation failure in vector");
981: return v-nl+NR_END;
982: }
983:
984: /************************ free vector ******************/
985: void free_vector(double*v, int nl, int nh)
986: {
987: free((FREE_ARG)(v+nl-NR_END));
988: }
989:
990: /************************ivector *******************************/
991: int *ivector(long nl,long nh)
992: {
993: int *v;
994: v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
995: if (!v) nrerror("allocation failure in ivector");
996: return v-nl+NR_END;
997: }
998:
999: /******************free ivector **************************/
1000: void free_ivector(int *v, long nl, long nh)
1001: {
1002: free((FREE_ARG)(v+nl-NR_END));
1003: }
1004:
1005: /************************lvector *******************************/
1006: long *lvector(long nl,long nh)
1007: {
1008: long *v;
1009: v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
1010: if (!v) nrerror("allocation failure in ivector");
1011: return v-nl+NR_END;
1012: }
1013:
1014: /******************free lvector **************************/
1015: void free_lvector(long *v, long nl, long nh)
1016: {
1017: free((FREE_ARG)(v+nl-NR_END));
1018: }
1019:
1020: /******************* imatrix *******************************/
1021: int **imatrix(long nrl, long nrh, long ncl, long nch)
1022: /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
1023: {
1024: long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
1025: int **m;
1026:
1027: /* allocate pointers to rows */
1028: m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
1029: if (!m) nrerror("allocation failure 1 in matrix()");
1030: m += NR_END;
1031: m -= nrl;
1032:
1033:
1034: /* allocate rows and set pointers to them */
1035: m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
1036: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1037: m[nrl] += NR_END;
1038: m[nrl] -= ncl;
1039:
1040: for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
1041:
1042: /* return pointer to array of pointers to rows */
1043: return m;
1044: }
1045:
1046: /****************** free_imatrix *************************/
1047: void free_imatrix(m,nrl,nrh,ncl,nch)
1048: int **m;
1049: long nch,ncl,nrh,nrl;
1050: /* free an int matrix allocated by imatrix() */
1051: {
1052: free((FREE_ARG) (m[nrl]+ncl-NR_END));
1053: free((FREE_ARG) (m+nrl-NR_END));
1054: }
1055:
1056: /******************* matrix *******************************/
1057: double **matrix(long nrl, long nrh, long ncl, long nch)
1058: {
1059: long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
1060: double **m;
1061:
1062: m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1063: if (!m) nrerror("allocation failure 1 in matrix()");
1064: m += NR_END;
1065: m -= nrl;
1066:
1067: m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1068: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1069: m[nrl] += NR_END;
1070: m[nrl] -= ncl;
1071:
1072: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1073: return m;
1.145 brouard 1074: /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
1075: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
1076: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126 brouard 1077: */
1078: }
1079:
1080: /*************************free matrix ************************/
1081: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
1082: {
1083: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1084: free((FREE_ARG)(m+nrl-NR_END));
1085: }
1086:
1087: /******************* ma3x *******************************/
1088: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
1089: {
1090: long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
1091: double ***m;
1092:
1093: m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1094: if (!m) nrerror("allocation failure 1 in matrix()");
1095: m += NR_END;
1096: m -= nrl;
1097:
1098: m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1099: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1100: m[nrl] += NR_END;
1101: m[nrl] -= ncl;
1102:
1103: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1104:
1105: m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
1106: if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
1107: m[nrl][ncl] += NR_END;
1108: m[nrl][ncl] -= nll;
1109: for (j=ncl+1; j<=nch; j++)
1110: m[nrl][j]=m[nrl][j-1]+nlay;
1111:
1112: for (i=nrl+1; i<=nrh; i++) {
1113: m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
1114: for (j=ncl+1; j<=nch; j++)
1115: m[i][j]=m[i][j-1]+nlay;
1116: }
1117: return m;
1118: /* gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
1119: &(m[i][j][k]) <=> *((*(m+i) + j)+k)
1120: */
1121: }
1122:
1123: /*************************free ma3x ************************/
1124: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
1125: {
1126: free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
1127: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1128: free((FREE_ARG)(m+nrl-NR_END));
1129: }
1130:
1131: /*************** function subdirf ***********/
1132: char *subdirf(char fileres[])
1133: {
1134: /* Caution optionfilefiname is hidden */
1135: strcpy(tmpout,optionfilefiname);
1136: strcat(tmpout,"/"); /* Add to the right */
1137: strcat(tmpout,fileres);
1138: return tmpout;
1139: }
1140:
1141: /*************** function subdirf2 ***********/
1142: char *subdirf2(char fileres[], char *preop)
1143: {
1144:
1145: /* Caution optionfilefiname is hidden */
1146: strcpy(tmpout,optionfilefiname);
1147: strcat(tmpout,"/");
1148: strcat(tmpout,preop);
1149: strcat(tmpout,fileres);
1150: return tmpout;
1151: }
1152:
1153: /*************** function subdirf3 ***********/
1154: char *subdirf3(char fileres[], char *preop, char *preop2)
1155: {
1156:
1157: /* Caution optionfilefiname is hidden */
1158: strcpy(tmpout,optionfilefiname);
1159: strcat(tmpout,"/");
1160: strcat(tmpout,preop);
1161: strcat(tmpout,preop2);
1162: strcat(tmpout,fileres);
1163: return tmpout;
1164: }
1165:
1.162 brouard 1166: char *asc_diff_time(long time_sec, char ascdiff[])
1167: {
1168: long sec_left, days, hours, minutes;
1169: days = (time_sec) / (60*60*24);
1170: sec_left = (time_sec) % (60*60*24);
1171: hours = (sec_left) / (60*60) ;
1172: sec_left = (sec_left) %(60*60);
1173: minutes = (sec_left) /60;
1174: sec_left = (sec_left) % (60);
1175: sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);
1176: return ascdiff;
1177: }
1178:
1.126 brouard 1179: /***************** f1dim *************************/
1180: extern int ncom;
1181: extern double *pcom,*xicom;
1182: extern double (*nrfunc)(double []);
1183:
1184: double f1dim(double x)
1185: {
1186: int j;
1187: double f;
1188: double *xt;
1189:
1190: xt=vector(1,ncom);
1191: for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
1192: f=(*nrfunc)(xt);
1193: free_vector(xt,1,ncom);
1194: return f;
1195: }
1196:
1197: /*****************brent *************************/
1198: double brent(double ax, double bx, double cx, double (*f)(double), double tol, double *xmin)
1199: {
1200: int iter;
1201: double a,b,d,etemp;
1.159 brouard 1202: double fu=0,fv,fw,fx;
1.164 brouard 1203: double ftemp=0.;
1.126 brouard 1204: double p,q,r,tol1,tol2,u,v,w,x,xm;
1205: double e=0.0;
1206:
1207: a=(ax < cx ? ax : cx);
1208: b=(ax > cx ? ax : cx);
1209: x=w=v=bx;
1210: fw=fv=fx=(*f)(x);
1211: for (iter=1;iter<=ITMAX;iter++) {
1212: xm=0.5*(a+b);
1213: tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
1214: /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
1215: printf(".");fflush(stdout);
1216: fprintf(ficlog,".");fflush(ficlog);
1.162 brouard 1217: #ifdef DEBUGBRENT
1.126 brouard 1218: 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);
1219: 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);
1220: /* if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
1221: #endif
1222: if (fabs(x-xm) <= (tol2-0.5*(b-a))){
1223: *xmin=x;
1224: return fx;
1225: }
1226: ftemp=fu;
1227: if (fabs(e) > tol1) {
1228: r=(x-w)*(fx-fv);
1229: q=(x-v)*(fx-fw);
1230: p=(x-v)*q-(x-w)*r;
1231: q=2.0*(q-r);
1232: if (q > 0.0) p = -p;
1233: q=fabs(q);
1234: etemp=e;
1235: e=d;
1236: if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
1237: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1238: else {
1239: d=p/q;
1240: u=x+d;
1241: if (u-a < tol2 || b-u < tol2)
1242: d=SIGN(tol1,xm-x);
1243: }
1244: } else {
1245: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1246: }
1247: u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
1248: fu=(*f)(u);
1249: if (fu <= fx) {
1250: if (u >= x) a=x; else b=x;
1251: SHFT(v,w,x,u)
1252: SHFT(fv,fw,fx,fu)
1253: } else {
1254: if (u < x) a=u; else b=u;
1255: if (fu <= fw || w == x) {
1256: v=w;
1257: w=u;
1258: fv=fw;
1259: fw=fu;
1260: } else if (fu <= fv || v == x || v == w) {
1261: v=u;
1262: fv=fu;
1263: }
1264: }
1265: }
1266: nrerror("Too many iterations in brent");
1267: *xmin=x;
1268: return fx;
1269: }
1270:
1271: /****************** mnbrak ***********************/
1272:
1273: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
1274: double (*func)(double))
1275: {
1276: double ulim,u,r,q, dum;
1277: double fu;
1278:
1279: *fa=(*func)(*ax);
1280: *fb=(*func)(*bx);
1281: if (*fb > *fa) {
1282: SHFT(dum,*ax,*bx,dum)
1283: SHFT(dum,*fb,*fa,dum)
1284: }
1285: *cx=(*bx)+GOLD*(*bx-*ax);
1286: *fc=(*func)(*cx);
1.162 brouard 1287: while (*fb > *fc) { /* Declining fa, fb, fc */
1.126 brouard 1288: r=(*bx-*ax)*(*fb-*fc);
1289: q=(*bx-*cx)*(*fb-*fa);
1290: u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
1.162 brouard 1291: (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscisse of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
1292: ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscisse where function can be evaluated */
1293: if ((*bx-u)*(u-*cx) > 0.0) { /* if u between b and c */
1.126 brouard 1294: fu=(*func)(u);
1.163 brouard 1295: #ifdef DEBUG
1296: /* f(x)=A(x-u)**2+f(u) */
1297: double A, fparabu;
1298: A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
1299: fparabu= *fa - A*(*ax-u)*(*ax-u);
1300: 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);
1301: 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);
1302: #endif
1.162 brouard 1303: } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.126 brouard 1304: fu=(*func)(u);
1305: if (fu < *fc) {
1306: SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
1307: SHFT(*fb,*fc,fu,(*func)(u))
1308: }
1.162 brouard 1309: } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.126 brouard 1310: u=ulim;
1311: fu=(*func)(u);
1312: } else {
1313: u=(*cx)+GOLD*(*cx-*bx);
1314: fu=(*func)(u);
1315: }
1316: SHFT(*ax,*bx,*cx,u)
1317: SHFT(*fa,*fb,*fc,fu)
1318: }
1319: }
1320:
1321: /*************** linmin ************************/
1.162 brouard 1322: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
1323: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
1324: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
1325: the value of func at the returned location p . This is actually all accomplished by calling the
1326: routines mnbrak and brent .*/
1.126 brouard 1327: int ncom;
1328: double *pcom,*xicom;
1329: double (*nrfunc)(double []);
1330:
1331: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
1332: {
1333: double brent(double ax, double bx, double cx,
1334: double (*f)(double), double tol, double *xmin);
1335: double f1dim(double x);
1336: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
1337: double *fc, double (*func)(double));
1338: int j;
1339: double xx,xmin,bx,ax;
1340: double fx,fb,fa;
1341:
1342: ncom=n;
1343: pcom=vector(1,n);
1344: xicom=vector(1,n);
1345: nrfunc=func;
1346: for (j=1;j<=n;j++) {
1347: pcom[j]=p[j];
1348: xicom[j]=xi[j];
1349: }
1350: ax=0.0;
1351: xx=1.0;
1.162 brouard 1352: mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Find a bracket a,x,b in direction n=xi ie xicom */
1353: *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 1354: #ifdef DEBUG
1355: printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1356: fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1357: #endif
1358: for (j=1;j<=n;j++) {
1359: xi[j] *= xmin;
1360: p[j] += xi[j];
1361: }
1362: free_vector(xicom,1,n);
1363: free_vector(pcom,1,n);
1364: }
1365:
1366:
1367: /*************** powell ************************/
1.162 brouard 1368: /*
1369: Minimization of a function func of n variables. Input consists of an initial starting point
1370: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
1371: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
1372: such that failure to decrease by more than this amount on one iteration signals doneness. On
1373: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
1374: function value at p , and iter is the number of iterations taken. The routine linmin is used.
1375: */
1.126 brouard 1376: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
1377: double (*func)(double []))
1378: {
1379: void linmin(double p[], double xi[], int n, double *fret,
1380: double (*func)(double []));
1381: int i,ibig,j;
1382: double del,t,*pt,*ptt,*xit;
1383: double fp,fptt;
1384: double *xits;
1385: int niterf, itmp;
1386:
1387: pt=vector(1,n);
1388: ptt=vector(1,n);
1389: xit=vector(1,n);
1390: xits=vector(1,n);
1391: *fret=(*func)(p);
1392: for (j=1;j<=n;j++) pt[j]=p[j];
1.157 brouard 1393: rcurr_time = time(NULL);
1.126 brouard 1394: for (*iter=1;;++(*iter)) {
1395: fp=(*fret);
1396: ibig=0;
1397: del=0.0;
1.157 brouard 1398: rlast_time=rcurr_time;
1399: /* (void) gettimeofday(&curr_time,&tzp); */
1400: rcurr_time = time(NULL);
1401: curr_time = *localtime(&rcurr_time);
1402: printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
1403: fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1404: /* fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.126 brouard 1405: for (i=1;i<=n;i++) {
1406: printf(" %d %.12f",i, p[i]);
1407: fprintf(ficlog," %d %.12lf",i, p[i]);
1408: fprintf(ficrespow," %.12lf", p[i]);
1409: }
1410: printf("\n");
1411: fprintf(ficlog,"\n");
1412: fprintf(ficrespow,"\n");fflush(ficrespow);
1413: if(*iter <=3){
1.157 brouard 1414: tml = *localtime(&rcurr_time);
1415: strcpy(strcurr,asctime(&tml));
1416: rforecast_time=rcurr_time;
1.126 brouard 1417: itmp = strlen(strcurr);
1418: if(strcurr[itmp-1]=='\n') /* Windows outputs with a new line */
1419: strcurr[itmp-1]='\0';
1.162 brouard 1420: printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157 brouard 1421: fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126 brouard 1422: for(niterf=10;niterf<=30;niterf+=10){
1.157 brouard 1423: rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
1424: forecast_time = *localtime(&rforecast_time);
1425: strcpy(strfor,asctime(&forecast_time));
1.126 brouard 1426: itmp = strlen(strfor);
1427: if(strfor[itmp-1]=='\n')
1428: strfor[itmp-1]='\0';
1.157 brouard 1429: 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);
1430: 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 1431: }
1432: }
1433: for (i=1;i<=n;i++) {
1434: for (j=1;j<=n;j++) xit[j]=xi[j][i];
1435: fptt=(*fret);
1436: #ifdef DEBUG
1.164 brouard 1437: printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1438: fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126 brouard 1439: #endif
1440: printf("%d",i);fflush(stdout);
1441: fprintf(ficlog,"%d",i);fflush(ficlog);
1442: linmin(p,xit,n,fret,func);
1443: if (fabs(fptt-(*fret)) > del) {
1444: del=fabs(fptt-(*fret));
1445: ibig=i;
1446: }
1447: #ifdef DEBUG
1448: printf("%d %.12e",i,(*fret));
1449: fprintf(ficlog,"%d %.12e",i,(*fret));
1450: for (j=1;j<=n;j++) {
1451: xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
1452: printf(" x(%d)=%.12e",j,xit[j]);
1453: fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1454: }
1455: for(j=1;j<=n;j++) {
1.162 brouard 1456: printf(" p(%d)=%.12e",j,p[j]);
1457: fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126 brouard 1458: }
1459: printf("\n");
1460: fprintf(ficlog,"\n");
1461: #endif
1.162 brouard 1462: } /* end i */
1.126 brouard 1463: if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
1464: #ifdef DEBUG
1465: int k[2],l;
1466: k[0]=1;
1467: k[1]=-1;
1468: printf("Max: %.12e",(*func)(p));
1469: fprintf(ficlog,"Max: %.12e",(*func)(p));
1470: for (j=1;j<=n;j++) {
1471: printf(" %.12e",p[j]);
1472: fprintf(ficlog," %.12e",p[j]);
1473: }
1474: printf("\n");
1475: fprintf(ficlog,"\n");
1476: for(l=0;l<=1;l++) {
1477: for (j=1;j<=n;j++) {
1478: ptt[j]=p[j]+(p[j]-pt[j])*k[l];
1479: printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1480: fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1481: }
1482: printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1483: fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1484: }
1485: #endif
1486:
1487:
1488: free_vector(xit,1,n);
1489: free_vector(xits,1,n);
1490: free_vector(ptt,1,n);
1491: free_vector(pt,1,n);
1492: return;
1493: }
1494: if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
1.161 brouard 1495: for (j=1;j<=n;j++) { /* Computes an extrapolated point */
1.126 brouard 1496: ptt[j]=2.0*p[j]-pt[j];
1497: xit[j]=p[j]-pt[j];
1498: pt[j]=p[j];
1499: }
1500: fptt=(*func)(ptt);
1.161 brouard 1501: if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.162 brouard 1502: /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161 brouard 1503: /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162 brouard 1504: /* Let f"(x2) be the 2nd derivative equal everywhere. */
1505: /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
1506: /* will reach at f3 = fm + h^2/2 f"m ; f" = (f1 -2f2 +f3 ) / h**2 */
1.161 brouard 1507: /* f1-f3 = delta(2h) = 2 h**2 f'' = 2(f1- 2f2 +f3) */
1508: /* Thus we compare delta(2h) with observed f1-f3 */
1.162 brouard 1509: /* or best gain on one ancient line 'del' with total */
1510: /* gain f1-f2 = f1 - f2 - 'del' with del */
1.161 brouard 1511: /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.162 brouard 1512:
1.161 brouard 1513: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del);
1514: t= t- del*SQR(fp-fptt);
1515: printf("t1= %.12lf, t2= %.12lf, t=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t);
1516: 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);
1517: #ifdef DEBUG
1518: printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1519: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1520: fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1521: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1522: 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);
1523: 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);
1524: #endif
1525: if (t < 0.0) { /* Then we use it for last direction */
1526: linmin(p,xit,n,fret,func); /* computes mean on the extrapolated direction.*/
1.126 brouard 1527: for (j=1;j<=n;j++) {
1.161 brouard 1528: xi[j][ibig]=xi[j][n]; /* Replace the direction with biggest decrease by n */
1529: xi[j][n]=xit[j]; /* and nth direction by the extrapolated */
1.126 brouard 1530: }
1.161 brouard 1531: printf("Gaining to use average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.169 brouard 1532: fprintf(ficlog,"Gaining to use average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161 brouard 1533:
1.126 brouard 1534: #ifdef DEBUG
1.164 brouard 1535: printf("Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1536: fprintf(ficlog,"Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126 brouard 1537: for(j=1;j<=n;j++){
1538: printf(" %.12e",xit[j]);
1539: fprintf(ficlog," %.12e",xit[j]);
1540: }
1541: printf("\n");
1542: fprintf(ficlog,"\n");
1543: #endif
1.162 brouard 1544: } /* end of t negative */
1545: } /* end if (fptt < fp) */
1.126 brouard 1546: }
1547: }
1548:
1549: /**** Prevalence limit (stable or period prevalence) ****************/
1550:
1551: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
1552: {
1553: /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1554: matrix by transitions matrix until convergence is reached */
1.169 brouard 1555:
1.126 brouard 1556: int i, ii,j,k;
1557: double min, max, maxmin, maxmax,sumnew=0.;
1.145 brouard 1558: /* double **matprod2(); */ /* test */
1.131 brouard 1559: double **out, cov[NCOVMAX+1], **pmij();
1.126 brouard 1560: double **newm;
1561: double agefin, delaymax=50 ; /* Max number of years to converge */
1.169 brouard 1562:
1.126 brouard 1563: for (ii=1;ii<=nlstate+ndeath;ii++)
1564: for (j=1;j<=nlstate+ndeath;j++){
1565: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1566: }
1.169 brouard 1567:
1568: cov[1]=1.;
1569:
1570: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.126 brouard 1571: for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1572: newm=savm;
1573: /* Covariates have to be included here again */
1.138 brouard 1574: cov[2]=agefin;
1575:
1576: for (k=1; k<=cptcovn;k++) {
1577: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.145 brouard 1578: /*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 1579: }
1.145 brouard 1580: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1581: /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
1582: /* 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 1583:
1584: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
1585: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
1586: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145 brouard 1587: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1588: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142 brouard 1589: out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138 brouard 1590:
1.126 brouard 1591: savm=oldm;
1592: oldm=newm;
1593: maxmax=0.;
1594: for(j=1;j<=nlstate;j++){
1595: min=1.;
1596: max=0.;
1597: for(i=1; i<=nlstate; i++) {
1598: sumnew=0;
1599: for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
1600: prlim[i][j]= newm[i][j]/(1-sumnew);
1.145 brouard 1601: /*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 1602: max=FMAX(max,prlim[i][j]);
1603: min=FMIN(min,prlim[i][j]);
1604: }
1605: maxmin=max-min;
1606: maxmax=FMAX(maxmax,maxmin);
1.169 brouard 1607: } /* j loop */
1.126 brouard 1608: if(maxmax < ftolpl){
1609: return prlim;
1610: }
1.169 brouard 1611: } /* age loop */
1612: return prlim; /* should not reach here */
1.126 brouard 1613: }
1614:
1615: /*************** transition probabilities ***************/
1616:
1617: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1618: {
1.138 brouard 1619: /* According to parameters values stored in x and the covariate's values stored in cov,
1620: computes the probability to be observed in state j being in state i by appying the
1621: model to the ncovmodel covariates (including constant and age).
1622: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
1623: and, according on how parameters are entered, the position of the coefficient xij(nc) of the
1624: ncth covariate in the global vector x is given by the formula:
1625: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
1626: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
1627: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
1628: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1629: Outputs ps[i][j] the probability to be observed in j being in j according to
1630: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1631: */
1632: double s1, lnpijopii;
1.126 brouard 1633: /*double t34;*/
1.164 brouard 1634: int i,j, nc, ii, jj;
1.126 brouard 1635:
1636: for(i=1; i<= nlstate; i++){
1637: for(j=1; j<i;j++){
1.138 brouard 1638: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1639: /*lnpijopii += param[i][j][nc]*cov[nc];*/
1640: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
1641: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 1642: }
1.138 brouard 1643: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1644: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 1645: }
1646: for(j=i+1; j<=nlstate+ndeath;j++){
1.138 brouard 1647: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1648: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
1649: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
1650: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126 brouard 1651: }
1.138 brouard 1652: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126 brouard 1653: }
1654: }
1655:
1656: for(i=1; i<= nlstate; i++){
1657: s1=0;
1.131 brouard 1658: for(j=1; j<i; j++){
1.138 brouard 1659: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 1660: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1661: }
1662: for(j=i+1; j<=nlstate+ndeath; j++){
1.138 brouard 1663: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 1664: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1665: }
1.138 brouard 1666: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126 brouard 1667: ps[i][i]=1./(s1+1.);
1.138 brouard 1668: /* Computing other pijs */
1.126 brouard 1669: for(j=1; j<i; j++)
1670: ps[i][j]= exp(ps[i][j])*ps[i][i];
1671: for(j=i+1; j<=nlstate+ndeath; j++)
1672: ps[i][j]= exp(ps[i][j])*ps[i][i];
1673: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
1674: } /* end i */
1675:
1676: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
1677: for(jj=1; jj<= nlstate+ndeath; jj++){
1678: ps[ii][jj]=0;
1679: ps[ii][ii]=1;
1680: }
1681: }
1682:
1.145 brouard 1683:
1684: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
1685: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */
1686: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
1687: /* } */
1688: /* printf("\n "); */
1689: /* } */
1690: /* printf("\n ");printf("%lf ",cov[2]);*/
1691: /*
1.126 brouard 1692: for(i=1; i<= npar; i++) printf("%f ",x[i]);
1693: goto end;*/
1694: return ps;
1695: }
1696:
1697: /**************** Product of 2 matrices ******************/
1698:
1.145 brouard 1699: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126 brouard 1700: {
1701: /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
1702: b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
1703: /* in, b, out are matrice of pointers which should have been initialized
1704: before: only the contents of out is modified. The function returns
1705: a pointer to pointers identical to out */
1.145 brouard 1706: int i, j, k;
1.126 brouard 1707: for(i=nrl; i<= nrh; i++)
1.145 brouard 1708: for(k=ncolol; k<=ncoloh; k++){
1709: out[i][k]=0.;
1710: for(j=ncl; j<=nch; j++)
1711: out[i][k] +=in[i][j]*b[j][k];
1712: }
1.126 brouard 1713: return out;
1714: }
1715:
1716:
1717: /************* Higher Matrix Product ***************/
1718:
1719: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
1720: {
1721: /* Computes the transition matrix starting at age 'age' over
1722: 'nhstepm*hstepm*stepm' months (i.e. until
1723: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
1724: nhstepm*hstepm matrices.
1725: Output is stored in matrix po[i][j][h] for h every 'hstepm' step
1726: (typically every 2 years instead of every month which is too big
1727: for the memory).
1728: Model is determined by parameters x and covariates have to be
1729: included manually here.
1730:
1731: */
1732:
1733: int i, j, d, h, k;
1.131 brouard 1734: double **out, cov[NCOVMAX+1];
1.126 brouard 1735: double **newm;
1736:
1737: /* Hstepm could be zero and should return the unit matrix */
1738: for (i=1;i<=nlstate+ndeath;i++)
1739: for (j=1;j<=nlstate+ndeath;j++){
1740: oldm[i][j]=(i==j ? 1.0 : 0.0);
1741: po[i][j][0]=(i==j ? 1.0 : 0.0);
1742: }
1743: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1744: for(h=1; h <=nhstepm; h++){
1745: for(d=1; d <=hstepm; d++){
1746: newm=savm;
1747: /* Covariates have to be included here again */
1748: cov[1]=1.;
1749: cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
1.131 brouard 1750: for (k=1; k<=cptcovn;k++)
1751: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.126 brouard 1752: for (k=1; k<=cptcovage;k++)
1753: cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
1.145 brouard 1754: for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.126 brouard 1755: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
1756:
1757:
1758: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
1759: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1760: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
1761: pmij(pmmij,cov,ncovmodel,x,nlstate));
1762: savm=oldm;
1763: oldm=newm;
1764: }
1765: for(i=1; i<=nlstate+ndeath; i++)
1766: for(j=1;j<=nlstate+ndeath;j++) {
1767: po[i][j][h]=newm[i][j];
1.128 brouard 1768: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126 brouard 1769: }
1.128 brouard 1770: /*printf("h=%d ",h);*/
1.126 brouard 1771: } /* end h */
1.128 brouard 1772: /* printf("\n H=%d \n",h); */
1.126 brouard 1773: return po;
1774: }
1775:
1.162 brouard 1776: #ifdef NLOPT
1777: double myfunc(unsigned n, const double *p1, double *grad, void *pd){
1778: double fret;
1779: double *xt;
1780: int j;
1781: myfunc_data *d2 = (myfunc_data *) pd;
1782: /* xt = (p1-1); */
1783: xt=vector(1,n);
1784: for (j=1;j<=n;j++) xt[j]=p1[j-1]; /* xt[1]=p1[0] */
1785:
1786: fret=(d2->function)(xt); /* p xt[1]@8 is fine */
1787: /* fret=(*func)(xt); /\* p xt[1]@8 is fine *\/ */
1788: printf("Function = %.12lf ",fret);
1789: for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]);
1790: printf("\n");
1791: free_vector(xt,1,n);
1792: return fret;
1793: }
1794: #endif
1.126 brouard 1795:
1796: /*************** log-likelihood *************/
1797: double func( double *x)
1798: {
1799: int i, ii, j, k, mi, d, kk;
1.131 brouard 1800: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 1801: double **out;
1802: double sw; /* Sum of weights */
1803: double lli; /* Individual log likelihood */
1804: int s1, s2;
1805: double bbh, survp;
1806: long ipmx;
1807: /*extern weight */
1808: /* We are differentiating ll according to initial status */
1809: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
1810: /*for(i=1;i<imx;i++)
1811: printf(" %d\n",s[4][i]);
1812: */
1.162 brouard 1813:
1814: ++countcallfunc;
1815:
1.126 brouard 1816: cov[1]=1.;
1817:
1818: for(k=1; k<=nlstate; k++) ll[k]=0.;
1819:
1820: if(mle==1){
1821: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138 brouard 1822: /* Computes the values of the ncovmodel covariates of the model
1823: depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
1824: Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
1825: to be observed in j being in i according to the model.
1826: */
1.145 brouard 1827: for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1828: cov[2+k]=covar[Tvar[k]][i];
1829: }
1.137 brouard 1830: /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4]
1.138 brouard 1831: is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]
1.137 brouard 1832: has been calculated etc */
1.126 brouard 1833: for(mi=1; mi<= wav[i]-1; mi++){
1834: for (ii=1;ii<=nlstate+ndeath;ii++)
1835: for (j=1;j<=nlstate+ndeath;j++){
1836: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1837: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1838: }
1839: for(d=0; d<dh[mi][i]; d++){
1840: newm=savm;
1841: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1842: for (kk=1; kk<=cptcovage;kk++) {
1.137 brouard 1843: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; /* Tage[kk] gives the data-covariate associated with age */
1.126 brouard 1844: }
1845: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1846: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1847: savm=oldm;
1848: oldm=newm;
1849: } /* end mult */
1850:
1851: /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
1852: /* But now since version 0.9 we anticipate for bias at large stepm.
1853: * If stepm is larger than one month (smallest stepm) and if the exact delay
1854: * (in months) between two waves is not a multiple of stepm, we rounded to
1855: * the nearest (and in case of equal distance, to the lowest) interval but now
1856: * we keep into memory the bias bh[mi][i] and also the previous matrix product
1857: * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
1858: * probability in order to take into account the bias as a fraction of the way
1859: * from savm to out if bh is negative or even beyond if bh is positive. bh varies
1860: * -stepm/2 to stepm/2 .
1861: * For stepm=1 the results are the same as for previous versions of Imach.
1862: * For stepm > 1 the results are less biased than in previous versions.
1863: */
1864: s1=s[mw[mi][i]][i];
1865: s2=s[mw[mi+1][i]][i];
1866: bbh=(double)bh[mi][i]/(double)stepm;
1867: /* bias bh is positive if real duration
1868: * is higher than the multiple of stepm and negative otherwise.
1869: */
1870: /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
1871: if( s2 > nlstate){
1872: /* i.e. if s2 is a death state and if the date of death is known
1873: then the contribution to the likelihood is the probability to
1874: die between last step unit time and current step unit time,
1875: which is also equal to probability to die before dh
1876: minus probability to die before dh-stepm .
1877: In version up to 0.92 likelihood was computed
1878: as if date of death was unknown. Death was treated as any other
1879: health state: the date of the interview describes the actual state
1880: and not the date of a change in health state. The former idea was
1881: to consider that at each interview the state was recorded
1882: (healthy, disable or death) and IMaCh was corrected; but when we
1883: introduced the exact date of death then we should have modified
1884: the contribution of an exact death to the likelihood. This new
1885: contribution is smaller and very dependent of the step unit
1886: stepm. It is no more the probability to die between last interview
1887: and month of death but the probability to survive from last
1888: interview up to one month before death multiplied by the
1889: probability to die within a month. Thanks to Chris
1890: Jackson for correcting this bug. Former versions increased
1891: mortality artificially. The bad side is that we add another loop
1892: which slows down the processing. The difference can be up to 10%
1893: lower mortality.
1894: */
1895: lli=log(out[s1][s2] - savm[s1][s2]);
1896:
1897:
1898: } else if (s2==-2) {
1899: for (j=1,survp=0. ; j<=nlstate; j++)
1900: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1901: /*survp += out[s1][j]; */
1902: lli= log(survp);
1903: }
1904:
1905: else if (s2==-4) {
1906: for (j=3,survp=0. ; j<=nlstate; j++)
1907: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1908: lli= log(survp);
1909: }
1910:
1911: else if (s2==-5) {
1912: for (j=1,survp=0. ; j<=2; j++)
1913: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1914: lli= log(survp);
1915: }
1916:
1917: else{
1918: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1919: /* 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 */
1920: }
1921: /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
1922: /*if(lli ==000.0)*/
1923: /*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); */
1924: ipmx +=1;
1925: sw += weight[i];
1926: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1927: } /* end of wave */
1928: } /* end of individual */
1929: } else if(mle==2){
1930: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1931: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1932: for(mi=1; mi<= wav[i]-1; mi++){
1933: for (ii=1;ii<=nlstate+ndeath;ii++)
1934: for (j=1;j<=nlstate+ndeath;j++){
1935: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1936: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1937: }
1938: for(d=0; d<=dh[mi][i]; d++){
1939: newm=savm;
1940: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1941: for (kk=1; kk<=cptcovage;kk++) {
1942: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1943: }
1944: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1945: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1946: savm=oldm;
1947: oldm=newm;
1948: } /* end mult */
1949:
1950: s1=s[mw[mi][i]][i];
1951: s2=s[mw[mi+1][i]][i];
1952: bbh=(double)bh[mi][i]/(double)stepm;
1953: 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 */
1954: ipmx +=1;
1955: sw += weight[i];
1956: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1957: } /* end of wave */
1958: } /* end of individual */
1959: } else if(mle==3){ /* exponential inter-extrapolation */
1960: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1961: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1962: for(mi=1; mi<= wav[i]-1; mi++){
1963: for (ii=1;ii<=nlstate+ndeath;ii++)
1964: for (j=1;j<=nlstate+ndeath;j++){
1965: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1966: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1967: }
1968: for(d=0; d<dh[mi][i]; d++){
1969: newm=savm;
1970: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1971: for (kk=1; kk<=cptcovage;kk++) {
1972: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1973: }
1974: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1975: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1976: savm=oldm;
1977: oldm=newm;
1978: } /* end mult */
1979:
1980: s1=s[mw[mi][i]][i];
1981: s2=s[mw[mi+1][i]][i];
1982: bbh=(double)bh[mi][i]/(double)stepm;
1983: 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 */
1984: ipmx +=1;
1985: sw += weight[i];
1986: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1987: } /* end of wave */
1988: } /* end of individual */
1989: }else if (mle==4){ /* ml=4 no inter-extrapolation */
1990: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1991: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1992: for(mi=1; mi<= wav[i]-1; mi++){
1993: for (ii=1;ii<=nlstate+ndeath;ii++)
1994: for (j=1;j<=nlstate+ndeath;j++){
1995: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1996: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1997: }
1998: for(d=0; d<dh[mi][i]; d++){
1999: newm=savm;
2000: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2001: for (kk=1; kk<=cptcovage;kk++) {
2002: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2003: }
2004:
2005: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2006: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2007: savm=oldm;
2008: oldm=newm;
2009: } /* end mult */
2010:
2011: s1=s[mw[mi][i]][i];
2012: s2=s[mw[mi+1][i]][i];
2013: if( s2 > nlstate){
2014: lli=log(out[s1][s2] - savm[s1][s2]);
2015: }else{
2016: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2017: }
2018: ipmx +=1;
2019: sw += weight[i];
2020: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2021: /* 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]); */
2022: } /* end of wave */
2023: } /* end of individual */
2024: }else{ /* ml=5 no inter-extrapolation no jackson =0.8a */
2025: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2026: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2027: for(mi=1; mi<= wav[i]-1; mi++){
2028: for (ii=1;ii<=nlstate+ndeath;ii++)
2029: for (j=1;j<=nlstate+ndeath;j++){
2030: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2031: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2032: }
2033: for(d=0; d<dh[mi][i]; d++){
2034: newm=savm;
2035: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2036: for (kk=1; kk<=cptcovage;kk++) {
2037: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2038: }
2039:
2040: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2041: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2042: savm=oldm;
2043: oldm=newm;
2044: } /* end mult */
2045:
2046: s1=s[mw[mi][i]][i];
2047: s2=s[mw[mi+1][i]][i];
2048: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2049: ipmx +=1;
2050: sw += weight[i];
2051: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2052: /*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]);*/
2053: } /* end of wave */
2054: } /* end of individual */
2055: } /* End of if */
2056: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2057: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2058: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2059: return -l;
2060: }
2061:
2062: /*************** log-likelihood *************/
2063: double funcone( double *x)
2064: {
2065: /* Same as likeli but slower because of a lot of printf and if */
2066: int i, ii, j, k, mi, d, kk;
1.131 brouard 2067: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 2068: double **out;
2069: double lli; /* Individual log likelihood */
2070: double llt;
2071: int s1, s2;
2072: double bbh, survp;
2073: /*extern weight */
2074: /* We are differentiating ll according to initial status */
2075: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2076: /*for(i=1;i<imx;i++)
2077: printf(" %d\n",s[4][i]);
2078: */
2079: cov[1]=1.;
2080:
2081: for(k=1; k<=nlstate; k++) ll[k]=0.;
2082:
2083: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2084: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2085: for(mi=1; mi<= wav[i]-1; mi++){
2086: for (ii=1;ii<=nlstate+ndeath;ii++)
2087: for (j=1;j<=nlstate+ndeath;j++){
2088: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2089: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2090: }
2091: for(d=0; d<dh[mi][i]; d++){
2092: newm=savm;
2093: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2094: for (kk=1; kk<=cptcovage;kk++) {
2095: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2096: }
1.145 brouard 2097: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126 brouard 2098: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2099: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145 brouard 2100: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
2101: /* 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126 brouard 2102: savm=oldm;
2103: oldm=newm;
2104: } /* end mult */
2105:
2106: s1=s[mw[mi][i]][i];
2107: s2=s[mw[mi+1][i]][i];
2108: bbh=(double)bh[mi][i]/(double)stepm;
2109: /* bias is positive if real duration
2110: * is higher than the multiple of stepm and negative otherwise.
2111: */
2112: if( s2 > nlstate && (mle <5) ){ /* Jackson */
2113: lli=log(out[s1][s2] - savm[s1][s2]);
2114: } else if (s2==-2) {
2115: for (j=1,survp=0. ; j<=nlstate; j++)
2116: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2117: lli= log(survp);
2118: }else if (mle==1){
2119: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2120: } else if(mle==2){
2121: 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 */
2122: } else if(mle==3){ /* exponential inter-extrapolation */
2123: 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 */
2124: } else if (mle==4){ /* mle=4 no inter-extrapolation */
2125: lli=log(out[s1][s2]); /* Original formula */
1.136 brouard 2126: } else{ /* mle=0 back to 1 */
2127: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2128: /*lli=log(out[s1][s2]); */ /* Original formula */
1.126 brouard 2129: } /* End of if */
2130: ipmx +=1;
2131: sw += weight[i];
2132: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132 brouard 2133: /*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 2134: if(globpr){
1.141 brouard 2135: fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
1.126 brouard 2136: %11.6f %11.6f %11.6f ", \
2137: num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
2138: 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
2139: for(k=1,llt=0.,l=0.; k<=nlstate; k++){
2140: llt +=ll[k]*gipmx/gsw;
2141: fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
2142: }
2143: fprintf(ficresilk," %10.6f\n", -llt);
2144: }
2145: } /* end of wave */
2146: } /* end of individual */
2147: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2148: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2149: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2150: if(globpr==0){ /* First time we count the contributions and weights */
2151: gipmx=ipmx;
2152: gsw=sw;
2153: }
2154: return -l;
2155: }
2156:
2157:
2158: /*************** function likelione ***********/
2159: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
2160: {
2161: /* This routine should help understanding what is done with
2162: the selection of individuals/waves and
2163: to check the exact contribution to the likelihood.
2164: Plotting could be done.
2165: */
2166: int k;
2167:
2168: if(*globpri !=0){ /* Just counts and sums, no printings */
2169: strcpy(fileresilk,"ilk");
2170: strcat(fileresilk,fileres);
2171: if((ficresilk=fopen(fileresilk,"w"))==NULL) {
2172: printf("Problem with resultfile: %s\n", fileresilk);
2173: fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
2174: }
2175: 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");
2176: fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
2177: /* i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
2178: for(k=1; k<=nlstate; k++)
2179: fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
2180: fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
2181: }
2182:
2183: *fretone=(*funcone)(p);
2184: if(*globpri !=0){
2185: fclose(ficresilk);
2186: fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
2187: fflush(fichtm);
2188: }
2189: return;
2190: }
2191:
2192:
2193: /*********** Maximum Likelihood Estimation ***************/
2194:
2195: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
2196: {
1.165 brouard 2197: int i,j, iter=0;
1.126 brouard 2198: double **xi;
2199: double fret;
2200: double fretone; /* Only one call to likelihood */
2201: /* char filerespow[FILENAMELENGTH];*/
1.162 brouard 2202:
2203: #ifdef NLOPT
2204: int creturn;
2205: nlopt_opt opt;
2206: /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
2207: double *lb;
2208: double minf; /* the minimum objective value, upon return */
2209: double * p1; /* Shifted parameters from 0 instead of 1 */
2210: myfunc_data dinst, *d = &dinst;
2211: #endif
2212:
2213:
1.126 brouard 2214: xi=matrix(1,npar,1,npar);
2215: for (i=1;i<=npar;i++)
2216: for (j=1;j<=npar;j++)
2217: xi[i][j]=(i==j ? 1.0 : 0.0);
2218: printf("Powell\n"); fprintf(ficlog,"Powell\n");
2219: strcpy(filerespow,"pow");
2220: strcat(filerespow,fileres);
2221: if((ficrespow=fopen(filerespow,"w"))==NULL) {
2222: printf("Problem with resultfile: %s\n", filerespow);
2223: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
2224: }
2225: fprintf(ficrespow,"# Powell\n# iter -2*LL");
2226: for (i=1;i<=nlstate;i++)
2227: for(j=1;j<=nlstate+ndeath;j++)
2228: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
2229: fprintf(ficrespow,"\n");
1.162 brouard 2230: #ifdef POWELL
1.126 brouard 2231: powell(p,xi,npar,ftol,&iter,&fret,func);
1.162 brouard 2232: #endif
1.126 brouard 2233:
1.162 brouard 2234: #ifdef NLOPT
2235: #ifdef NEWUOA
2236: opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
2237: #else
2238: opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
2239: #endif
2240: lb=vector(0,npar-1);
2241: for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
2242: nlopt_set_lower_bounds(opt, lb);
2243: nlopt_set_initial_step1(opt, 0.1);
2244:
2245: p1= (p+1); /* p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
2246: d->function = func;
2247: printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
2248: nlopt_set_min_objective(opt, myfunc, d);
2249: nlopt_set_xtol_rel(opt, ftol);
2250: if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
2251: printf("nlopt failed! %d\n",creturn);
2252: }
2253: else {
2254: printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
2255: printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
2256: iter=1; /* not equal */
2257: }
2258: nlopt_destroy(opt);
2259: #endif
1.126 brouard 2260: free_matrix(xi,1,npar,1,npar);
2261: fclose(ficrespow);
1.162 brouard 2262: printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2263: fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2264: fprintf(ficres,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126 brouard 2265:
2266: }
2267:
2268: /**** Computes Hessian and covariance matrix ***/
2269: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
2270: {
2271: double **a,**y,*x,pd;
2272: double **hess;
1.164 brouard 2273: int i, j;
1.126 brouard 2274: int *indx;
2275:
2276: double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
2277: double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
2278: void lubksb(double **a, int npar, int *indx, double b[]) ;
2279: void ludcmp(double **a, int npar, int *indx, double *d) ;
2280: double gompertz(double p[]);
2281: hess=matrix(1,npar,1,npar);
2282:
2283: printf("\nCalculation of the hessian matrix. Wait...\n");
2284: fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
2285: for (i=1;i<=npar;i++){
2286: printf("%d",i);fflush(stdout);
2287: fprintf(ficlog,"%d",i);fflush(ficlog);
2288:
2289: hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
2290:
2291: /* printf(" %f ",p[i]);
2292: printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
2293: }
2294:
2295: for (i=1;i<=npar;i++) {
2296: for (j=1;j<=npar;j++) {
2297: if (j>i) {
2298: printf(".%d%d",i,j);fflush(stdout);
2299: fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
2300: hess[i][j]=hessij(p,delti,i,j,func,npar);
2301:
2302: hess[j][i]=hess[i][j];
2303: /*printf(" %lf ",hess[i][j]);*/
2304: }
2305: }
2306: }
2307: printf("\n");
2308: fprintf(ficlog,"\n");
2309:
2310: printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
2311: fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
2312:
2313: a=matrix(1,npar,1,npar);
2314: y=matrix(1,npar,1,npar);
2315: x=vector(1,npar);
2316: indx=ivector(1,npar);
2317: for (i=1;i<=npar;i++)
2318: for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
2319: ludcmp(a,npar,indx,&pd);
2320:
2321: for (j=1;j<=npar;j++) {
2322: for (i=1;i<=npar;i++) x[i]=0;
2323: x[j]=1;
2324: lubksb(a,npar,indx,x);
2325: for (i=1;i<=npar;i++){
2326: matcov[i][j]=x[i];
2327: }
2328: }
2329:
2330: printf("\n#Hessian matrix#\n");
2331: fprintf(ficlog,"\n#Hessian matrix#\n");
2332: for (i=1;i<=npar;i++) {
2333: for (j=1;j<=npar;j++) {
2334: printf("%.3e ",hess[i][j]);
2335: fprintf(ficlog,"%.3e ",hess[i][j]);
2336: }
2337: printf("\n");
2338: fprintf(ficlog,"\n");
2339: }
2340:
2341: /* Recompute Inverse */
2342: for (i=1;i<=npar;i++)
2343: for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
2344: ludcmp(a,npar,indx,&pd);
2345:
2346: /* printf("\n#Hessian matrix recomputed#\n");
2347:
2348: for (j=1;j<=npar;j++) {
2349: for (i=1;i<=npar;i++) x[i]=0;
2350: x[j]=1;
2351: lubksb(a,npar,indx,x);
2352: for (i=1;i<=npar;i++){
2353: y[i][j]=x[i];
2354: printf("%.3e ",y[i][j]);
2355: fprintf(ficlog,"%.3e ",y[i][j]);
2356: }
2357: printf("\n");
2358: fprintf(ficlog,"\n");
2359: }
2360: */
2361:
2362: free_matrix(a,1,npar,1,npar);
2363: free_matrix(y,1,npar,1,npar);
2364: free_vector(x,1,npar);
2365: free_ivector(indx,1,npar);
2366: free_matrix(hess,1,npar,1,npar);
2367:
2368:
2369: }
2370:
2371: /*************** hessian matrix ****************/
2372: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
2373: {
2374: int i;
2375: int l=1, lmax=20;
2376: double k1,k2;
1.132 brouard 2377: double p2[MAXPARM+1]; /* identical to x */
1.126 brouard 2378: double res;
2379: double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
2380: double fx;
2381: int k=0,kmax=10;
2382: double l1;
2383:
2384: fx=func(x);
2385: for (i=1;i<=npar;i++) p2[i]=x[i];
1.145 brouard 2386: for(l=0 ; l <=lmax; l++){ /* Enlarging the zone around the Maximum */
1.126 brouard 2387: l1=pow(10,l);
2388: delts=delt;
2389: for(k=1 ; k <kmax; k=k+1){
2390: delt = delta*(l1*k);
2391: p2[theta]=x[theta] +delt;
1.145 brouard 2392: k1=func(p2)-fx; /* Might be negative if too close to the theoretical maximum */
1.126 brouard 2393: p2[theta]=x[theta]-delt;
2394: k2=func(p2)-fx;
2395: /*res= (k1-2.0*fx+k2)/delt/delt; */
2396: res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
2397:
1.132 brouard 2398: #ifdef DEBUGHESS
1.126 brouard 2399: 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);
2400: 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);
2401: #endif
2402: /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
2403: if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
2404: k=kmax;
2405: }
2406: else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164 brouard 2407: k=kmax; l=lmax*10;
1.126 brouard 2408: }
2409: else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
2410: delts=delt;
2411: }
2412: }
2413: }
2414: delti[theta]=delts;
2415: return res;
2416:
2417: }
2418:
2419: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
2420: {
2421: int i;
1.164 brouard 2422: int l=1, lmax=20;
1.126 brouard 2423: double k1,k2,k3,k4,res,fx;
1.132 brouard 2424: double p2[MAXPARM+1];
1.126 brouard 2425: int k;
2426:
2427: fx=func(x);
2428: for (k=1; k<=2; k++) {
2429: for (i=1;i<=npar;i++) p2[i]=x[i];
2430: p2[thetai]=x[thetai]+delti[thetai]/k;
2431: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2432: k1=func(p2)-fx;
2433:
2434: p2[thetai]=x[thetai]+delti[thetai]/k;
2435: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2436: k2=func(p2)-fx;
2437:
2438: p2[thetai]=x[thetai]-delti[thetai]/k;
2439: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2440: k3=func(p2)-fx;
2441:
2442: p2[thetai]=x[thetai]-delti[thetai]/k;
2443: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2444: k4=func(p2)-fx;
2445: res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
2446: #ifdef DEBUG
2447: 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);
2448: 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);
2449: #endif
2450: }
2451: return res;
2452: }
2453:
2454: /************** Inverse of matrix **************/
2455: void ludcmp(double **a, int n, int *indx, double *d)
2456: {
2457: int i,imax,j,k;
2458: double big,dum,sum,temp;
2459: double *vv;
2460:
2461: vv=vector(1,n);
2462: *d=1.0;
2463: for (i=1;i<=n;i++) {
2464: big=0.0;
2465: for (j=1;j<=n;j++)
2466: if ((temp=fabs(a[i][j])) > big) big=temp;
2467: if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
2468: vv[i]=1.0/big;
2469: }
2470: for (j=1;j<=n;j++) {
2471: for (i=1;i<j;i++) {
2472: sum=a[i][j];
2473: for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
2474: a[i][j]=sum;
2475: }
2476: big=0.0;
2477: for (i=j;i<=n;i++) {
2478: sum=a[i][j];
2479: for (k=1;k<j;k++)
2480: sum -= a[i][k]*a[k][j];
2481: a[i][j]=sum;
2482: if ( (dum=vv[i]*fabs(sum)) >= big) {
2483: big=dum;
2484: imax=i;
2485: }
2486: }
2487: if (j != imax) {
2488: for (k=1;k<=n;k++) {
2489: dum=a[imax][k];
2490: a[imax][k]=a[j][k];
2491: a[j][k]=dum;
2492: }
2493: *d = -(*d);
2494: vv[imax]=vv[j];
2495: }
2496: indx[j]=imax;
2497: if (a[j][j] == 0.0) a[j][j]=TINY;
2498: if (j != n) {
2499: dum=1.0/(a[j][j]);
2500: for (i=j+1;i<=n;i++) a[i][j] *= dum;
2501: }
2502: }
2503: free_vector(vv,1,n); /* Doesn't work */
2504: ;
2505: }
2506:
2507: void lubksb(double **a, int n, int *indx, double b[])
2508: {
2509: int i,ii=0,ip,j;
2510: double sum;
2511:
2512: for (i=1;i<=n;i++) {
2513: ip=indx[i];
2514: sum=b[ip];
2515: b[ip]=b[i];
2516: if (ii)
2517: for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
2518: else if (sum) ii=i;
2519: b[i]=sum;
2520: }
2521: for (i=n;i>=1;i--) {
2522: sum=b[i];
2523: for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
2524: b[i]=sum/a[i][i];
2525: }
2526: }
2527:
2528: void pstamp(FILE *fichier)
2529: {
2530: fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
2531: }
2532:
2533: /************ Frequencies ********************/
2534: 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[])
2535: { /* Some frequencies */
2536:
1.164 brouard 2537: int i, m, jk, j1, bool, z1,j;
1.126 brouard 2538: int first;
2539: double ***freq; /* Frequencies */
2540: double *pp, **prop;
2541: double pos,posprop, k2, dateintsum=0,k2cpt=0;
2542: char fileresp[FILENAMELENGTH];
2543:
2544: pp=vector(1,nlstate);
2545: prop=matrix(1,nlstate,iagemin,iagemax+3);
2546: strcpy(fileresp,"p");
2547: strcat(fileresp,fileres);
2548: if((ficresp=fopen(fileresp,"w"))==NULL) {
2549: printf("Problem with prevalence resultfile: %s\n", fileresp);
2550: fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
2551: exit(0);
2552: }
2553: freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
2554: j1=0;
2555:
2556: j=cptcoveff;
2557: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2558:
2559: first=1;
2560:
1.169 brouard 2561: /* for(k1=1; k1<=j ; k1++){ */ /* Loop on covariates */
2562: /* for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
2563: /* j1++; */
1.145 brouard 2564: for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126 brouard 2565: /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
2566: scanf("%d", i);*/
2567: for (i=-5; i<=nlstate+ndeath; i++)
2568: for (jk=-5; jk<=nlstate+ndeath; jk++)
2569: for(m=iagemin; m <= iagemax+3; m++)
2570: freq[i][jk][m]=0;
1.143 brouard 2571:
2572: for (i=1; i<=nlstate; i++)
2573: for(m=iagemin; m <= iagemax+3; m++)
2574: prop[i][m]=0;
1.126 brouard 2575:
2576: dateintsum=0;
2577: k2cpt=0;
2578: for (i=1; i<=imx; i++) {
2579: bool=1;
1.144 brouard 2580: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
2581: for (z1=1; z1<=cptcoveff; z1++)
2582: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
1.145 brouard 2583: /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144 brouard 2584: bool=0;
1.145 brouard 2585: /* 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",
2586: bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
2587: j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
1.144 brouard 2588: /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
2589: }
1.126 brouard 2590: }
1.144 brouard 2591:
1.126 brouard 2592: if (bool==1){
2593: for(m=firstpass; m<=lastpass; m++){
2594: k2=anint[m][i]+(mint[m][i]/12.);
2595: /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
2596: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2597: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2598: if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
2599: if (m<lastpass) {
2600: freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
2601: freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
2602: }
2603:
2604: if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
2605: dateintsum=dateintsum+k2;
2606: k2cpt++;
2607: }
2608: /*}*/
2609: }
2610: }
1.145 brouard 2611: } /* end i */
1.126 brouard 2612:
2613: /* fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
2614: pstamp(ficresp);
2615: if (cptcovn>0) {
2616: fprintf(ficresp, "\n#********** Variable ");
2617: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2618: fprintf(ficresp, "**********\n#");
1.143 brouard 2619: fprintf(ficlog, "\n#********** Variable ");
2620: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2621: fprintf(ficlog, "**********\n#");
1.126 brouard 2622: }
2623: for(i=1; i<=nlstate;i++)
2624: fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
2625: fprintf(ficresp, "\n");
2626:
2627: for(i=iagemin; i <= iagemax+3; i++){
2628: if(i==iagemax+3){
2629: fprintf(ficlog,"Total");
2630: }else{
2631: if(first==1){
2632: first=0;
2633: printf("See log file for details...\n");
2634: }
2635: fprintf(ficlog,"Age %d", i);
2636: }
2637: for(jk=1; jk <=nlstate ; jk++){
2638: for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
2639: pp[jk] += freq[jk][m][i];
2640: }
2641: for(jk=1; jk <=nlstate ; jk++){
2642: for(m=-1, pos=0; m <=0 ; m++)
2643: pos += freq[jk][m][i];
2644: if(pp[jk]>=1.e-10){
2645: if(first==1){
1.132 brouard 2646: printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126 brouard 2647: }
2648: fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
2649: }else{
2650: if(first==1)
2651: printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2652: fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2653: }
2654: }
2655:
2656: for(jk=1; jk <=nlstate ; jk++){
2657: for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
2658: pp[jk] += freq[jk][m][i];
2659: }
2660: for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
2661: pos += pp[jk];
2662: posprop += prop[jk][i];
2663: }
2664: for(jk=1; jk <=nlstate ; jk++){
2665: if(pos>=1.e-5){
2666: if(first==1)
2667: printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2668: fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2669: }else{
2670: if(first==1)
2671: printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2672: fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2673: }
2674: if( i <= iagemax){
2675: if(pos>=1.e-5){
2676: fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
2677: /*probs[i][jk][j1]= pp[jk]/pos;*/
2678: /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
2679: }
2680: else
2681: fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
2682: }
2683: }
2684:
2685: for(jk=-1; jk <=nlstate+ndeath; jk++)
2686: for(m=-1; m <=nlstate+ndeath; m++)
2687: if(freq[jk][m][i] !=0 ) {
2688: if(first==1)
2689: printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
2690: fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
2691: }
2692: if(i <= iagemax)
2693: fprintf(ficresp,"\n");
2694: if(first==1)
2695: printf("Others in log...\n");
2696: fprintf(ficlog,"\n");
2697: }
1.145 brouard 2698: /*}*/
1.126 brouard 2699: }
2700: dateintmean=dateintsum/k2cpt;
2701:
2702: fclose(ficresp);
2703: free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
2704: free_vector(pp,1,nlstate);
2705: free_matrix(prop,1,nlstate,iagemin, iagemax+3);
2706: /* End of Freq */
2707: }
2708:
2709: /************ Prevalence ********************/
2710: 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)
2711: {
2712: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
2713: in each health status at the date of interview (if between dateprev1 and dateprev2).
2714: We still use firstpass and lastpass as another selection.
2715: */
2716:
1.164 brouard 2717: int i, m, jk, j1, bool, z1,j;
2718:
2719: double **prop;
2720: double posprop;
1.126 brouard 2721: double y2; /* in fractional years */
2722: int iagemin, iagemax;
1.145 brouard 2723: int first; /** to stop verbosity which is redirected to log file */
1.126 brouard 2724:
2725: iagemin= (int) agemin;
2726: iagemax= (int) agemax;
2727: /*pp=vector(1,nlstate);*/
2728: prop=matrix(1,nlstate,iagemin,iagemax+3);
2729: /* freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
2730: j1=0;
2731:
1.145 brouard 2732: /*j=cptcoveff;*/
1.126 brouard 2733: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2734:
1.145 brouard 2735: first=1;
2736: for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
2737: /*for(i1=1; i1<=ncodemax[k1];i1++){
2738: j1++;*/
1.126 brouard 2739:
2740: for (i=1; i<=nlstate; i++)
2741: for(m=iagemin; m <= iagemax+3; m++)
2742: prop[i][m]=0.0;
2743:
2744: for (i=1; i<=imx; i++) { /* Each individual */
2745: bool=1;
2746: if (cptcovn>0) {
2747: for (z1=1; z1<=cptcoveff; z1++)
2748: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
2749: bool=0;
2750: }
2751: if (bool==1) {
2752: for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
2753: y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
2754: if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
2755: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2756: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2757: 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);
2758: if (s[m][i]>0 && s[m][i]<=nlstate) {
2759: /*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]]);*/
2760: prop[s[m][i]][(int)agev[m][i]] += weight[i];
2761: prop[s[m][i]][iagemax+3] += weight[i];
2762: }
2763: }
2764: } /* end selection of waves */
2765: }
2766: }
2767: for(i=iagemin; i <= iagemax+3; i++){
2768: for(jk=1,posprop=0; jk <=nlstate ; jk++) {
2769: posprop += prop[jk][i];
2770: }
1.145 brouard 2771:
1.126 brouard 2772: for(jk=1; jk <=nlstate ; jk++){
2773: if( i <= iagemax){
2774: if(posprop>=1.e-5){
2775: probs[i][jk][j1]= prop[jk][i]/posprop;
1.145 brouard 2776: } else{
2777: if(first==1){
2778: first=0;
2779: 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]);
2780: }
2781: }
1.126 brouard 2782: }
2783: }/* end jk */
2784: }/* end i */
1.145 brouard 2785: /*} *//* end i1 */
2786: } /* end j1 */
1.126 brouard 2787:
2788: /* free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
2789: /*free_vector(pp,1,nlstate);*/
2790: free_matrix(prop,1,nlstate, iagemin,iagemax+3);
2791: } /* End of prevalence */
2792:
2793: /************* Waves Concatenation ***************/
2794:
2795: 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)
2796: {
2797: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
2798: Death is a valid wave (if date is known).
2799: mw[mi][i] is the mi (mi=1 to wav[i]) effective wave of individual i
2800: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
2801: and mw[mi+1][i]. dh depends on stepm.
2802: */
2803:
2804: int i, mi, m;
2805: /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
2806: double sum=0., jmean=0.;*/
2807: int first;
2808: int j, k=0,jk, ju, jl;
2809: double sum=0.;
2810: first=0;
1.164 brouard 2811: jmin=100000;
1.126 brouard 2812: jmax=-1;
2813: jmean=0.;
2814: for(i=1; i<=imx; i++){
2815: mi=0;
2816: m=firstpass;
2817: while(s[m][i] <= nlstate){
2818: if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
2819: mw[++mi][i]=m;
2820: if(m >=lastpass)
2821: break;
2822: else
2823: m++;
2824: }/* end while */
2825: if (s[m][i] > nlstate){
2826: mi++; /* Death is another wave */
2827: /* if(mi==0) never been interviewed correctly before death */
2828: /* Only death is a correct wave */
2829: mw[mi][i]=m;
2830: }
2831:
2832: wav[i]=mi;
2833: if(mi==0){
2834: nbwarn++;
2835: if(first==0){
2836: printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
2837: first=1;
2838: }
2839: if(first==1){
2840: fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
2841: }
2842: } /* end mi==0 */
2843: } /* End individuals */
2844:
2845: for(i=1; i<=imx; i++){
2846: for(mi=1; mi<wav[i];mi++){
2847: if (stepm <=0)
2848: dh[mi][i]=1;
2849: else{
2850: if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
2851: if (agedc[i] < 2*AGESUP) {
2852: j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
2853: if(j==0) j=1; /* Survives at least one month after exam */
2854: else if(j<0){
2855: nberr++;
2856: 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]);
2857: j=1; /* Temporary Dangerous patch */
2858: 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);
2859: 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]);
2860: 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);
2861: }
2862: k=k+1;
2863: if (j >= jmax){
2864: jmax=j;
2865: ijmax=i;
2866: }
2867: if (j <= jmin){
2868: jmin=j;
2869: ijmin=i;
2870: }
2871: sum=sum+j;
2872: /*if (j<0) printf("j=%d num=%d \n",j,i);*/
2873: /* printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
2874: }
2875: }
2876: else{
2877: j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
2878: /* 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]); */
2879:
2880: k=k+1;
2881: if (j >= jmax) {
2882: jmax=j;
2883: ijmax=i;
2884: }
2885: else if (j <= jmin){
2886: jmin=j;
2887: ijmin=i;
2888: }
2889: /* if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
2890: /*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]);*/
2891: if(j<0){
2892: nberr++;
2893: 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]);
2894: 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]);
2895: }
2896: sum=sum+j;
2897: }
2898: jk= j/stepm;
2899: jl= j -jk*stepm;
2900: ju= j -(jk+1)*stepm;
2901: if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
2902: if(jl==0){
2903: dh[mi][i]=jk;
2904: bh[mi][i]=0;
2905: }else{ /* We want a negative bias in order to only have interpolation ie
1.136 brouard 2906: * to avoid the price of an extra matrix product in likelihood */
1.126 brouard 2907: dh[mi][i]=jk+1;
2908: bh[mi][i]=ju;
2909: }
2910: }else{
2911: if(jl <= -ju){
2912: dh[mi][i]=jk;
2913: bh[mi][i]=jl; /* bias is positive if real duration
2914: * is higher than the multiple of stepm and negative otherwise.
2915: */
2916: }
2917: else{
2918: dh[mi][i]=jk+1;
2919: bh[mi][i]=ju;
2920: }
2921: if(dh[mi][i]==0){
2922: dh[mi][i]=1; /* At least one step */
2923: bh[mi][i]=ju; /* At least one step */
2924: /* 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);*/
2925: }
2926: } /* end if mle */
2927: }
2928: } /* end wave */
2929: }
2930: jmean=sum/k;
2931: 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 2932: 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 2933: }
2934:
2935: /*********** Tricode ****************************/
1.145 brouard 2936: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126 brouard 2937: {
1.144 brouard 2938: /**< Uses cptcovn+2*cptcovprod as the number of covariates */
2939: /* 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 2940: * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145 brouard 2941: * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.169 brouard 2942: * nbcode[Tvar[j]][1]=
1.144 brouard 2943: */
1.130 brouard 2944:
1.145 brouard 2945: int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136 brouard 2946: int modmaxcovj=0; /* Modality max of covariates j */
1.145 brouard 2947: int cptcode=0; /* Modality max of covariates j */
2948: int modmincovj=0; /* Modality min of covariates j */
2949:
2950:
1.126 brouard 2951: cptcoveff=0;
2952:
1.145 brouard 2953: for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.144 brouard 2954: for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126 brouard 2955:
1.145 brouard 2956: /* Loop on covariates without age and products */
2957: for (j=1; j<=(cptcovs); j++) { /* model V1 + V2*age+ V3 + V3*V4 : V1 + V3 = 2 only */
2958: for (i=1; i<=imx; i++) { /* Lopp on individuals: reads the data file to get the maximum value of the
1.136 brouard 2959: modality of this covariate Vj*/
1.145 brouard 2960: ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
2961: * If product of Vn*Vm, still boolean *:
2962: * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
2963: * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0 */
2964: /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136 brouard 2965: modality of the nth covariate of individual i. */
1.145 brouard 2966: if (ij > modmaxcovj)
2967: modmaxcovj=ij;
2968: else if (ij < modmincovj)
2969: modmincovj=ij;
2970: if ((ij < -1) && (ij > NCOVMAX)){
2971: printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
2972: exit(1);
2973: }else
1.136 brouard 2974: Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145 brouard 2975: /* If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126 brouard 2976: /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136 brouard 2977: /* getting the maximum value of the modality of the covariate
2978: (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
2979: female is 1, then modmaxcovj=1.*/
1.126 brouard 2980: }
1.145 brouard 2981: printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
2982: cptcode=modmaxcovj;
1.137 brouard 2983: /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145 brouard 2984: /*for (i=0; i<=cptcode; i++) {*/
2985: for (i=modmincovj; i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
2986: printf("Frequencies of covariates %d V%d %d\n", j, Tvar[j], Ndum[i]);
2987: if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
2988: ncodemax[j]++; /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
2989: }
2990: /* In fact ncodemax[j]=2 (dichotom. variables only) but it could be more for
2991: historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131 brouard 2992: } /* Ndum[-1] number of undefined modalities */
1.126 brouard 2993:
1.136 brouard 2994: /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.145 brouard 2995: /* For covariate j, modalities could be 1, 2, 3, 4. If Ndum[2]=0 ncodemax[j] is not 4 but 3 */
2996: /* If Ndum[3}= 635; Ndum[4]=0; Ndum[5]=0; Ndum[6]=27; Ndum[7]=125;
2997: modmincovj=3; modmaxcovj = 7;
2998: There are only 3 modalities non empty (or 2 if 27 is too few) : ncodemax[j]=3;
2999: which will be coded 0, 1, 2 which in binary on 3-1 digits are 0=00 1=01, 2=10; defining two dummy
3000: variables V1_1 and V1_2.
3001: nbcode[Tvar[j]][ij]=k;
3002: nbcode[Tvar[j]][1]=0;
3003: nbcode[Tvar[j]][2]=1;
3004: nbcode[Tvar[j]][3]=2;
3005: */
3006: ij=1; /* ij is similar to i but can jumps over null modalities */
3007: for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
3008: for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
3009: /*recode from 0 */
1.131 brouard 3010: if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
3011: nbcode[Tvar[j]][ij]=k; /* stores the modality in an array nbcode.
3012: k is a modality. If we have model=V1+V1*sex
3013: then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
1.126 brouard 3014: ij++;
3015: }
3016: if (ij > ncodemax[j]) break;
1.137 brouard 3017: } /* end of loop on */
3018: } /* end of loop on modality */
3019: } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/
3020:
1.145 brouard 3021: for (k=-1; k< maxncov; k++) Ndum[k]=0;
1.137 brouard 3022:
1.145 brouard 3023: for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */
3024: /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
3025: ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
3026: Ndum[ij]++;
3027: }
1.126 brouard 3028:
3029: ij=1;
1.145 brouard 3030: for (i=0; i<= maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
3031: /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126 brouard 3032: if((Ndum[i]!=0) && (i<=ncovcol)){
1.145 brouard 3033: /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
3034: Tvaraff[ij]=i; /*For printing (unclear) */
1.126 brouard 3035: ij++;
1.145 brouard 3036: }else
3037: Tvaraff[ij]=0;
1.126 brouard 3038: }
1.131 brouard 3039: ij--;
1.144 brouard 3040: cptcoveff=ij; /*Number of total covariates*/
1.145 brouard 3041:
1.126 brouard 3042: }
3043:
1.145 brouard 3044:
1.126 brouard 3045: /*********** Health Expectancies ****************/
3046:
1.127 brouard 3047: 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 3048:
3049: {
3050: /* Health expectancies, no variances */
1.164 brouard 3051: int i, j, nhstepm, hstepm, h, nstepm;
1.126 brouard 3052: int nhstepma, nstepma; /* Decreasing with age */
3053: double age, agelim, hf;
3054: double ***p3mat;
3055: double eip;
3056:
3057: pstamp(ficreseij);
3058: fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
3059: fprintf(ficreseij,"# Age");
3060: for(i=1; i<=nlstate;i++){
3061: for(j=1; j<=nlstate;j++){
3062: fprintf(ficreseij," e%1d%1d ",i,j);
3063: }
3064: fprintf(ficreseij," e%1d. ",i);
3065: }
3066: fprintf(ficreseij,"\n");
3067:
3068:
3069: if(estepm < stepm){
3070: printf ("Problem %d lower than %d\n",estepm, stepm);
3071: }
3072: else hstepm=estepm;
3073: /* We compute the life expectancy from trapezoids spaced every estepm months
3074: * This is mainly to measure the difference between two models: for example
3075: * if stepm=24 months pijx are given only every 2 years and by summing them
3076: * we are calculating an estimate of the Life Expectancy assuming a linear
3077: * progression in between and thus overestimating or underestimating according
3078: * to the curvature of the survival function. If, for the same date, we
3079: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3080: * to compare the new estimate of Life expectancy with the same linear
3081: * hypothesis. A more precise result, taking into account a more precise
3082: * curvature will be obtained if estepm is as small as stepm. */
3083:
3084: /* For example we decided to compute the life expectancy with the smallest unit */
3085: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3086: nhstepm is the number of hstepm from age to agelim
3087: nstepm is the number of stepm from age to agelin.
3088: Look at hpijx to understand the reason of that which relies in memory size
3089: and note for a fixed period like estepm months */
3090: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3091: survival function given by stepm (the optimization length). Unfortunately it
3092: means that if the survival funtion is printed only each two years of age and if
3093: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3094: results. So we changed our mind and took the option of the best precision.
3095: */
3096: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3097:
3098: agelim=AGESUP;
3099: /* If stepm=6 months */
3100: /* Computed by stepm unit matrices, product of hstepm matrices, stored
3101: in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
3102:
3103: /* nhstepm age range expressed in number of stepm */
3104: nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3105: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3106: /* if (stepm >= YEARM) hstepm=1;*/
3107: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3108: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3109:
3110: for (age=bage; age<=fage; age ++){
3111: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3112: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3113: /* if (stepm >= YEARM) hstepm=1;*/
3114: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3115:
3116: /* If stepm=6 months */
3117: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3118: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3119:
3120: hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3121:
3122: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3123:
3124: printf("%d|",(int)age);fflush(stdout);
3125: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3126:
3127: /* Computing expectancies */
3128: for(i=1; i<=nlstate;i++)
3129: for(j=1; j<=nlstate;j++)
3130: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3131: eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
3132:
3133: /* 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]);*/
3134:
3135: }
3136:
3137: fprintf(ficreseij,"%3.0f",age );
3138: for(i=1; i<=nlstate;i++){
3139: eip=0;
3140: for(j=1; j<=nlstate;j++){
3141: eip +=eij[i][j][(int)age];
3142: fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
3143: }
3144: fprintf(ficreseij,"%9.4f", eip );
3145: }
3146: fprintf(ficreseij,"\n");
3147:
3148: }
3149: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3150: printf("\n");
3151: fprintf(ficlog,"\n");
3152:
3153: }
3154:
1.127 brouard 3155: 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 3156:
3157: {
3158: /* Covariances of health expectancies eij and of total life expectancies according
3159: to initial status i, ei. .
3160: */
3161: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
3162: int nhstepma, nstepma; /* Decreasing with age */
3163: double age, agelim, hf;
3164: double ***p3matp, ***p3matm, ***varhe;
3165: double **dnewm,**doldm;
3166: double *xp, *xm;
3167: double **gp, **gm;
3168: double ***gradg, ***trgradg;
3169: int theta;
3170:
3171: double eip, vip;
3172:
3173: varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
3174: xp=vector(1,npar);
3175: xm=vector(1,npar);
3176: dnewm=matrix(1,nlstate*nlstate,1,npar);
3177: doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
3178:
3179: pstamp(ficresstdeij);
3180: fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
3181: fprintf(ficresstdeij,"# Age");
3182: for(i=1; i<=nlstate;i++){
3183: for(j=1; j<=nlstate;j++)
3184: fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
3185: fprintf(ficresstdeij," e%1d. ",i);
3186: }
3187: fprintf(ficresstdeij,"\n");
3188:
3189: pstamp(ficrescveij);
3190: fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
3191: fprintf(ficrescveij,"# Age");
3192: for(i=1; i<=nlstate;i++)
3193: for(j=1; j<=nlstate;j++){
3194: cptj= (j-1)*nlstate+i;
3195: for(i2=1; i2<=nlstate;i2++)
3196: for(j2=1; j2<=nlstate;j2++){
3197: cptj2= (j2-1)*nlstate+i2;
3198: if(cptj2 <= cptj)
3199: fprintf(ficrescveij," %1d%1d,%1d%1d",i,j,i2,j2);
3200: }
3201: }
3202: fprintf(ficrescveij,"\n");
3203:
3204: if(estepm < stepm){
3205: printf ("Problem %d lower than %d\n",estepm, stepm);
3206: }
3207: else hstepm=estepm;
3208: /* We compute the life expectancy from trapezoids spaced every estepm months
3209: * This is mainly to measure the difference between two models: for example
3210: * if stepm=24 months pijx are given only every 2 years and by summing them
3211: * we are calculating an estimate of the Life Expectancy assuming a linear
3212: * progression in between and thus overestimating or underestimating according
3213: * to the curvature of the survival function. If, for the same date, we
3214: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3215: * to compare the new estimate of Life expectancy with the same linear
3216: * hypothesis. A more precise result, taking into account a more precise
3217: * curvature will be obtained if estepm is as small as stepm. */
3218:
3219: /* For example we decided to compute the life expectancy with the smallest unit */
3220: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3221: nhstepm is the number of hstepm from age to agelim
3222: nstepm is the number of stepm from age to agelin.
3223: Look at hpijx to understand the reason of that which relies in memory size
3224: and note for a fixed period like estepm months */
3225: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3226: survival function given by stepm (the optimization length). Unfortunately it
3227: means that if the survival funtion is printed only each two years of age and if
3228: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3229: results. So we changed our mind and took the option of the best precision.
3230: */
3231: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3232:
3233: /* If stepm=6 months */
3234: /* nhstepm age range expressed in number of stepm */
3235: agelim=AGESUP;
3236: nstepm=(int) rint((agelim-bage)*YEARM/stepm);
3237: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3238: /* if (stepm >= YEARM) hstepm=1;*/
3239: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3240:
3241: p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3242: p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3243: gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
3244: trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
3245: gp=matrix(0,nhstepm,1,nlstate*nlstate);
3246: gm=matrix(0,nhstepm,1,nlstate*nlstate);
3247:
3248: for (age=bage; age<=fage; age ++){
3249: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3250: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3251: /* if (stepm >= YEARM) hstepm=1;*/
3252: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3253:
3254: /* If stepm=6 months */
3255: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3256: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3257:
3258: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3259:
3260: /* Computing Variances of health expectancies */
3261: /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
3262: decrease memory allocation */
3263: for(theta=1; theta <=npar; theta++){
3264: for(i=1; i<=npar; i++){
3265: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3266: xm[i] = x[i] - (i==theta ?delti[theta]:0);
3267: }
3268: hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);
3269: hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);
3270:
3271: for(j=1; j<= nlstate; j++){
3272: for(i=1; i<=nlstate; i++){
3273: for(h=0; h<=nhstepm-1; h++){
3274: gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
3275: gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
3276: }
3277: }
3278: }
3279:
3280: for(ij=1; ij<= nlstate*nlstate; ij++)
3281: for(h=0; h<=nhstepm-1; h++){
3282: gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
3283: }
3284: }/* End theta */
3285:
3286:
3287: for(h=0; h<=nhstepm-1; h++)
3288: for(j=1; j<=nlstate*nlstate;j++)
3289: for(theta=1; theta <=npar; theta++)
3290: trgradg[h][j][theta]=gradg[h][theta][j];
3291:
3292:
3293: for(ij=1;ij<=nlstate*nlstate;ij++)
3294: for(ji=1;ji<=nlstate*nlstate;ji++)
3295: varhe[ij][ji][(int)age] =0.;
3296:
3297: printf("%d|",(int)age);fflush(stdout);
3298: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3299: for(h=0;h<=nhstepm-1;h++){
3300: for(k=0;k<=nhstepm-1;k++){
3301: matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
3302: matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
3303: for(ij=1;ij<=nlstate*nlstate;ij++)
3304: for(ji=1;ji<=nlstate*nlstate;ji++)
3305: varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
3306: }
3307: }
3308:
3309: /* Computing expectancies */
3310: hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3311: for(i=1; i<=nlstate;i++)
3312: for(j=1; j<=nlstate;j++)
3313: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3314: eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
3315:
3316: /* 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]);*/
3317:
3318: }
3319:
3320: fprintf(ficresstdeij,"%3.0f",age );
3321: for(i=1; i<=nlstate;i++){
3322: eip=0.;
3323: vip=0.;
3324: for(j=1; j<=nlstate;j++){
3325: eip += eij[i][j][(int)age];
3326: for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
3327: vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
3328: fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
3329: }
3330: fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
3331: }
3332: fprintf(ficresstdeij,"\n");
3333:
3334: fprintf(ficrescveij,"%3.0f",age );
3335: for(i=1; i<=nlstate;i++)
3336: for(j=1; j<=nlstate;j++){
3337: cptj= (j-1)*nlstate+i;
3338: for(i2=1; i2<=nlstate;i2++)
3339: for(j2=1; j2<=nlstate;j2++){
3340: cptj2= (j2-1)*nlstate+i2;
3341: if(cptj2 <= cptj)
3342: fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
3343: }
3344: }
3345: fprintf(ficrescveij,"\n");
3346:
3347: }
3348: free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
3349: free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
3350: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
3351: free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
3352: free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3353: free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3354: printf("\n");
3355: fprintf(ficlog,"\n");
3356:
3357: free_vector(xm,1,npar);
3358: free_vector(xp,1,npar);
3359: free_matrix(dnewm,1,nlstate*nlstate,1,npar);
3360: free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
3361: free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
3362: }
3363:
3364: /************ Variance ******************/
3365: 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[])
3366: {
3367: /* Variance of health expectancies */
3368: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
3369: /* double **newm;*/
1.169 brouard 3370: /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
3371:
3372: int movingaverage();
1.126 brouard 3373: double **dnewm,**doldm;
3374: double **dnewmp,**doldmp;
3375: int i, j, nhstepm, hstepm, h, nstepm ;
1.164 brouard 3376: int k;
1.126 brouard 3377: double *xp;
3378: double **gp, **gm; /* for var eij */
3379: double ***gradg, ***trgradg; /*for var eij */
3380: double **gradgp, **trgradgp; /* for var p point j */
3381: double *gpp, *gmp; /* for var p point j */
3382: double **varppt; /* for var p point j nlstate to nlstate+ndeath */
3383: double ***p3mat;
3384: double age,agelim, hf;
3385: double ***mobaverage;
3386: int theta;
3387: char digit[4];
3388: char digitp[25];
3389:
3390: char fileresprobmorprev[FILENAMELENGTH];
3391:
3392: if(popbased==1){
3393: if(mobilav!=0)
3394: strcpy(digitp,"-populbased-mobilav-");
3395: else strcpy(digitp,"-populbased-nomobil-");
3396: }
3397: else
3398: strcpy(digitp,"-stablbased-");
3399:
3400: if (mobilav!=0) {
3401: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3402: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
3403: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
3404: printf(" Error in movingaverage mobilav=%d\n",mobilav);
3405: }
3406: }
3407:
3408: strcpy(fileresprobmorprev,"prmorprev");
3409: sprintf(digit,"%-d",ij);
3410: /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
3411: strcat(fileresprobmorprev,digit); /* Tvar to be done */
3412: strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
3413: strcat(fileresprobmorprev,fileres);
3414: if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
3415: printf("Problem with resultfile: %s\n", fileresprobmorprev);
3416: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
3417: }
3418: printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3419:
3420: fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3421: pstamp(ficresprobmorprev);
3422: 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);
3423: fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
3424: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3425: fprintf(ficresprobmorprev," p.%-d SE",j);
3426: for(i=1; i<=nlstate;i++)
3427: fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
3428: }
3429: fprintf(ficresprobmorprev,"\n");
3430: fprintf(ficgp,"\n# Routine varevsij");
3431: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
3432: 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");
3433: fprintf(fichtm,"\n<br>%s <br>\n",digitp);
3434: /* } */
3435: varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3436: pstamp(ficresvij);
3437: fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n# (weighted average of eij where weights are ");
3438: if(popbased==1)
1.128 brouard 3439: 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 3440: else
3441: fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
3442: fprintf(ficresvij,"# Age");
3443: for(i=1; i<=nlstate;i++)
3444: for(j=1; j<=nlstate;j++)
3445: fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
3446: fprintf(ficresvij,"\n");
3447:
3448: xp=vector(1,npar);
3449: dnewm=matrix(1,nlstate,1,npar);
3450: doldm=matrix(1,nlstate,1,nlstate);
3451: dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
3452: doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3453:
3454: gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
3455: gpp=vector(nlstate+1,nlstate+ndeath);
3456: gmp=vector(nlstate+1,nlstate+ndeath);
3457: trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
3458:
3459: if(estepm < stepm){
3460: printf ("Problem %d lower than %d\n",estepm, stepm);
3461: }
3462: else hstepm=estepm;
3463: /* For example we decided to compute the life expectancy with the smallest unit */
3464: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3465: nhstepm is the number of hstepm from age to agelim
3466: nstepm is the number of stepm from age to agelin.
1.128 brouard 3467: Look at function hpijx to understand why (it is linked to memory size questions) */
1.126 brouard 3468: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3469: survival function given by stepm (the optimization length). Unfortunately it
3470: means that if the survival funtion is printed every two years of age and if
3471: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3472: results. So we changed our mind and took the option of the best precision.
3473: */
3474: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3475: agelim = AGESUP;
3476: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3477: nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3478: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3479: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3480: gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
3481: gp=matrix(0,nhstepm,1,nlstate);
3482: gm=matrix(0,nhstepm,1,nlstate);
3483:
3484:
3485: for(theta=1; theta <=npar; theta++){
3486: for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
3487: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3488: }
3489: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3490: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3491:
3492: if (popbased==1) {
3493: if(mobilav ==0){
3494: for(i=1; i<=nlstate;i++)
3495: prlim[i][i]=probs[(int)age][i][ij];
3496: }else{ /* mobilav */
3497: for(i=1; i<=nlstate;i++)
3498: prlim[i][i]=mobaverage[(int)age][i][ij];
3499: }
3500: }
3501:
3502: for(j=1; j<= nlstate; j++){
3503: for(h=0; h<=nhstepm; h++){
3504: for(i=1, gp[h][j]=0.;i<=nlstate;i++)
3505: gp[h][j] += prlim[i][i]*p3mat[i][j][h];
3506: }
3507: }
3508: /* This for computing probability of death (h=1 means
3509: computed over hstepm matrices product = hstepm*stepm months)
3510: as a weighted average of prlim.
3511: */
3512: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3513: for(i=1,gpp[j]=0.; i<= nlstate; i++)
3514: gpp[j] += prlim[i][i]*p3mat[i][j][1];
3515: }
3516: /* end probability of death */
3517:
3518: for(i=1; i<=npar; i++) /* Computes gradient x - delta */
3519: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3520: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3521: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3522:
3523: if (popbased==1) {
3524: if(mobilav ==0){
3525: for(i=1; i<=nlstate;i++)
3526: prlim[i][i]=probs[(int)age][i][ij];
3527: }else{ /* mobilav */
3528: for(i=1; i<=nlstate;i++)
3529: prlim[i][i]=mobaverage[(int)age][i][ij];
3530: }
3531: }
3532:
1.128 brouard 3533: for(j=1; j<= nlstate; j++){ /* Sum of wi * eij = e.j */
1.126 brouard 3534: for(h=0; h<=nhstepm; h++){
3535: for(i=1, gm[h][j]=0.;i<=nlstate;i++)
3536: gm[h][j] += prlim[i][i]*p3mat[i][j][h];
3537: }
3538: }
3539: /* This for computing probability of death (h=1 means
3540: computed over hstepm matrices product = hstepm*stepm months)
3541: as a weighted average of prlim.
3542: */
3543: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3544: for(i=1,gmp[j]=0.; i<= nlstate; i++)
3545: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3546: }
3547: /* end probability of death */
3548:
3549: for(j=1; j<= nlstate; j++) /* vareij */
3550: for(h=0; h<=nhstepm; h++){
3551: gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
3552: }
3553:
3554: for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
3555: gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
3556: }
3557:
3558: } /* End theta */
3559:
3560: trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
3561:
3562: for(h=0; h<=nhstepm; h++) /* veij */
3563: for(j=1; j<=nlstate;j++)
3564: for(theta=1; theta <=npar; theta++)
3565: trgradg[h][j][theta]=gradg[h][theta][j];
3566:
3567: for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
3568: for(theta=1; theta <=npar; theta++)
3569: trgradgp[j][theta]=gradgp[theta][j];
3570:
3571:
3572: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3573: for(i=1;i<=nlstate;i++)
3574: for(j=1;j<=nlstate;j++)
3575: vareij[i][j][(int)age] =0.;
3576:
3577: for(h=0;h<=nhstepm;h++){
3578: for(k=0;k<=nhstepm;k++){
3579: matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
3580: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
3581: for(i=1;i<=nlstate;i++)
3582: for(j=1;j<=nlstate;j++)
3583: vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
3584: }
3585: }
3586:
3587: /* pptj */
3588: matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
3589: matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
3590: for(j=nlstate+1;j<=nlstate+ndeath;j++)
3591: for(i=nlstate+1;i<=nlstate+ndeath;i++)
3592: varppt[j][i]=doldmp[j][i];
3593: /* end ppptj */
3594: /* x centered again */
3595: hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);
3596: prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
3597:
3598: if (popbased==1) {
3599: if(mobilav ==0){
3600: for(i=1; i<=nlstate;i++)
3601: prlim[i][i]=probs[(int)age][i][ij];
3602: }else{ /* mobilav */
3603: for(i=1; i<=nlstate;i++)
3604: prlim[i][i]=mobaverage[(int)age][i][ij];
3605: }
3606: }
3607:
3608: /* This for computing probability of death (h=1 means
3609: computed over hstepm (estepm) matrices product = hstepm*stepm months)
3610: as a weighted average of prlim.
3611: */
3612: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3613: for(i=1,gmp[j]=0.;i<= nlstate; i++)
3614: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3615: }
3616: /* end probability of death */
3617:
3618: fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
3619: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3620: fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
3621: for(i=1; i<=nlstate;i++){
3622: fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
3623: }
3624: }
3625: fprintf(ficresprobmorprev,"\n");
3626:
3627: fprintf(ficresvij,"%.0f ",age );
3628: for(i=1; i<=nlstate;i++)
3629: for(j=1; j<=nlstate;j++){
3630: fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
3631: }
3632: fprintf(ficresvij,"\n");
3633: free_matrix(gp,0,nhstepm,1,nlstate);
3634: free_matrix(gm,0,nhstepm,1,nlstate);
3635: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
3636: free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
3637: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3638: } /* End age */
3639: free_vector(gpp,nlstate+1,nlstate+ndeath);
3640: free_vector(gmp,nlstate+1,nlstate+ndeath);
3641: free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
3642: free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.145 brouard 3643: fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
1.126 brouard 3644: /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131 brouard 3645: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.126 brouard 3646: /* fprintf(ficgp,"\n plot \"%s\" u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
3647: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
3648: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145 brouard 3649: fprintf(ficgp,"\n plot \"%s\" u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
1.170 brouard 3650: fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
1.145 brouard 3651: fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126 brouard 3652: fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
3653: 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);
3654: /* 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);
3655: */
3656: /* fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
3657: fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
3658:
3659: free_vector(xp,1,npar);
3660: free_matrix(doldm,1,nlstate,1,nlstate);
3661: free_matrix(dnewm,1,nlstate,1,npar);
3662: free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3663: free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
3664: free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3665: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3666: fclose(ficresprobmorprev);
3667: fflush(ficgp);
3668: fflush(fichtm);
3669: } /* end varevsij */
3670:
3671: /************ Variance of prevlim ******************/
3672: 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[])
3673: {
3674: /* Variance of prevalence limit */
3675: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164 brouard 3676:
1.126 brouard 3677: double **dnewm,**doldm;
3678: int i, j, nhstepm, hstepm;
3679: double *xp;
3680: double *gp, *gm;
3681: double **gradg, **trgradg;
3682: double age,agelim;
3683: int theta;
3684:
3685: pstamp(ficresvpl);
3686: fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
3687: fprintf(ficresvpl,"# Age");
3688: for(i=1; i<=nlstate;i++)
3689: fprintf(ficresvpl," %1d-%1d",i,i);
3690: fprintf(ficresvpl,"\n");
3691:
3692: xp=vector(1,npar);
3693: dnewm=matrix(1,nlstate,1,npar);
3694: doldm=matrix(1,nlstate,1,nlstate);
3695:
3696: hstepm=1*YEARM; /* Every year of age */
3697: hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
3698: agelim = AGESUP;
3699: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3700: nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3701: if (stepm >= YEARM) hstepm=1;
3702: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
3703: gradg=matrix(1,npar,1,nlstate);
3704: gp=vector(1,nlstate);
3705: gm=vector(1,nlstate);
3706:
3707: for(theta=1; theta <=npar; theta++){
3708: for(i=1; i<=npar; i++){ /* Computes gradient */
3709: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3710: }
3711: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3712: for(i=1;i<=nlstate;i++)
3713: gp[i] = prlim[i][i];
3714:
3715: for(i=1; i<=npar; i++) /* Computes gradient */
3716: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3717: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3718: for(i=1;i<=nlstate;i++)
3719: gm[i] = prlim[i][i];
3720:
3721: for(i=1;i<=nlstate;i++)
3722: gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
3723: } /* End theta */
3724:
3725: trgradg =matrix(1,nlstate,1,npar);
3726:
3727: for(j=1; j<=nlstate;j++)
3728: for(theta=1; theta <=npar; theta++)
3729: trgradg[j][theta]=gradg[theta][j];
3730:
3731: for(i=1;i<=nlstate;i++)
3732: varpl[i][(int)age] =0.;
3733: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
3734: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
3735: for(i=1;i<=nlstate;i++)
3736: varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
3737:
3738: fprintf(ficresvpl,"%.0f ",age );
3739: for(i=1; i<=nlstate;i++)
3740: fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
3741: fprintf(ficresvpl,"\n");
3742: free_vector(gp,1,nlstate);
3743: free_vector(gm,1,nlstate);
3744: free_matrix(gradg,1,npar,1,nlstate);
3745: free_matrix(trgradg,1,nlstate,1,npar);
3746: } /* End age */
3747:
3748: free_vector(xp,1,npar);
3749: free_matrix(doldm,1,nlstate,1,npar);
3750: free_matrix(dnewm,1,nlstate,1,nlstate);
3751:
3752: }
3753:
3754: /************ Variance of one-step probabilities ******************/
3755: 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[])
3756: {
1.164 brouard 3757: int i, j=0, k1, l1, tj;
1.126 brouard 3758: int k2, l2, j1, z1;
1.164 brouard 3759: int k=0, l;
1.145 brouard 3760: int first=1, first1, first2;
1.126 brouard 3761: double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
3762: double **dnewm,**doldm;
3763: double *xp;
3764: double *gp, *gm;
3765: double **gradg, **trgradg;
3766: double **mu;
1.164 brouard 3767: double age, cov[NCOVMAX+1];
1.126 brouard 3768: double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
3769: int theta;
3770: char fileresprob[FILENAMELENGTH];
3771: char fileresprobcov[FILENAMELENGTH];
3772: char fileresprobcor[FILENAMELENGTH];
3773: double ***varpij;
3774:
3775: strcpy(fileresprob,"prob");
3776: strcat(fileresprob,fileres);
3777: if((ficresprob=fopen(fileresprob,"w"))==NULL) {
3778: printf("Problem with resultfile: %s\n", fileresprob);
3779: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
3780: }
3781: strcpy(fileresprobcov,"probcov");
3782: strcat(fileresprobcov,fileres);
3783: if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
3784: printf("Problem with resultfile: %s\n", fileresprobcov);
3785: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
3786: }
3787: strcpy(fileresprobcor,"probcor");
3788: strcat(fileresprobcor,fileres);
3789: if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
3790: printf("Problem with resultfile: %s\n", fileresprobcor);
3791: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
3792: }
3793: printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3794: fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3795: printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3796: fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3797: printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3798: fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3799: pstamp(ficresprob);
3800: fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
3801: fprintf(ficresprob,"# Age");
3802: pstamp(ficresprobcov);
3803: fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
3804: fprintf(ficresprobcov,"# Age");
3805: pstamp(ficresprobcor);
3806: fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
3807: fprintf(ficresprobcor,"# Age");
3808:
3809:
3810: for(i=1; i<=nlstate;i++)
3811: for(j=1; j<=(nlstate+ndeath);j++){
3812: fprintf(ficresprob," p%1d-%1d (SE)",i,j);
3813: fprintf(ficresprobcov," p%1d-%1d ",i,j);
3814: fprintf(ficresprobcor," p%1d-%1d ",i,j);
3815: }
3816: /* fprintf(ficresprob,"\n");
3817: fprintf(ficresprobcov,"\n");
3818: fprintf(ficresprobcor,"\n");
3819: */
1.131 brouard 3820: xp=vector(1,npar);
1.126 brouard 3821: dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3822: doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
3823: mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
3824: varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
3825: first=1;
3826: fprintf(ficgp,"\n# Routine varprob");
3827: fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
3828: fprintf(fichtm,"\n");
3829:
3830: fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
3831: fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
3832: file %s<br>\n",optionfilehtmcov);
3833: fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
3834: and drawn. It helps understanding how is the covariance between two incidences.\
3835: They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
3836: 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. \
3837: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
3838: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
3839: standard deviations wide on each axis. <br>\
3840: Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
3841: and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
3842: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
3843:
3844: cov[1]=1;
1.145 brouard 3845: /* tj=cptcoveff; */
3846: tj = (int) pow(2,cptcoveff);
1.126 brouard 3847: if (cptcovn<1) {tj=1;ncodemax[1]=1;}
3848: j1=0;
1.145 brouard 3849: for(j1=1; j1<=tj;j1++){
3850: /*for(i1=1; i1<=ncodemax[t];i1++){ */
3851: /*j1++;*/
1.126 brouard 3852: if (cptcovn>0) {
3853: fprintf(ficresprob, "\n#********** Variable ");
3854: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3855: fprintf(ficresprob, "**********\n#\n");
3856: fprintf(ficresprobcov, "\n#********** Variable ");
3857: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3858: fprintf(ficresprobcov, "**********\n#\n");
3859:
3860: fprintf(ficgp, "\n#********** Variable ");
3861: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3862: fprintf(ficgp, "**********\n#\n");
3863:
3864:
3865: fprintf(fichtmcov, "\n<hr size=\"2\" color=\"#EC5E5E\">********** Variable ");
3866: for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3867: fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
3868:
3869: fprintf(ficresprobcor, "\n#********** Variable ");
3870: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3871: fprintf(ficresprobcor, "**********\n#");
3872: }
3873:
1.145 brouard 3874: gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
3875: trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3876: gp=vector(1,(nlstate)*(nlstate+ndeath));
3877: gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126 brouard 3878: for (age=bage; age<=fage; age ++){
3879: cov[2]=age;
3880: for (k=1; k<=cptcovn;k++) {
1.145 brouard 3881: cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
3882: * 1 1 1 1 1
3883: * 2 2 1 1 1
3884: * 3 1 2 1 1
3885: */
3886: /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126 brouard 3887: }
3888: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
3889: for (k=1; k<=cptcovprod;k++)
3890: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
3891:
3892:
3893: for(theta=1; theta <=npar; theta++){
3894: for(i=1; i<=npar; i++)
3895: xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
3896:
3897: pmij(pmmij,cov,ncovmodel,xp,nlstate);
3898:
3899: k=0;
3900: for(i=1; i<= (nlstate); i++){
3901: for(j=1; j<=(nlstate+ndeath);j++){
3902: k=k+1;
3903: gp[k]=pmmij[i][j];
3904: }
3905: }
3906:
3907: for(i=1; i<=npar; i++)
3908: xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
3909:
3910: pmij(pmmij,cov,ncovmodel,xp,nlstate);
3911: k=0;
3912: for(i=1; i<=(nlstate); i++){
3913: for(j=1; j<=(nlstate+ndeath);j++){
3914: k=k+1;
3915: gm[k]=pmmij[i][j];
3916: }
3917: }
3918:
3919: for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
3920: gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];
3921: }
3922:
3923: for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
3924: for(theta=1; theta <=npar; theta++)
3925: trgradg[j][theta]=gradg[theta][j];
3926:
3927: matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
3928: matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
3929:
3930: pmij(pmmij,cov,ncovmodel,x,nlstate);
3931:
3932: k=0;
3933: for(i=1; i<=(nlstate); i++){
3934: for(j=1; j<=(nlstate+ndeath);j++){
3935: k=k+1;
3936: mu[k][(int) age]=pmmij[i][j];
3937: }
3938: }
3939: for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
3940: for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
3941: varpij[i][j][(int)age] = doldm[i][j];
3942:
3943: /*printf("\n%d ",(int)age);
3944: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
3945: printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
3946: fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
3947: }*/
3948:
3949: fprintf(ficresprob,"\n%d ",(int)age);
3950: fprintf(ficresprobcov,"\n%d ",(int)age);
3951: fprintf(ficresprobcor,"\n%d ",(int)age);
3952:
3953: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
3954: fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
3955: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
3956: fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
3957: fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
3958: }
3959: i=0;
3960: for (k=1; k<=(nlstate);k++){
3961: for (l=1; l<=(nlstate+ndeath);l++){
1.145 brouard 3962: i++;
1.126 brouard 3963: fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
3964: fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
3965: for (j=1; j<=i;j++){
1.145 brouard 3966: /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126 brouard 3967: fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
3968: fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
3969: }
3970: }
3971: }/* end of loop for state */
3972: } /* end of loop for age */
1.145 brouard 3973: free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
3974: free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
3975: free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
3976: free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
3977:
1.126 brouard 3978: /* Confidence intervalle of pij */
3979: /*
1.131 brouard 3980: fprintf(ficgp,"\nunset parametric;unset label");
1.126 brouard 3981: fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
3982: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
3983: 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);
3984: fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
3985: fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
3986: fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
3987: */
3988:
3989: /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145 brouard 3990: first1=1;first2=2;
1.126 brouard 3991: for (k2=1; k2<=(nlstate);k2++){
3992: for (l2=1; l2<=(nlstate+ndeath);l2++){
3993: if(l2==k2) continue;
3994: j=(k2-1)*(nlstate+ndeath)+l2;
3995: for (k1=1; k1<=(nlstate);k1++){
3996: for (l1=1; l1<=(nlstate+ndeath);l1++){
3997: if(l1==k1) continue;
3998: i=(k1-1)*(nlstate+ndeath)+l1;
3999: if(i<=j) continue;
4000: for (age=bage; age<=fage; age ++){
4001: if ((int)age %5==0){
4002: v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
4003: v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
4004: cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
4005: mu1=mu[i][(int) age]/stepm*YEARM ;
4006: mu2=mu[j][(int) age]/stepm*YEARM;
4007: c12=cv12/sqrt(v1*v2);
4008: /* Computing eigen value of matrix of covariance */
4009: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
4010: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135 brouard 4011: if ((lc2 <0) || (lc1 <0) ){
1.145 brouard 4012: if(first2==1){
4013: first1=0;
4014: 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);
4015: }
4016: 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);
4017: /* lc1=fabs(lc1); */ /* If we want to have them positive */
4018: /* lc2=fabs(lc2); */
1.135 brouard 4019: }
4020:
1.126 brouard 4021: /* Eigen vectors */
4022: v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
4023: /*v21=sqrt(1.-v11*v11); *//* error */
4024: v21=(lc1-v1)/cv12*v11;
4025: v12=-v21;
4026: v22=v11;
4027: tnalp=v21/v11;
4028: if(first1==1){
4029: first1=0;
4030: 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);
4031: }
4032: 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);
4033: /*printf(fignu*/
4034: /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
4035: /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
4036: if(first==1){
4037: first=0;
4038: fprintf(ficgp,"\nset parametric;unset label");
4039: 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 4040: fprintf(ficgp,"\nset ter png small size 320, 240");
1.126 brouard 4041: fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
4042: :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
4043: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
4044: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
4045: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4046: fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4047: fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
4048: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4049: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4050: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4051: 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",\
4052: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4053: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4054: }else{
4055: first=0;
4056: fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
4057: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4058: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4059: 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",\
4060: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4061: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4062: }/* if first */
4063: } /* age mod 5 */
4064: } /* end loop age */
4065: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4066: first=1;
4067: } /*l12 */
4068: } /* k12 */
4069: } /*l1 */
4070: }/* k1 */
1.169 brouard 4071: /* } */ /* loop covariates */
1.126 brouard 4072: }
4073: free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
4074: free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
4075: free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4076: free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
4077: free_vector(xp,1,npar);
4078: fclose(ficresprob);
4079: fclose(ficresprobcov);
4080: fclose(ficresprobcor);
4081: fflush(ficgp);
4082: fflush(fichtmcov);
4083: }
4084:
4085:
4086: /******************* Printing html file ***********/
4087: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
4088: int lastpass, int stepm, int weightopt, char model[],\
4089: int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
4090: int popforecast, int estepm ,\
4091: double jprev1, double mprev1,double anprev1, \
4092: double jprev2, double mprev2,double anprev2){
4093: int jj1, k1, i1, cpt;
4094:
4095: fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
4096: <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
4097: </ul>");
4098: fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
4099: - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
4100: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
4101: fprintf(fichtm,"\
4102: - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
4103: stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
4104: fprintf(fichtm,"\
4105: - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
4106: subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
4107: fprintf(fichtm,"\
1.128 brouard 4108: - (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 4109: <a href=\"%s\">%s</a> <br>\n",
4110: estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
4111: fprintf(fichtm,"\
4112: - Population projections by age and states: \
4113: <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
4114:
4115: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
4116:
1.145 brouard 4117: m=pow(2,cptcoveff);
1.126 brouard 4118: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4119:
4120: jj1=0;
4121: for(k1=1; k1<=m;k1++){
4122: for(i1=1; i1<=ncodemax[k1];i1++){
4123: jj1++;
4124: if (cptcovn > 0) {
4125: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4126: for (cpt=1; cpt<=cptcoveff;cpt++)
4127: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4128: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4129: }
4130: /* Pij */
1.145 brouard 4131: 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> \
4132: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
1.126 brouard 4133: /* Quasi-incidences */
4134: fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
1.145 brouard 4135: 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> \
4136: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
1.126 brouard 4137: /* Period (stable) prevalence in each health state */
1.154 brouard 4138: for(cpt=1; cpt<=nlstate;cpt++){
1.166 brouard 4139: 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> \
4140: <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 4141: }
4142: for(cpt=1; cpt<=nlstate;cpt++) {
1.154 brouard 4143: 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> \
4144: <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 4145: }
4146: } /* end i1 */
4147: }/* End k1 */
4148: fprintf(fichtm,"</ul>");
4149:
4150:
4151: fprintf(fichtm,"\
4152: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
4153: - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
4154:
4155: fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4156: subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
4157: fprintf(fichtm,"\
4158: - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4159: subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
4160:
4161: fprintf(fichtm,"\
4162: - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4163: subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
4164: fprintf(fichtm,"\
4165: - 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): \
4166: <a href=\"%s\">%s</a> <br>\n</li>",
4167: estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
4168: fprintf(fichtm,"\
4169: - (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): \
4170: <a href=\"%s\">%s</a> <br>\n</li>",
4171: estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
4172: fprintf(fichtm,"\
1.128 brouard 4173: - 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 4174: estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
4175: fprintf(fichtm,"\
1.128 brouard 4176: - 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",
4177: estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
1.126 brouard 4178: fprintf(fichtm,"\
4179: - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
4180: subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
4181:
4182: /* if(popforecast==1) fprintf(fichtm,"\n */
4183: /* - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
4184: /* - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
4185: /* <br>",fileres,fileres,fileres,fileres); */
4186: /* else */
4187: /* 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); */
4188: fflush(fichtm);
4189: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
4190:
1.145 brouard 4191: m=pow(2,cptcoveff);
1.126 brouard 4192: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4193:
4194: jj1=0;
4195: for(k1=1; k1<=m;k1++){
4196: for(i1=1; i1<=ncodemax[k1];i1++){
4197: jj1++;
4198: if (cptcovn > 0) {
4199: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4200: for (cpt=1; cpt<=cptcoveff;cpt++)
4201: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4202: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4203: }
4204: for(cpt=1; cpt<=nlstate;cpt++) {
4205: fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.145 brouard 4206: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
4207: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);
1.126 brouard 4208: }
4209: fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128 brouard 4210: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
4211: true period expectancies (those weighted with period prevalences are also\
4212: drawn in addition to the population based expectancies computed using\
4213: observed and cahotic prevalences: %s%d.png<br>\
1.126 brouard 4214: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
4215: } /* end i1 */
4216: }/* End k1 */
4217: fprintf(fichtm,"</ul>");
4218: fflush(fichtm);
4219: }
4220:
4221: /******************* Gnuplot file **************/
4222: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4223:
4224: char dirfileres[132],optfileres[132];
1.164 brouard 4225: int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.130 brouard 4226: int ng=0;
1.126 brouard 4227: /* if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
4228: /* printf("Problem with file %s",optionfilegnuplot); */
4229: /* fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
4230: /* } */
4231:
4232: /*#ifdef windows */
4233: fprintf(ficgp,"cd \"%s\" \n",pathc);
4234: /*#endif */
4235: m=pow(2,cptcoveff);
4236:
4237: strcpy(dirfileres,optionfilefiname);
4238: strcpy(optfileres,"vpl");
4239: /* 1eme*/
1.153 brouard 4240: fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
1.126 brouard 4241: for (cpt=1; cpt<= nlstate ; cpt ++) {
1.145 brouard 4242: for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
4243: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
4244: fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
1.126 brouard 4245: fprintf(ficgp,"set xlabel \"Age\" \n\
4246: set ylabel \"Probability\" \n\
1.145 brouard 4247: set ter png small size 320, 240\n\
1.170 brouard 4248: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
1.126 brouard 4249:
4250: for (i=1; i<= nlstate ; i ++) {
1.170 brouard 4251: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4252: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4253: }
1.170 brouard 4254: 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 4255: for (i=1; i<= nlstate ; i ++) {
1.170 brouard 4256: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4257: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4258: }
1.170 brouard 4259: 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 4260: for (i=1; i<= nlstate ; i ++) {
1.170 brouard 4261: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4262: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4263: }
1.145 brouard 4264: 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 4265: }
4266: }
4267: /*2 eme*/
1.153 brouard 4268: fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
1.126 brouard 4269: for (k1=1; k1<= m ; k1 ++) {
4270: fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
1.145 brouard 4271: fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
1.126 brouard 4272:
4273: for (i=1; i<= nlstate+1 ; i ++) {
4274: k=2*i;
1.170 brouard 4275: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126 brouard 4276: for (j=1; j<= nlstate+1 ; j ++) {
1.170 brouard 4277: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4278: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4279: }
4280: if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
4281: else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
1.170 brouard 4282: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126 brouard 4283: for (j=1; j<= nlstate+1 ; j ++) {
1.170 brouard 4284: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4285: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4286: }
1.145 brouard 4287: fprintf(ficgp,"\" t\"\" w l lt 0,");
1.170 brouard 4288: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126 brouard 4289: for (j=1; j<= nlstate+1 ; j ++) {
1.170 brouard 4290: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4291: else fprintf(ficgp," %%*lf (%%*lf)");
1.126 brouard 4292: }
1.145 brouard 4293: if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
4294: else fprintf(ficgp,"\" t\"\" w l lt 0,");
1.126 brouard 4295: }
4296: }
4297:
4298: /*3eme*/
4299:
4300: for (k1=1; k1<= m ; k1 ++) {
4301: for (cpt=1; cpt<= nlstate ; cpt ++) {
4302: /* k=2+nlstate*(2*cpt-2); */
4303: k=2+(nlstate+1)*(cpt-1);
4304: fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
1.145 brouard 4305: fprintf(ficgp,"set ter png small size 320, 240\n\
1.126 brouard 4306: 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);
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: fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4311: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4312: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4313:
4314: */
4315: for (i=1; i< nlstate ; i ++) {
4316: 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);
4317: /* 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);*/
4318:
4319: }
4320: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
4321: }
4322: }
4323:
4324: /* CV preval stable (period) */
1.153 brouard 4325: for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
4326: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.126 brouard 4327: k=3;
1.153 brouard 4328: fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
1.145 brouard 4329: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
1.126 brouard 4330: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.145 brouard 4331: set ter png small size 320, 240\n\
1.126 brouard 4332: unset log y\n\
1.153 brouard 4333: plot [%.f:%.f] ", ageminpar, agemaxpar);
4334: for (i=1; i<= nlstate ; i ++){
4335: if(i==1)
4336: fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
4337: else
4338: fprintf(ficgp,", '' ");
1.154 brouard 4339: l=(nlstate+ndeath)*(i-1)+1;
4340: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.153 brouard 4341: for (j=1; j<= (nlstate-1) ; j ++)
4342: fprintf(ficgp,"+$%d",k+l+j);
4343: fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
4344: } /* nlstate */
4345: fprintf(ficgp,"\n");
4346: } /* end cpt state*/
4347: } /* end covariate */
1.126 brouard 4348:
4349: /* proba elementaires */
4350: for(i=1,jk=1; i <=nlstate; i++){
4351: for(k=1; k <=(nlstate+ndeath); k++){
4352: if (k != i) {
4353: for(j=1; j <=ncovmodel; j++){
4354: fprintf(ficgp,"p%d=%f ",jk,p[jk]);
4355: jk++;
4356: fprintf(ficgp,"\n");
4357: }
4358: }
4359: }
4360: }
1.145 brouard 4361: /*goto avoid;*/
1.126 brouard 4362: for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
4363: for(jk=1; jk <=m; jk++) {
1.145 brouard 4364: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);
1.126 brouard 4365: if (ng==2)
4366: fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
4367: else
4368: fprintf(ficgp,"\nset title \"Probability\"\n");
1.145 brouard 4369: fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot [%.f:%.f] ",ageminpar,agemaxpar);
1.126 brouard 4370: i=1;
4371: for(k2=1; k2<=nlstate; k2++) {
4372: k3=i;
4373: for(k=1; k<=(nlstate+ndeath); k++) {
4374: if (k != k2){
4375: if(ng==2)
4376: fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
4377: else
4378: fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
1.141 brouard 4379: ij=1;/* To be checked else nbcode[0][0] wrong */
1.126 brouard 4380: for(j=3; j <=ncovmodel; j++) {
1.145 brouard 4381: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /\* Bug valgrind *\/ */
4382: /* /\*fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);*\/ */
4383: /* ij++; */
4384: /* } */
4385: /* else */
1.126 brouard 4386: fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4387: }
4388: fprintf(ficgp,")/(1");
4389:
4390: for(k1=1; k1 <=nlstate; k1++){
4391: fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
4392: ij=1;
4393: for(j=3; j <=ncovmodel; j++){
1.145 brouard 4394: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { */
4395: /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]); */
4396: /* ij++; */
4397: /* } */
4398: /* else */
1.126 brouard 4399: fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4400: }
4401: fprintf(ficgp,")");
4402: }
4403: fprintf(ficgp,") t \"p%d%d\" ", k2,k);
4404: if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
4405: i=i+ncovmodel;
4406: }
4407: } /* end k */
4408: } /* end k2 */
4409: } /* end jk */
4410: } /* end ng */
1.164 brouard 4411: /* avoid: */
1.126 brouard 4412: fflush(ficgp);
4413: } /* end gnuplot */
4414:
4415:
4416: /*************** Moving average **************/
4417: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
4418:
4419: int i, cpt, cptcod;
4420: int modcovmax =1;
4421: int mobilavrange, mob;
4422: double age;
4423:
4424: modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
4425: a covariate has 2 modalities */
4426: if (cptcovn<1) modcovmax=1; /* At least 1 pass */
4427:
4428: if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
4429: if(mobilav==1) mobilavrange=5; /* default */
4430: else mobilavrange=mobilav;
4431: for (age=bage; age<=fage; age++)
4432: for (i=1; i<=nlstate;i++)
4433: for (cptcod=1;cptcod<=modcovmax;cptcod++)
4434: mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
4435: /* We keep the original values on the extreme ages bage, fage and for
4436: fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
4437: we use a 5 terms etc. until the borders are no more concerned.
4438: */
4439: for (mob=3;mob <=mobilavrange;mob=mob+2){
4440: for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
4441: for (i=1; i<=nlstate;i++){
4442: for (cptcod=1;cptcod<=modcovmax;cptcod++){
4443: mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
4444: for (cpt=1;cpt<=(mob-1)/2;cpt++){
4445: mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
4446: mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
4447: }
4448: mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
4449: }
4450: }
4451: }/* end age */
4452: }/* end mob */
4453: }else return -1;
4454: return 0;
4455: }/* End movingaverage */
4456:
4457:
4458: /************** Forecasting ******************/
1.169 brouard 4459: 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 4460: /* proj1, year, month, day of starting projection
4461: agemin, agemax range of age
4462: dateprev1 dateprev2 range of dates during which prevalence is computed
4463: anproj2 year of en of projection (same day and month as proj1).
4464: */
1.164 brouard 4465: int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126 brouard 4466: double agec; /* generic age */
4467: double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
4468: double *popeffectif,*popcount;
4469: double ***p3mat;
4470: double ***mobaverage;
4471: char fileresf[FILENAMELENGTH];
4472:
4473: agelim=AGESUP;
4474: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4475:
4476: strcpy(fileresf,"f");
4477: strcat(fileresf,fileres);
4478: if((ficresf=fopen(fileresf,"w"))==NULL) {
4479: printf("Problem with forecast resultfile: %s\n", fileresf);
4480: fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
4481: }
4482: printf("Computing forecasting: result on file '%s' \n", fileresf);
4483: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
4484:
4485: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4486:
4487: if (mobilav!=0) {
4488: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4489: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4490: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4491: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4492: }
4493: }
4494:
4495: stepsize=(int) (stepm+YEARM-1)/YEARM;
4496: if (stepm<=12) stepsize=1;
4497: if(estepm < stepm){
4498: printf ("Problem %d lower than %d\n",estepm, stepm);
4499: }
4500: else hstepm=estepm;
4501:
4502: hstepm=hstepm/stepm;
4503: yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp and
4504: fractional in yp1 */
4505: anprojmean=yp;
4506: yp2=modf((yp1*12),&yp);
4507: mprojmean=yp;
4508: yp1=modf((yp2*30.5),&yp);
4509: jprojmean=yp;
4510: if(jprojmean==0) jprojmean=1;
4511: if(mprojmean==0) jprojmean=1;
4512:
4513: i1=cptcoveff;
4514: if (cptcovn < 1){i1=1;}
4515:
4516: fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
4517:
4518: fprintf(ficresf,"#****** Routine prevforecast **\n");
4519:
4520: /* if (h==(int)(YEARM*yearp)){ */
4521: for(cptcov=1, k=0;cptcov<=i1;cptcov++){
4522: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4523: k=k+1;
4524: fprintf(ficresf,"\n#******");
4525: for(j=1;j<=cptcoveff;j++) {
4526: 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]]);
4527: }
4528: fprintf(ficresf,"******\n");
4529: fprintf(ficresf,"# Covariate valuofcovar yearproj age");
4530: for(j=1; j<=nlstate+ndeath;j++){
4531: for(i=1; i<=nlstate;i++)
4532: fprintf(ficresf," p%d%d",i,j);
4533: fprintf(ficresf," p.%d",j);
4534: }
4535: for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
4536: fprintf(ficresf,"\n");
4537: fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);
4538:
4539: for (agec=fage; agec>=(ageminpar-1); agec--){
4540: nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
4541: nhstepm = nhstepm/hstepm;
4542: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4543: oldm=oldms;savm=savms;
4544: hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
4545:
4546: for (h=0; h<=nhstepm; h++){
4547: if (h*hstepm/YEARM*stepm ==yearp) {
4548: fprintf(ficresf,"\n");
4549: for(j=1;j<=cptcoveff;j++)
4550: fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4551: fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
4552: }
4553: for(j=1; j<=nlstate+ndeath;j++) {
4554: ppij=0.;
4555: for(i=1; i<=nlstate;i++) {
4556: if (mobilav==1)
4557: ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
4558: else {
4559: ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
4560: }
4561: if (h*hstepm/YEARM*stepm== yearp) {
4562: fprintf(ficresf," %.3f", p3mat[i][j][h]);
4563: }
4564: } /* end i */
4565: if (h*hstepm/YEARM*stepm==yearp) {
4566: fprintf(ficresf," %.3f", ppij);
4567: }
4568: }/* end j */
4569: } /* end h */
4570: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4571: } /* end agec */
4572: } /* end yearp */
4573: } /* end cptcod */
4574: } /* end cptcov */
4575:
4576: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4577:
4578: fclose(ficresf);
4579: }
4580:
4581: /************** Forecasting *****not tested NB*************/
1.169 brouard 4582: 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 4583:
4584: int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
4585: int *popage;
4586: double calagedatem, agelim, kk1, kk2;
4587: double *popeffectif,*popcount;
4588: double ***p3mat,***tabpop,***tabpopprev;
4589: double ***mobaverage;
4590: char filerespop[FILENAMELENGTH];
4591:
4592: tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4593: tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4594: agelim=AGESUP;
4595: calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
4596:
4597: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4598:
4599:
4600: strcpy(filerespop,"pop");
4601: strcat(filerespop,fileres);
4602: if((ficrespop=fopen(filerespop,"w"))==NULL) {
4603: printf("Problem with forecast resultfile: %s\n", filerespop);
4604: fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
4605: }
4606: printf("Computing forecasting: result on file '%s' \n", filerespop);
4607: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
4608:
4609: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4610:
4611: if (mobilav!=0) {
4612: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4613: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4614: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4615: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4616: }
4617: }
4618:
4619: stepsize=(int) (stepm+YEARM-1)/YEARM;
4620: if (stepm<=12) stepsize=1;
4621:
4622: agelim=AGESUP;
4623:
4624: hstepm=1;
4625: hstepm=hstepm/stepm;
4626:
4627: if (popforecast==1) {
4628: if((ficpop=fopen(popfile,"r"))==NULL) {
4629: printf("Problem with population file : %s\n",popfile);exit(0);
4630: fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
4631: }
4632: popage=ivector(0,AGESUP);
4633: popeffectif=vector(0,AGESUP);
4634: popcount=vector(0,AGESUP);
4635:
4636: i=1;
4637: while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
4638:
4639: imx=i;
4640: for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
4641: }
4642:
4643: for(cptcov=1,k=0;cptcov<=i2;cptcov++){
4644: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4645: k=k+1;
4646: fprintf(ficrespop,"\n#******");
4647: for(j=1;j<=cptcoveff;j++) {
4648: fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4649: }
4650: fprintf(ficrespop,"******\n");
4651: fprintf(ficrespop,"# Age");
4652: for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
4653: if (popforecast==1) fprintf(ficrespop," [Population]");
4654:
4655: for (cpt=0; cpt<=0;cpt++) {
4656: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4657:
4658: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4659: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4660: nhstepm = nhstepm/hstepm;
4661:
4662: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4663: oldm=oldms;savm=savms;
4664: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4665:
4666: for (h=0; h<=nhstepm; h++){
4667: if (h==(int) (calagedatem+YEARM*cpt)) {
4668: fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4669: }
4670: for(j=1; j<=nlstate+ndeath;j++) {
4671: kk1=0.;kk2=0;
4672: for(i=1; i<=nlstate;i++) {
4673: if (mobilav==1)
4674: kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
4675: else {
4676: kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
4677: }
4678: }
4679: if (h==(int)(calagedatem+12*cpt)){
4680: tabpop[(int)(agedeb)][j][cptcod]=kk1;
4681: /*fprintf(ficrespop," %.3f", kk1);
4682: if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
4683: }
4684: }
4685: for(i=1; i<=nlstate;i++){
4686: kk1=0.;
4687: for(j=1; j<=nlstate;j++){
4688: kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
4689: }
4690: tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
4691: }
4692:
4693: if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
4694: fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
4695: }
4696: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4697: }
4698: }
4699:
4700: /******/
4701:
4702: for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
4703: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4704: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4705: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4706: nhstepm = nhstepm/hstepm;
4707:
4708: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4709: oldm=oldms;savm=savms;
4710: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4711: for (h=0; h<=nhstepm; h++){
4712: if (h==(int) (calagedatem+YEARM*cpt)) {
4713: fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4714: }
4715: for(j=1; j<=nlstate+ndeath;j++) {
4716: kk1=0.;kk2=0;
4717: for(i=1; i<=nlstate;i++) {
4718: kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];
4719: }
4720: if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);
4721: }
4722: }
4723: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4724: }
4725: }
4726: }
4727: }
4728:
4729: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4730:
4731: if (popforecast==1) {
4732: free_ivector(popage,0,AGESUP);
4733: free_vector(popeffectif,0,AGESUP);
4734: free_vector(popcount,0,AGESUP);
4735: }
4736: free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4737: free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4738: fclose(ficrespop);
4739: } /* End of popforecast */
4740:
4741: int fileappend(FILE *fichier, char *optionfich)
4742: {
4743: if((fichier=fopen(optionfich,"a"))==NULL) {
4744: printf("Problem with file: %s\n", optionfich);
4745: fprintf(ficlog,"Problem with file: %s\n", optionfich);
4746: return (0);
4747: }
4748: fflush(fichier);
4749: return (1);
4750: }
4751:
4752:
4753: /**************** function prwizard **********************/
4754: void prwizard(int ncovmodel, int nlstate, int ndeath, char model[], FILE *ficparo)
4755: {
4756:
4757: /* Wizard to print covariance matrix template */
4758:
1.164 brouard 4759: char ca[32], cb[32];
4760: int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126 brouard 4761: int numlinepar;
4762:
4763: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4764: fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4765: for(i=1; i <=nlstate; i++){
4766: jj=0;
4767: for(j=1; j <=nlstate+ndeath; j++){
4768: if(j==i) continue;
4769: jj++;
4770: /*ca[0]= k+'a'-1;ca[1]='\0';*/
4771: printf("%1d%1d",i,j);
4772: fprintf(ficparo,"%1d%1d",i,j);
4773: for(k=1; k<=ncovmodel;k++){
4774: /* printf(" %lf",param[i][j][k]); */
4775: /* fprintf(ficparo," %lf",param[i][j][k]); */
4776: printf(" 0.");
4777: fprintf(ficparo," 0.");
4778: }
4779: printf("\n");
4780: fprintf(ficparo,"\n");
4781: }
4782: }
4783: printf("# Scales (for hessian or gradient estimation)\n");
4784: fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
4785: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
4786: for(i=1; i <=nlstate; i++){
4787: jj=0;
4788: for(j=1; j <=nlstate+ndeath; j++){
4789: if(j==i) continue;
4790: jj++;
4791: fprintf(ficparo,"%1d%1d",i,j);
4792: printf("%1d%1d",i,j);
4793: fflush(stdout);
4794: for(k=1; k<=ncovmodel;k++){
4795: /* printf(" %le",delti3[i][j][k]); */
4796: /* fprintf(ficparo," %le",delti3[i][j][k]); */
4797: printf(" 0.");
4798: fprintf(ficparo," 0.");
4799: }
4800: numlinepar++;
4801: printf("\n");
4802: fprintf(ficparo,"\n");
4803: }
4804: }
4805: printf("# Covariance matrix\n");
4806: /* # 121 Var(a12)\n\ */
4807: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4808: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
4809: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
4810: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
4811: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
4812: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
4813: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4814: fflush(stdout);
4815: fprintf(ficparo,"# Covariance matrix\n");
4816: /* # 121 Var(a12)\n\ */
4817: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4818: /* # ...\n\ */
4819: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4820:
4821: for(itimes=1;itimes<=2;itimes++){
4822: jj=0;
4823: for(i=1; i <=nlstate; i++){
4824: for(j=1; j <=nlstate+ndeath; j++){
4825: if(j==i) continue;
4826: for(k=1; k<=ncovmodel;k++){
4827: jj++;
4828: ca[0]= k+'a'-1;ca[1]='\0';
4829: if(itimes==1){
4830: printf("#%1d%1d%d",i,j,k);
4831: fprintf(ficparo,"#%1d%1d%d",i,j,k);
4832: }else{
4833: printf("%1d%1d%d",i,j,k);
4834: fprintf(ficparo,"%1d%1d%d",i,j,k);
4835: /* printf(" %.5le",matcov[i][j]); */
4836: }
4837: ll=0;
4838: for(li=1;li <=nlstate; li++){
4839: for(lj=1;lj <=nlstate+ndeath; lj++){
4840: if(lj==li) continue;
4841: for(lk=1;lk<=ncovmodel;lk++){
4842: ll++;
4843: if(ll<=jj){
4844: cb[0]= lk +'a'-1;cb[1]='\0';
4845: if(ll<jj){
4846: if(itimes==1){
4847: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4848: fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4849: }else{
4850: printf(" 0.");
4851: fprintf(ficparo," 0.");
4852: }
4853: }else{
4854: if(itimes==1){
4855: printf(" Var(%s%1d%1d)",ca,i,j);
4856: fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
4857: }else{
4858: printf(" 0.");
4859: fprintf(ficparo," 0.");
4860: }
4861: }
4862: }
4863: } /* end lk */
4864: } /* end lj */
4865: } /* end li */
4866: printf("\n");
4867: fprintf(ficparo,"\n");
4868: numlinepar++;
4869: } /* end k*/
4870: } /*end j */
4871: } /* end i */
4872: } /* end itimes */
4873:
4874: } /* end of prwizard */
4875: /******************* Gompertz Likelihood ******************************/
4876: double gompertz(double x[])
4877: {
4878: double A,B,L=0.0,sump=0.,num=0.;
4879: int i,n=0; /* n is the size of the sample */
4880:
4881: for (i=0;i<=imx-1 ; i++) {
4882: sump=sump+weight[i];
4883: /* sump=sump+1;*/
4884: num=num+1;
4885: }
4886:
4887:
4888: /* for (i=0; i<=imx; i++)
4889: 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]);*/
4890:
4891: for (i=1;i<=imx ; i++)
4892: {
4893: if (cens[i] == 1 && wav[i]>1)
4894: A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
4895:
4896: if (cens[i] == 0 && wav[i]>1)
4897: A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
4898: +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);
4899:
4900: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
4901: if (wav[i] > 1 ) { /* ??? */
4902: L=L+A*weight[i];
4903: /* 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]);*/
4904: }
4905: }
4906:
4907: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
4908:
4909: return -2*L*num/sump;
4910: }
4911:
1.136 brouard 4912: #ifdef GSL
4913: /******************* Gompertz_f Likelihood ******************************/
4914: double gompertz_f(const gsl_vector *v, void *params)
4915: {
4916: double A,B,LL=0.0,sump=0.,num=0.;
4917: double *x= (double *) v->data;
4918: int i,n=0; /* n is the size of the sample */
4919:
4920: for (i=0;i<=imx-1 ; i++) {
4921: sump=sump+weight[i];
4922: /* sump=sump+1;*/
4923: num=num+1;
4924: }
4925:
4926:
4927: /* for (i=0; i<=imx; i++)
4928: 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]);*/
4929: printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
4930: for (i=1;i<=imx ; i++)
4931: {
4932: if (cens[i] == 1 && wav[i]>1)
4933: A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
4934:
4935: if (cens[i] == 0 && wav[i]>1)
4936: A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
4937: +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);
4938:
4939: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
4940: if (wav[i] > 1 ) { /* ??? */
4941: LL=LL+A*weight[i];
4942: /* 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]);*/
4943: }
4944: }
4945:
4946: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
4947: printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
4948:
4949: return -2*LL*num/sump;
4950: }
4951: #endif
4952:
1.126 brouard 4953: /******************* Printing html file ***********/
4954: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
4955: int lastpass, int stepm, int weightopt, char model[],\
4956: int imx, double p[],double **matcov,double agemortsup){
4957: int i,k;
4958:
4959: fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
4960: fprintf(fichtm," mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
4961: for (i=1;i<=2;i++)
4962: 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]));
4963: fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
4964: fprintf(fichtm,"</ul>");
4965:
4966: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
4967:
4968: 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>");
4969:
4970: for (k=agegomp;k<(agemortsup-2);k++)
4971: 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]);
4972:
4973:
4974: fflush(fichtm);
4975: }
4976:
4977: /******************* Gnuplot file **************/
4978: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4979:
4980: char dirfileres[132],optfileres[132];
1.164 brouard 4981:
1.126 brouard 4982: int ng;
4983:
4984:
4985: /*#ifdef windows */
4986: fprintf(ficgp,"cd \"%s\" \n",pathc);
4987: /*#endif */
4988:
4989:
4990: strcpy(dirfileres,optionfilefiname);
4991: strcpy(optfileres,"vpl");
4992: fprintf(ficgp,"set out \"graphmort.png\"\n ");
4993: fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
1.145 brouard 4994: fprintf(ficgp, "set ter png small size 320, 240\n set log y\n");
4995: /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126 brouard 4996: fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
4997:
4998: }
4999:
1.136 brouard 5000: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
5001: {
1.126 brouard 5002:
1.136 brouard 5003: /*-------- data file ----------*/
5004: FILE *fic;
5005: char dummy[]=" ";
1.164 brouard 5006: int i=0, j=0, n=0;
1.136 brouard 5007: int linei, month, year,iout;
5008: char line[MAXLINE], linetmp[MAXLINE];
1.164 brouard 5009: char stra[MAXLINE], strb[MAXLINE];
1.136 brouard 5010: char *stratrunc;
5011: int lstra;
1.126 brouard 5012:
5013:
1.136 brouard 5014: if((fic=fopen(datafile,"r"))==NULL) {
5015: printf("Problem while opening datafile: %s\n", datafile);return 1;
5016: fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
5017: }
1.126 brouard 5018:
1.136 brouard 5019: i=1;
5020: linei=0;
5021: while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
5022: linei=linei+1;
5023: for(j=strlen(line); j>=0;j--){ /* Untabifies line */
5024: if(line[j] == '\t')
5025: line[j] = ' ';
5026: }
5027: for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
5028: ;
5029: };
5030: line[j+1]=0; /* Trims blanks at end of line */
5031: if(line[0]=='#'){
5032: fprintf(ficlog,"Comment line\n%s\n",line);
5033: printf("Comment line\n%s\n",line);
5034: continue;
5035: }
5036: trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164 brouard 5037: strcpy(line, linetmp);
1.136 brouard 5038:
1.126 brouard 5039:
1.136 brouard 5040: for (j=maxwav;j>=1;j--){
1.137 brouard 5041: cutv(stra, strb, line, ' ');
1.136 brouard 5042: if(strb[0]=='.') { /* Missing status */
5043: lval=-1;
5044: }else{
5045: errno=0;
5046: lval=strtol(strb,&endptr,10);
5047: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
5048: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5049: 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);
5050: 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 5051: return 1;
5052: }
5053: }
5054: s[j][i]=lval;
5055:
5056: strcpy(line,stra);
5057: cutv(stra, strb,line,' ');
1.169 brouard 5058: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136 brouard 5059: }
1.169 brouard 5060: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136 brouard 5061: month=99;
5062: year=9999;
5063: }else{
1.141 brouard 5064: 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);
5065: 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 5066: return 1;
5067: }
5068: anint[j][i]= (double) year;
5069: mint[j][i]= (double)month;
5070: strcpy(line,stra);
5071: } /* ENd Waves */
5072:
5073: cutv(stra, strb,line,' ');
1.169 brouard 5074: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136 brouard 5075: }
1.169 brouard 5076: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136 brouard 5077: month=99;
5078: year=9999;
5079: }else{
1.141 brouard 5080: 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);
5081: 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 5082: return 1;
5083: }
5084: andc[i]=(double) year;
5085: moisdc[i]=(double) month;
5086: strcpy(line,stra);
5087:
5088: cutv(stra, strb,line,' ');
1.169 brouard 5089: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136 brouard 5090: }
1.169 brouard 5091: else if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136 brouard 5092: month=99;
5093: year=9999;
5094: }else{
1.141 brouard 5095: 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);
5096: 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 5097: return 1;
5098: }
5099: if (year==9999) {
1.141 brouard 5100: 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);
5101: 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 5102: return 1;
1.126 brouard 5103:
1.136 brouard 5104: }
5105: annais[i]=(double)(year);
5106: moisnais[i]=(double)(month);
5107: strcpy(line,stra);
5108:
5109: cutv(stra, strb,line,' ');
5110: errno=0;
5111: dval=strtod(strb,&endptr);
5112: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5113: printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight. Exiting.\n",dval, i,line,linei);
5114: 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 5115: fflush(ficlog);
5116: return 1;
5117: }
5118: weight[i]=dval;
5119: strcpy(line,stra);
5120:
5121: for (j=ncovcol;j>=1;j--){
5122: cutv(stra, strb,line,' ');
5123: if(strb[0]=='.') { /* Missing status */
5124: lval=-1;
5125: }else{
5126: errno=0;
5127: lval=strtol(strb,&endptr,10);
5128: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5129: 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);
5130: 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 5131: return 1;
5132: }
5133: }
5134: if(lval <-1 || lval >1){
1.141 brouard 5135: printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 5136: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5137: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5138: For example, for multinomial values like 1, 2 and 3,\n \
5139: build V1=0 V2=0 for the reference value (1),\n \
5140: V1=1 V2=0 for (2) \n \
5141: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5142: output of IMaCh is often meaningless.\n \
5143: Exiting.\n",lval,linei, i,line,j);
1.141 brouard 5144: fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 5145: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5146: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5147: For example, for multinomial values like 1, 2 and 3,\n \
5148: build V1=0 V2=0 for the reference value (1),\n \
5149: V1=1 V2=0 for (2) \n \
5150: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5151: output of IMaCh is often meaningless.\n \
5152: Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
5153: return 1;
5154: }
5155: covar[j][i]=(double)(lval);
5156: strcpy(line,stra);
5157: }
5158: lstra=strlen(stra);
5159:
5160: if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
5161: stratrunc = &(stra[lstra-9]);
5162: num[i]=atol(stratrunc);
5163: }
5164: else
5165: num[i]=atol(stra);
5166: /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
5167: 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;}*/
5168:
5169: i=i+1;
5170: } /* End loop reading data */
1.126 brouard 5171:
1.136 brouard 5172: *imax=i-1; /* Number of individuals */
5173: fclose(fic);
5174:
5175: return (0);
1.164 brouard 5176: /* endread: */
1.136 brouard 5177: printf("Exiting readdata: ");
5178: fclose(fic);
5179: return (1);
1.126 brouard 5180:
5181:
5182:
1.136 brouard 5183: }
1.145 brouard 5184: void removespace(char *str) {
5185: char *p1 = str, *p2 = str;
5186: do
5187: while (*p2 == ' ')
5188: p2++;
1.169 brouard 5189: while (*p1++ == *p2++);
1.145 brouard 5190: }
5191:
5192: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
5193: * Model V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age
5194: * - cptcovt total number of covariates of the model nbocc(+)+1 = 8
5195: * - cptcovn or number of covariates k of the models excluding age*products =6
5196: * - cptcovage number of covariates with age*products =2
5197: * - cptcovs number of simple covariates
5198: * - 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
5199: * which is a new column after the 9 (ncovcol) variables.
5200: * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
5201: * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
5202: * Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
5203: * - Tvard[k] p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
5204: */
1.136 brouard 5205: {
1.145 brouard 5206: int i, j, k, ks;
1.164 brouard 5207: int j1, k1, k2;
1.136 brouard 5208: char modelsav[80];
1.145 brouard 5209: char stra[80], strb[80], strc[80], strd[80],stre[80];
1.136 brouard 5210:
1.145 brouard 5211: /*removespace(model);*/
1.136 brouard 5212: if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145 brouard 5213: j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
5214: j=nbocc(model,'+'); /**< j=Number of '+' */
5215: j1=nbocc(model,'*'); /**< j1=Number of '*' */
5216: cptcovs=j+1-j1; /**< Number of simple covariates V1+V2*age+V3 +V3*V4=> V1 + V3 =2 */
5217: cptcovt= j+1; /* Number of total covariates in the model V1 + V2*age+ V3 + V3*V4=> 4*/
5218: /* including age products which are counted in cptcovage.
1.169 brouard 5219: * but the covariates which are products must be treated separately: ncovn=4- 2=2 (V1+V3). */
1.145 brouard 5220: cptcovprod=j1; /**< Number of products V1*V2 +v3*age = 2 */
5221: cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1 */
1.136 brouard 5222: strcpy(modelsav,model);
1.137 brouard 5223: if (strstr(model,"AGE") !=0){
5224: printf("Error. AGE must be in lower case 'age' model=%s ",model);
5225: fprintf(ficlog,"Error. AGE must be in lower case model=%s ",model);fflush(ficlog);
1.136 brouard 5226: return 1;
5227: }
1.141 brouard 5228: if (strstr(model,"v") !=0){
5229: printf("Error. 'v' must be in upper case 'V' model=%s ",model);
5230: fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
5231: return 1;
5232: }
1.136 brouard 5233:
1.145 brouard 5234: /* Design
5235: * V1 V2 V3 V4 V5 V6 V7 V8 V9 Weight
5236: * < ncovcol=8 >
5237: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
5238: * k= 1 2 3 4 5 6 7 8
5239: * cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
5240: * covar[k,i], value of kth covariate if not including age for individual i:
5241: * covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
5242: * Tvar[k] # of the kth covariate: Tvar[1]=2 Tvar[4]=3 Tvar[8]=8
5243: * if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and
5244: * Tage[++cptcovage]=k
5245: * if products, new covar are created after ncovcol with k1
5246: * Tvar[k]=ncovcol+k1; # of the kth covariate product: Tvar[5]=ncovcol+1=10 Tvar[6]=ncovcol+1=11
5247: * Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
5248: * 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
5249: * Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
5250: * Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
5251: * V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
5252: * < ncovcol=8 >
5253: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 d1 d1 d2 d2
5254: * k= 1 2 3 4 5 6 7 8 9 10 11 12
5255: * Tvar[k]= 2 1 3 3 10 11 8 8 5 6 7 8
5256: * p Tvar[1]@12={2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5257: * p Tprod[1]@2={ 6, 5}
5258: *p Tvard[1][1]@4= {7, 8, 5, 6}
5259: * covar[k][i]= V2 V1 ? V3 V5*V6? V7*V8? ? V8
5260: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
5261: *How to reorganize?
5262: * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
5263: * Tvars {2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5264: * {2, 1, 4, 8, 5, 6, 3, 7}
5265: * Struct []
5266: */
5267:
1.136 brouard 5268: /* This loop fills the array Tvar from the string 'model'.*/
5269: /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
1.137 brouard 5270: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 */
5271: /* k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
5272: /* k=3 V4 Tvar[k=3]= 4 (from V4) */
5273: /* k=2 V1 Tvar[k=2]= 1 (from V1) */
5274: /* k=1 Tvar[1]=2 (from V2) */
5275: /* k=5 Tvar[5] */
5276: /* for (k=1; k<=cptcovn;k++) { */
5277: /* cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
5278: /* } */
5279: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.145 brouard 5280: /*
5281: * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
5282: for(k=cptcovt; k>=1;k--) /**< Number of covariates */
5283: Tvar[k]=0;
5284: cptcovage=0;
5285: for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
5286: cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+'
5287: modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */
1.137 brouard 5288: if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
1.136 brouard 5289: /* printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
5290: /*scanf("%d",i);*/
1.145 brouard 5291: if (strchr(strb,'*')) { /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
5292: cutl(strc,strd,strb,'*'); /**< strd*strc Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
5293: if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
5294: /* covar is not filled and then is empty */
1.136 brouard 5295: cptcovprod--;
1.145 brouard 5296: cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
5297: Tvar[k]=atoi(stre); /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2 */
1.136 brouard 5298: cptcovage++; /* Sums the number of covariates which include age as a product */
1.137 brouard 5299: Tage[cptcovage]=k; /* Tage[1] = 4 */
1.136 brouard 5300: /*printf("stre=%s ", stre);*/
1.137 brouard 5301: } else if (strcmp(strd,"age")==0) { /* or age*Vn */
1.136 brouard 5302: cptcovprod--;
1.145 brouard 5303: cutl(stre,strb,strc,'V');
1.136 brouard 5304: Tvar[k]=atoi(stre);
5305: cptcovage++;
5306: Tage[cptcovage]=k;
1.137 brouard 5307: } else { /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2 strb=V3*V2*/
5308: /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
1.145 brouard 5309: cptcovn++;
5310: cptcovprodnoage++;k1++;
5311: cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
5312: Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
1.137 brouard 5313: because this model-covariate is a construction we invent a new column
5314: ncovcol + k1
5315: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
5316: Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
1.145 brouard 5317: cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
1.137 brouard 5318: Tprod[k1]=k; /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 */
1.145 brouard 5319: Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
5320: Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
5321: k2=k2+2;
5322: Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
5323: Tvar[cptcovt+k2+1]=Tvard[k1][2]; /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
1.137 brouard 5324: for (i=1; i<=lastobs;i++){
5325: /* Computes the new covariate which is a product of
1.145 brouard 5326: covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
1.136 brouard 5327: covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
1.137 brouard 5328: }
5329: } /* End age is not in the model */
5330: } /* End if model includes a product */
1.136 brouard 5331: else { /* no more sum */
5332: /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
5333: /* scanf("%d",i);*/
1.145 brouard 5334: cutl(strd,strc,strb,'V');
5335: ks++; /**< Number of simple covariates */
5336: cptcovn++;
5337: Tvar[k]=atoi(strd);
1.136 brouard 5338: }
1.137 brouard 5339: strcpy(modelsav,stra); /* modelsav=V2+V1+V4 stra=V2+V1+V4 */
1.136 brouard 5340: /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
5341: scanf("%d",i);*/
5342: } /* end of loop + */
5343: } /* end model */
5344:
5345: /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
5346: If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
5347:
5348: /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
5349: printf("cptcovprod=%d ", cptcovprod);
5350: fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
5351:
5352: scanf("%d ",i);*/
5353:
5354:
1.137 brouard 5355: return (0); /* with covar[new additional covariate if product] and Tage if age */
1.164 brouard 5356: /*endread:*/
1.136 brouard 5357: printf("Exiting decodemodel: ");
5358: return (1);
5359: }
5360:
1.169 brouard 5361: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136 brouard 5362: {
5363: int i, m;
5364:
5365: for (i=1; i<=imx; i++) {
5366: for(m=2; (m<= maxwav); m++) {
5367: if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
5368: anint[m][i]=9999;
5369: s[m][i]=-1;
5370: }
5371: if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169 brouard 5372: *nberr = *nberr + 1;
5373: 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);
5374: 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 5375: s[m][i]=-1;
5376: }
5377: if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169 brouard 5378: (*nberr)++;
1.136 brouard 5379: 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]);
5380: 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]);
5381: s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
5382: }
5383: }
5384: }
5385:
5386: for (i=1; i<=imx; i++) {
5387: agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
5388: for(m=firstpass; (m<= lastpass); m++){
5389: if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
5390: if (s[m][i] >= nlstate+1) {
1.169 brouard 5391: if(agedc[i]>0){
5392: if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136 brouard 5393: agev[m][i]=agedc[i];
5394: /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169 brouard 5395: }else {
1.136 brouard 5396: if ((int)andc[i]!=9999){
5397: nbwarn++;
5398: printf("Warning negative age at death: %ld line:%d\n",num[i],i);
5399: fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
5400: agev[m][i]=-1;
5401: }
5402: }
1.169 brouard 5403: } /* agedc > 0 */
1.136 brouard 5404: }
5405: else if(s[m][i] !=9){ /* Standard case, age in fractional
5406: years but with the precision of a month */
5407: agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
5408: if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
5409: agev[m][i]=1;
5410: else if(agev[m][i] < *agemin){
5411: *agemin=agev[m][i];
5412: printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
5413: }
5414: else if(agev[m][i] >*agemax){
5415: *agemax=agev[m][i];
1.156 brouard 5416: /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136 brouard 5417: }
5418: /*agev[m][i]=anint[m][i]-annais[i];*/
5419: /* agev[m][i] = age[i]+2*m;*/
5420: }
5421: else { /* =9 */
5422: agev[m][i]=1;
5423: s[m][i]=-1;
5424: }
5425: }
5426: else /*= 0 Unknown */
5427: agev[m][i]=1;
5428: }
5429:
5430: }
5431: for (i=1; i<=imx; i++) {
5432: for(m=firstpass; (m<=lastpass); m++){
5433: if (s[m][i] > (nlstate+ndeath)) {
1.169 brouard 5434: (*nberr)++;
1.136 brouard 5435: 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);
5436: 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);
5437: return 1;
5438: }
5439: }
5440: }
5441:
5442: /*for (i=1; i<=imx; i++){
5443: for (m=firstpass; (m<lastpass); m++){
5444: printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
5445: }
5446:
5447: }*/
5448:
5449:
1.139 brouard 5450: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
5451: fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
1.136 brouard 5452:
5453: return (0);
1.164 brouard 5454: /* endread:*/
1.136 brouard 5455: printf("Exiting calandcheckages: ");
5456: return (1);
5457: }
5458:
1.172 brouard 5459: #if defined(_MSC_VER)
5460: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
5461: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
5462: //#include "stdafx.h"
5463: //#include <stdio.h>
5464: //#include <tchar.h>
5465: //#include <windows.h>
5466: //#include <iostream>
5467: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
5468:
5469: LPFN_ISWOW64PROCESS fnIsWow64Process;
5470:
5471: BOOL IsWow64()
5472: {
5473: BOOL bIsWow64 = FALSE;
5474:
5475: //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
5476: // (HANDLE, PBOOL);
5477:
5478: //LPFN_ISWOW64PROCESS fnIsWow64Process;
5479:
5480: HMODULE module = GetModuleHandle(_T("kernel32"));
5481: const char funcName[] = "IsWow64Process";
5482: fnIsWow64Process = (LPFN_ISWOW64PROCESS)
5483: GetProcAddress(module, funcName);
5484:
5485: if (NULL != fnIsWow64Process)
5486: {
5487: if (!fnIsWow64Process(GetCurrentProcess(),
5488: &bIsWow64))
5489: //throw std::exception("Unknown error");
5490: printf("Unknown error\n");
5491: }
5492: return bIsWow64 != FALSE;
5493: }
5494: #endif
1.169 brouard 5495: void syscompilerinfo()
1.167 brouard 5496: {
5497: /* #include "syscompilerinfo.h"*/
1.169 brouard 5498: /* #include <gnu/libc-version.h> */ /* Only on gnu */
1.171 brouard 5499: #include <stdint.h>
1.169 brouard 5500: printf("Compiled with:");fprintf(ficlog,"Compiled with:");
5501: #if defined(__clang__)
5502: printf(" Clang/LLVM");fprintf(ficlog," Clang/LLVM"); /* Clang/LLVM. ---------------------------------------------- */
5503: #endif
5504: #if defined(__ICC) || defined(__INTEL_COMPILER)
5505: printf(" Intel ICC/ICPC");fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
5506: #endif
5507: #if defined(__GNUC__) || defined(__GNUG__)
5508: printf(" GNU GCC/G++");fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
5509: #endif
5510: #if defined(__HP_cc) || defined(__HP_aCC)
5511: printf(" Hewlett-Packard C/aC++");fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
5512: #endif
5513: #if defined(__IBMC__) || defined(__IBMCPP__)
5514: printf(" IBM XL C/C++"); fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
5515: #endif
5516: #if defined(_MSC_VER)
5517: printf(" Microsoft Visual Studio");fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
5518: #endif
5519: #if defined(__PGI)
5520: printf(" Portland Group PGCC/PGCPP");fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
5521: #endif
5522: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
5523: printf(" Oracle Solaris Studio");fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167 brouard 5524: #endif
1.169 brouard 5525: printf(". ");fprintf(ficlog,". ");
5526:
1.167 brouard 5527: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
5528: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
5529: // Windows (x64 and x86)
1.173 ! brouard 5530: printf("Windows (x64 and x86). ");fprintf(ficlog,"Windows (x64 and x86). ");
1.167 brouard 5531: #elif __unix__ // all unices, not all compilers
5532: // Unix
1.173 ! brouard 5533: printf("Unix. ");fprintf(ficlog,"Unix. ");
1.167 brouard 5534: #elif __linux__
5535: // linux
1.173 ! brouard 5536: printf("linux. ");fprintf(ficlog,"linux. ");
1.167 brouard 5537: #elif __APPLE__
5538: // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though...
1.173 ! brouard 5539: printf("Mac OS. ");fprintf(ficlog,"Mac OS. ");
1.167 brouard 5540: #endif
5541:
5542: /* __MINGW32__ */
5543: /* __CYGWIN__ */
5544: /* __MINGW64__ */
5545: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
5546: /* _MSC_VER //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /? */
5547: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
5548: /* _WIN64 // Defined for applications for Win64. */
5549: /* _M_X64 // Defined for compilations that target x64 processors. */
5550: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171 brouard 5551:
1.167 brouard 5552: #if UINTPTR_MAX == 0xffffffff
1.171 brouard 5553: printf(" 32-bit.\n"); fprintf(ficlog," 32-bit.\n");/* 32-bit */
1.167 brouard 5554: #elif UINTPTR_MAX == 0xffffffffffffffff
1.171 brouard 5555: printf(" 64-bit.\n"); fprintf(ficlog," 64-bit.\n");/* 64-bit */
1.167 brouard 5556: #else
1.171 brouard 5557: printf(" wtf-bit.\n"); fprintf(ficlog," wtf-bit.\n");/* wtf */
1.167 brouard 5558: #endif
5559:
1.171 brouard 5560: /* struct utsname sysInfo;
1.167 brouard 5561:
5562: if (uname(&sysInfo) != -1) {
1.169 brouard 5563: printf(" %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
5564: fprintf(ficlog," %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.167 brouard 5565: }
5566: else
5567: perror("uname() error");
1.171 brouard 5568: */
1.169 brouard 5569: #if defined(__GNUC__)
5570: # if defined(__GNUC_PATCHLEVEL__)
5571: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
5572: + __GNUC_MINOR__ * 100 \
5573: + __GNUC_PATCHLEVEL__)
5574: # else
5575: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
5576: + __GNUC_MINOR__ * 100)
5577: # endif
5578: printf("GNU C version %d.\n", __GNUC_VERSION__);
5579: fprintf(ficlog, "GNU C version %d.\n", __GNUC_VERSION__);
5580: #endif
1.172 brouard 5581:
5582: // void main()
5583: // {
1.169 brouard 5584: #if defined(_MSC_VER)
1.172 brouard 5585: if (IsWow64())
5586: printf("The process is running under WOW64.\n");
5587: else
5588: printf("The process is not running under WOW64.\n");
5589:
5590: // printf("\nPress Enter to continue...");
5591: // getchar();
5592: // }
5593:
1.169 brouard 5594: #endif
5595:
5596: /* printf("GNU libc version: %s\n", gnu_get_libc_version()); */
1.167 brouard 5597:
5598: }
1.136 brouard 5599:
5600: /***********************************************/
5601: /**************** Main Program *****************/
5602: /***********************************************/
5603:
5604: int main(int argc, char *argv[])
5605: {
5606: #ifdef GSL
5607: const gsl_multimin_fminimizer_type *T;
5608: size_t iteri = 0, it;
5609: int rval = GSL_CONTINUE;
5610: int status = GSL_SUCCESS;
5611: double ssval;
5612: #endif
5613: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164 brouard 5614: int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
5615:
5616: int jj, ll, li, lj, lk;
1.136 brouard 5617: int numlinepar=0; /* Current linenumber of parameter file */
5618: int itimes;
5619: int NDIM=2;
5620: int vpopbased=0;
5621:
1.164 brouard 5622: char ca[32], cb[32];
1.136 brouard 5623: /* FILE *fichtm; *//* Html File */
5624: /* FILE *ficgp;*/ /*Gnuplot File */
5625: struct stat info;
1.164 brouard 5626: double agedeb;
1.136 brouard 5627: double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
5628:
1.165 brouard 5629: double fret;
1.136 brouard 5630: double dum; /* Dummy variable */
5631: double ***p3mat;
5632: double ***mobaverage;
1.164 brouard 5633:
5634: char line[MAXLINE];
1.136 brouard 5635: char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
5636: char pathr[MAXLINE], pathimach[MAXLINE];
1.164 brouard 5637: char *tok, *val; /* pathtot */
1.136 brouard 5638: int firstobs=1, lastobs=10;
1.164 brouard 5639: int c, h , cpt;
5640: int jl;
5641: int i1, j1, jk, stepsize;
5642: int *tab;
1.136 brouard 5643: int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
5644: int mobilav=0,popforecast=0;
5645: int hstepm, nhstepm;
5646: int agemortsup;
5647: float sumlpop=0.;
5648: double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
5649: double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
5650:
1.164 brouard 5651: double bage=0, fage=110, age, agelim, agebase;
1.136 brouard 5652: double ftolpl=FTOL;
5653: double **prlim;
5654: double ***param; /* Matrix of parameters */
5655: double *p;
5656: double **matcov; /* Matrix of covariance */
5657: double ***delti3; /* Scale */
5658: double *delti; /* Scale */
5659: double ***eij, ***vareij;
5660: double **varpl; /* Variances of prevalence limits by age */
5661: double *epj, vepp;
1.164 brouard 5662:
1.136 brouard 5663: double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
5664: double **ximort;
1.145 brouard 5665: char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136 brouard 5666: int *dcwave;
5667:
1.164 brouard 5668: char z[1]="c";
1.136 brouard 5669:
5670: /*char *strt;*/
5671: char strtend[80];
1.126 brouard 5672:
1.164 brouard 5673:
1.126 brouard 5674: /* setlocale (LC_ALL, ""); */
5675: /* bindtextdomain (PACKAGE, LOCALEDIR); */
5676: /* textdomain (PACKAGE); */
5677: /* setlocale (LC_CTYPE, ""); */
5678: /* setlocale (LC_MESSAGES, ""); */
5679:
5680: /* gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157 brouard 5681: rstart_time = time(NULL);
5682: /* (void) gettimeofday(&start_time,&tzp);*/
5683: start_time = *localtime(&rstart_time);
1.126 brouard 5684: curr_time=start_time;
1.157 brouard 5685: /*tml = *localtime(&start_time.tm_sec);*/
5686: /* strcpy(strstart,asctime(&tml)); */
5687: strcpy(strstart,asctime(&start_time));
1.126 brouard 5688:
5689: /* printf("Localtime (at start)=%s",strstart); */
1.157 brouard 5690: /* tp.tm_sec = tp.tm_sec +86400; */
5691: /* tm = *localtime(&start_time.tm_sec); */
1.126 brouard 5692: /* tmg.tm_year=tmg.tm_year +dsign*dyear; */
5693: /* tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
5694: /* tmg.tm_hour=tmg.tm_hour + 1; */
1.157 brouard 5695: /* tp.tm_sec = mktime(&tmg); */
1.126 brouard 5696: /* strt=asctime(&tmg); */
5697: /* printf("Time(after) =%s",strstart); */
5698: /* (void) time (&time_value);
5699: * printf("time=%d,t-=%d\n",time_value,time_value-86400);
5700: * tm = *localtime(&time_value);
5701: * strstart=asctime(&tm);
5702: * printf("tim_value=%d,asctime=%s\n",time_value,strstart);
5703: */
5704:
5705: nberr=0; /* Number of errors and warnings */
5706: nbwarn=0;
5707: getcwd(pathcd, size);
5708:
5709: printf("\n%s\n%s",version,fullversion);
5710: if(argc <=1){
5711: printf("\nEnter the parameter file name: ");
5712: fgets(pathr,FILENAMELENGTH,stdin);
5713: i=strlen(pathr);
5714: if(pathr[i-1]=='\n')
5715: pathr[i-1]='\0';
1.156 brouard 5716: i=strlen(pathr);
5717: if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
5718: pathr[i-1]='\0';
1.126 brouard 5719: for (tok = pathr; tok != NULL; ){
5720: printf("Pathr |%s|\n",pathr);
5721: while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
5722: printf("val= |%s| pathr=%s\n",val,pathr);
5723: strcpy (pathtot, val);
5724: if(pathr[0] == '\0') break; /* Dirty */
5725: }
5726: }
5727: else{
5728: strcpy(pathtot,argv[1]);
5729: }
5730: /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
5731: /*cygwin_split_path(pathtot,path,optionfile);
5732: printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
5733: /* cutv(path,optionfile,pathtot,'\\');*/
5734:
5735: /* Split argv[0], imach program to get pathimach */
5736: printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
5737: split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
5738: printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
5739: /* strcpy(pathimach,argv[0]); */
5740: /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
5741: split(pathtot,path,optionfile,optionfilext,optionfilefiname);
5742: printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
5743: chdir(path); /* Can be a relative path */
5744: if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
5745: printf("Current directory %s!\n",pathcd);
5746: strcpy(command,"mkdir ");
5747: strcat(command,optionfilefiname);
5748: if((outcmd=system(command)) != 0){
1.169 brouard 5749: printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126 brouard 5750: /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
5751: /* fclose(ficlog); */
5752: /* exit(1); */
5753: }
5754: /* if((imk=mkdir(optionfilefiname))<0){ */
5755: /* perror("mkdir"); */
5756: /* } */
5757:
5758: /*-------- arguments in the command line --------*/
5759:
5760: /* Log file */
5761: strcat(filelog, optionfilefiname);
5762: strcat(filelog,".log"); /* */
5763: if((ficlog=fopen(filelog,"w"))==NULL) {
5764: printf("Problem with logfile %s\n",filelog);
5765: goto end;
5766: }
5767: fprintf(ficlog,"Log filename:%s\n",filelog);
5768: fprintf(ficlog,"\n%s\n%s",version,fullversion);
5769: fprintf(ficlog,"\nEnter the parameter file name: \n");
5770: fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
5771: path=%s \n\
5772: optionfile=%s\n\
5773: optionfilext=%s\n\
1.156 brouard 5774: optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126 brouard 5775:
1.167 brouard 5776: syscompilerinfo();
5777:
1.126 brouard 5778: printf("Local time (at start):%s",strstart);
5779: fprintf(ficlog,"Local time (at start): %s",strstart);
5780: fflush(ficlog);
5781: /* (void) gettimeofday(&curr_time,&tzp); */
1.157 brouard 5782: /* printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126 brouard 5783:
5784: /* */
5785: strcpy(fileres,"r");
5786: strcat(fileres, optionfilefiname);
5787: strcat(fileres,".txt"); /* Other files have txt extension */
5788:
5789: /*---------arguments file --------*/
5790:
5791: if((ficpar=fopen(optionfile,"r"))==NULL) {
1.155 brouard 5792: printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
5793: fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126 brouard 5794: fflush(ficlog);
1.149 brouard 5795: /* goto end; */
5796: exit(70);
1.126 brouard 5797: }
5798:
5799:
5800:
5801: strcpy(filereso,"o");
5802: strcat(filereso,fileres);
5803: if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
5804: printf("Problem with Output resultfile: %s\n", filereso);
5805: fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
5806: fflush(ficlog);
5807: goto end;
5808: }
5809:
5810: /* Reads comments: lines beginning with '#' */
5811: numlinepar=0;
5812: while((c=getc(ficpar))=='#' && c!= EOF){
5813: ungetc(c,ficpar);
5814: fgets(line, MAXLINE, ficpar);
5815: numlinepar++;
1.141 brouard 5816: fputs(line,stdout);
1.126 brouard 5817: fputs(line,ficparo);
5818: fputs(line,ficlog);
5819: }
5820: ungetc(c,ficpar);
5821:
5822: 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);
5823: numlinepar++;
5824: 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);
5825: 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);
5826: 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);
5827: fflush(ficlog);
5828: while((c=getc(ficpar))=='#' && c!= EOF){
5829: ungetc(c,ficpar);
5830: fgets(line, MAXLINE, ficpar);
5831: numlinepar++;
1.141 brouard 5832: fputs(line, stdout);
5833: //puts(line);
1.126 brouard 5834: fputs(line,ficparo);
5835: fputs(line,ficlog);
5836: }
5837: ungetc(c,ficpar);
5838:
5839:
1.145 brouard 5840: covar=matrix(0,NCOVMAX,1,n); /**< used in readdata */
1.136 brouard 5841: cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
5842: /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
5843: v1+v2*age+v2*v3 makes cptcovn = 3
5844: */
5845: if (strlen(model)>1)
1.145 brouard 5846: 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*/
5847: else
5848: ncovmodel=2;
1.126 brouard 5849: nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
1.133 brouard 5850: nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
5851: npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131 brouard 5852: if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
5853: 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);
5854: 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);
5855: fflush(stdout);
5856: fclose (ficlog);
5857: goto end;
5858: }
1.126 brouard 5859: delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5860: delti=delti3[1][1];
5861: /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
5862: if(mle==-1){ /* Print a wizard for help writing covariance matrix */
5863: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
5864: printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
5865: fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
5866: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
5867: fclose (ficparo);
5868: fclose (ficlog);
5869: goto end;
5870: exit(0);
5871: }
5872: else if(mle==-3) {
5873: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
5874: printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
5875: fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
5876: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5877: matcov=matrix(1,npar,1,npar);
5878: }
5879: else{
1.145 brouard 5880: /* Read guessed parameters */
1.126 brouard 5881: /* Reads comments: lines beginning with '#' */
5882: while((c=getc(ficpar))=='#' && c!= EOF){
5883: ungetc(c,ficpar);
5884: fgets(line, MAXLINE, ficpar);
5885: numlinepar++;
1.141 brouard 5886: fputs(line,stdout);
1.126 brouard 5887: fputs(line,ficparo);
5888: fputs(line,ficlog);
5889: }
5890: ungetc(c,ficpar);
5891:
5892: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5893: for(i=1; i <=nlstate; i++){
5894: j=0;
5895: for(jj=1; jj <=nlstate+ndeath; jj++){
5896: if(jj==i) continue;
5897: j++;
5898: fscanf(ficpar,"%1d%1d",&i1,&j1);
5899: if ((i1 != i) && (j1 != j)){
5900: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
5901: It might be a problem of design; if ncovcol and the model are correct\n \
5902: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
5903: exit(1);
5904: }
5905: fprintf(ficparo,"%1d%1d",i1,j1);
5906: if(mle==1)
5907: printf("%1d%1d",i,j);
5908: fprintf(ficlog,"%1d%1d",i,j);
5909: for(k=1; k<=ncovmodel;k++){
5910: fscanf(ficpar," %lf",¶m[i][j][k]);
5911: if(mle==1){
5912: printf(" %lf",param[i][j][k]);
5913: fprintf(ficlog," %lf",param[i][j][k]);
5914: }
5915: else
5916: fprintf(ficlog," %lf",param[i][j][k]);
5917: fprintf(ficparo," %lf",param[i][j][k]);
5918: }
5919: fscanf(ficpar,"\n");
5920: numlinepar++;
5921: if(mle==1)
5922: printf("\n");
5923: fprintf(ficlog,"\n");
5924: fprintf(ficparo,"\n");
5925: }
5926: }
5927: fflush(ficlog);
5928:
1.145 brouard 5929: /* Reads scales values */
1.126 brouard 5930: p=param[1][1];
5931:
5932: /* Reads comments: lines beginning with '#' */
5933: while((c=getc(ficpar))=='#' && c!= EOF){
5934: ungetc(c,ficpar);
5935: fgets(line, MAXLINE, ficpar);
5936: numlinepar++;
1.141 brouard 5937: fputs(line,stdout);
1.126 brouard 5938: fputs(line,ficparo);
5939: fputs(line,ficlog);
5940: }
5941: ungetc(c,ficpar);
5942:
5943: for(i=1; i <=nlstate; i++){
5944: for(j=1; j <=nlstate+ndeath-1; j++){
5945: fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164 brouard 5946: if ( (i1-i) * (j1-j) != 0){
1.126 brouard 5947: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
5948: exit(1);
5949: }
5950: printf("%1d%1d",i,j);
5951: fprintf(ficparo,"%1d%1d",i1,j1);
5952: fprintf(ficlog,"%1d%1d",i1,j1);
5953: for(k=1; k<=ncovmodel;k++){
5954: fscanf(ficpar,"%le",&delti3[i][j][k]);
5955: printf(" %le",delti3[i][j][k]);
5956: fprintf(ficparo," %le",delti3[i][j][k]);
5957: fprintf(ficlog," %le",delti3[i][j][k]);
5958: }
5959: fscanf(ficpar,"\n");
5960: numlinepar++;
5961: printf("\n");
5962: fprintf(ficparo,"\n");
5963: fprintf(ficlog,"\n");
5964: }
5965: }
5966: fflush(ficlog);
5967:
1.145 brouard 5968: /* Reads covariance matrix */
1.126 brouard 5969: delti=delti3[1][1];
5970:
5971:
5972: /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
5973:
5974: /* Reads comments: lines beginning with '#' */
5975: while((c=getc(ficpar))=='#' && c!= EOF){
5976: ungetc(c,ficpar);
5977: fgets(line, MAXLINE, ficpar);
5978: numlinepar++;
1.141 brouard 5979: fputs(line,stdout);
1.126 brouard 5980: fputs(line,ficparo);
5981: fputs(line,ficlog);
5982: }
5983: ungetc(c,ficpar);
5984:
5985: matcov=matrix(1,npar,1,npar);
1.131 brouard 5986: for(i=1; i <=npar; i++)
5987: for(j=1; j <=npar; j++) matcov[i][j]=0.;
5988:
1.126 brouard 5989: for(i=1; i <=npar; i++){
1.145 brouard 5990: fscanf(ficpar,"%s",str);
1.126 brouard 5991: if(mle==1)
5992: printf("%s",str);
5993: fprintf(ficlog,"%s",str);
5994: fprintf(ficparo,"%s",str);
5995: for(j=1; j <=i; j++){
5996: fscanf(ficpar," %le",&matcov[i][j]);
5997: if(mle==1){
5998: printf(" %.5le",matcov[i][j]);
5999: }
6000: fprintf(ficlog," %.5le",matcov[i][j]);
6001: fprintf(ficparo," %.5le",matcov[i][j]);
6002: }
6003: fscanf(ficpar,"\n");
6004: numlinepar++;
6005: if(mle==1)
6006: printf("\n");
6007: fprintf(ficlog,"\n");
6008: fprintf(ficparo,"\n");
6009: }
6010: for(i=1; i <=npar; i++)
6011: for(j=i+1;j<=npar;j++)
6012: matcov[i][j]=matcov[j][i];
6013:
6014: if(mle==1)
6015: printf("\n");
6016: fprintf(ficlog,"\n");
6017:
6018: fflush(ficlog);
6019:
6020: /*-------- Rewriting parameter file ----------*/
6021: strcpy(rfileres,"r"); /* "Rparameterfile */
6022: strcat(rfileres,optionfilefiname); /* Parameter file first name*/
6023: strcat(rfileres,"."); /* */
6024: strcat(rfileres,optionfilext); /* Other files have txt extension */
6025: if((ficres =fopen(rfileres,"w"))==NULL) {
6026: printf("Problem writing new parameter file: %s\n", fileres);goto end;
6027: fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
6028: }
6029: fprintf(ficres,"#%s\n",version);
6030: } /* End of mle != -3 */
6031:
6032:
6033: n= lastobs;
6034: num=lvector(1,n);
6035: moisnais=vector(1,n);
6036: annais=vector(1,n);
6037: moisdc=vector(1,n);
6038: andc=vector(1,n);
6039: agedc=vector(1,n);
6040: cod=ivector(1,n);
6041: weight=vector(1,n);
6042: for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
6043: mint=matrix(1,maxwav,1,n);
6044: anint=matrix(1,maxwav,1,n);
1.131 brouard 6045: s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */
1.126 brouard 6046: tab=ivector(1,NCOVMAX);
1.144 brouard 6047: ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.126 brouard 6048:
1.136 brouard 6049: /* Reads data from file datafile */
6050: if (readdata(datafile, firstobs, lastobs, &imx)==1)
6051: goto end;
6052:
6053: /* Calculation of the number of parameters from char model */
1.137 brouard 6054: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4
6055: k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
6056: k=3 V4 Tvar[k=3]= 4 (from V4)
6057: k=2 V1 Tvar[k=2]= 1 (from V1)
6058: k=1 Tvar[1]=2 (from V2)
6059: */
6060: Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
6061: /* V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs).
6062: For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4,
6063: Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
6064: */
6065: /* For model-covariate k tells which data-covariate to use but
6066: because this model-covariate is a construction we invent a new column
6067: ncovcol + k1
6068: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
6069: Tvar[3=V1*V4]=4+1 etc */
1.145 brouard 6070: Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137 brouard 6071: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
6072: if V2+V1+V1*V4+age*V3+V3*V2 TProd[k1=2]=5 (V3*V2)
6073: */
1.145 brouard 6074: Tvaraff=ivector(1,NCOVMAX); /* Unclear */
6075: 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 6076: * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd.
6077: * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145 brouard 6078: Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137 brouard 6079: 4 covariates (3 plus signs)
6080: Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
6081: */
1.136 brouard 6082:
6083: if(decodemodel(model, lastobs) == 1)
6084: goto end;
6085:
1.137 brouard 6086: if((double)(lastobs-imx)/(double)imx > 1.10){
6087: nbwarn++;
6088: 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);
6089: 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);
6090: }
1.136 brouard 6091: /* if(mle==1){*/
1.137 brouard 6092: if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
6093: for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136 brouard 6094: }
6095:
6096: /*-calculation of age at interview from date of interview and age at death -*/
6097: agev=matrix(1,maxwav,1,imx);
6098:
6099: if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
6100: goto end;
6101:
1.126 brouard 6102:
1.136 brouard 6103: agegomp=(int)agemin;
6104: free_vector(moisnais,1,n);
6105: free_vector(annais,1,n);
1.126 brouard 6106: /* free_matrix(mint,1,maxwav,1,n);
6107: free_matrix(anint,1,maxwav,1,n);*/
6108: free_vector(moisdc,1,n);
6109: free_vector(andc,1,n);
1.145 brouard 6110: /* */
6111:
1.126 brouard 6112: wav=ivector(1,imx);
6113: dh=imatrix(1,lastpass-firstpass+1,1,imx);
6114: bh=imatrix(1,lastpass-firstpass+1,1,imx);
6115: mw=imatrix(1,lastpass-firstpass+1,1,imx);
6116:
6117: /* Concatenates waves */
6118: concatwav(wav, dh, bh, mw, s, agedc, agev, firstpass, lastpass, imx, nlstate, stepm);
1.145 brouard 6119: /* */
6120:
1.126 brouard 6121: /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
6122:
6123: nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
6124: ncodemax[1]=1;
1.145 brouard 6125: Ndum =ivector(-1,NCOVMAX);
6126: if (ncovmodel > 2)
6127: tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
6128:
6129: codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
6130: /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
6131: h=0;
6132:
6133:
6134: /*if (cptcovn > 0) */
1.126 brouard 6135:
1.145 brouard 6136:
1.126 brouard 6137: m=pow(2,cptcoveff);
6138:
1.131 brouard 6139: for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
1.143 brouard 6140: 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 */
6141: for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
6142: 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 6143: h++;
1.141 brouard 6144: if (h>m)
1.136 brouard 6145: h=1;
1.144 brouard 6146: /**< codtab(h,k) k = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.143 brouard 6147: * h 1 2 3 4
6148: *______________________________
6149: * 1 i=1 1 i=1 1 i=1 1 i=1 1
6150: * 2 2 1 1 1
6151: * 3 i=2 1 2 1 1
6152: * 4 2 2 1 1
6153: * 5 i=3 1 i=2 1 2 1
6154: * 6 2 1 2 1
6155: * 7 i=4 1 2 2 1
6156: * 8 2 2 2 1
6157: * 9 i=5 1 i=3 1 i=2 1 1
6158: * 10 2 1 1 1
6159: * 11 i=6 1 2 1 1
6160: * 12 2 2 1 1
6161: * 13 i=7 1 i=4 1 2 1
6162: * 14 2 1 2 1
6163: * 15 i=8 1 2 2 1
6164: * 16 2 2 2 1
6165: */
1.141 brouard 6166: codtab[h][k]=j;
1.145 brouard 6167: /*codtab[h][Tvar[k]]=j;*/
1.130 brouard 6168: 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 6169: }
6170: }
6171: }
6172: }
6173: /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
6174: codtab[1][2]=1;codtab[2][2]=2; */
6175: /* for(i=1; i <=m ;i++){
6176: for(k=1; k <=cptcovn; k++){
1.131 brouard 6177: printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
1.126 brouard 6178: }
6179: printf("\n");
6180: }
6181: scanf("%d",i);*/
1.145 brouard 6182:
6183: free_ivector(Ndum,-1,NCOVMAX);
6184:
6185:
1.126 brouard 6186:
6187: /*------------ gnuplot -------------*/
6188: strcpy(optionfilegnuplot,optionfilefiname);
6189: if(mle==-3)
6190: strcat(optionfilegnuplot,"-mort");
6191: strcat(optionfilegnuplot,".gp");
6192:
6193: if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
6194: printf("Problem with file %s",optionfilegnuplot);
6195: }
6196: else{
6197: fprintf(ficgp,"\n# %s\n", version);
6198: fprintf(ficgp,"# %s\n", optionfilegnuplot);
1.141 brouard 6199: //fprintf(ficgp,"set missing 'NaNq'\n");
6200: fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126 brouard 6201: }
6202: /* fclose(ficgp);*/
6203: /*--------- index.htm --------*/
6204:
6205: strcpy(optionfilehtm,optionfilefiname); /* Main html file */
6206: if(mle==-3)
6207: strcat(optionfilehtm,"-mort");
6208: strcat(optionfilehtm,".htm");
6209: if((fichtm=fopen(optionfilehtm,"w"))==NULL) {
1.131 brouard 6210: printf("Problem with %s \n",optionfilehtm);
6211: exit(0);
1.126 brouard 6212: }
6213:
6214: strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
6215: strcat(optionfilehtmcov,"-cov.htm");
6216: if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL) {
6217: printf("Problem with %s \n",optionfilehtmcov), exit(0);
6218: }
6219: else{
6220: fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6221: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6222: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
6223: optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
6224: }
6225:
6226: fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6227: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6228: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
6229: \n\
6230: <hr size=\"2\" color=\"#EC5E5E\">\
6231: <ul><li><h4>Parameter files</h4>\n\
6232: - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
6233: - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
6234: - Log file of the run: <a href=\"%s\">%s</a><br>\n\
6235: - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
6236: - Date and time at start: %s</ul>\n",\
6237: optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
6238: optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
6239: fileres,fileres,\
6240: filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
6241: fflush(fichtm);
6242:
6243: strcpy(pathr,path);
6244: strcat(pathr,optionfilefiname);
6245: chdir(optionfilefiname); /* Move to directory named optionfile */
6246:
6247: /* Calculates basic frequencies. Computes observed prevalence at single age
6248: and prints on file fileres'p'. */
6249: freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
6250:
6251: fprintf(fichtm,"\n");
6252: fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
6253: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
6254: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
6255: imx,agemin,agemax,jmin,jmax,jmean);
6256: pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6257: oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6258: newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6259: savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6260: oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
6261:
6262:
6263: /* For Powell, parameters are in a vector p[] starting at p[1]
6264: so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
6265: p=param[1][1]; /* *(*(*(param +1)+1)+0) */
6266:
6267: globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
6268:
6269: if (mle==-3){
1.136 brouard 6270: ximort=matrix(1,NDIM,1,NDIM);
6271: /* ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126 brouard 6272: cens=ivector(1,n);
6273: ageexmed=vector(1,n);
6274: agecens=vector(1,n);
6275: dcwave=ivector(1,n);
6276:
6277: for (i=1; i<=imx; i++){
6278: dcwave[i]=-1;
6279: for (m=firstpass; m<=lastpass; m++)
6280: if (s[m][i]>nlstate) {
6281: dcwave[i]=m;
6282: /* printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
6283: break;
6284: }
6285: }
6286:
6287: for (i=1; i<=imx; i++) {
6288: if (wav[i]>0){
6289: ageexmed[i]=agev[mw[1][i]][i];
6290: j=wav[i];
6291: agecens[i]=1.;
6292:
6293: if (ageexmed[i]> 1 && wav[i] > 0){
6294: agecens[i]=agev[mw[j][i]][i];
6295: cens[i]= 1;
6296: }else if (ageexmed[i]< 1)
6297: cens[i]= -1;
6298: if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
6299: cens[i]=0 ;
6300: }
6301: else cens[i]=-1;
6302: }
6303:
6304: for (i=1;i<=NDIM;i++) {
6305: for (j=1;j<=NDIM;j++)
6306: ximort[i][j]=(i == j ? 1.0 : 0.0);
6307: }
6308:
1.145 brouard 6309: /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126 brouard 6310: /*printf("%lf %lf", p[1], p[2]);*/
6311:
6312:
1.136 brouard 6313: #ifdef GSL
6314: printf("GSL optimization\n"); fprintf(ficlog,"Powell\n");
1.162 brouard 6315: #else
1.126 brouard 6316: printf("Powell\n"); fprintf(ficlog,"Powell\n");
1.136 brouard 6317: #endif
1.126 brouard 6318: strcpy(filerespow,"pow-mort");
6319: strcat(filerespow,fileres);
6320: if((ficrespow=fopen(filerespow,"w"))==NULL) {
6321: printf("Problem with resultfile: %s\n", filerespow);
6322: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
6323: }
1.136 brouard 6324: #ifdef GSL
6325: fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162 brouard 6326: #else
1.126 brouard 6327: fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136 brouard 6328: #endif
1.126 brouard 6329: /* for (i=1;i<=nlstate;i++)
6330: for(j=1;j<=nlstate+ndeath;j++)
6331: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
6332: */
6333: fprintf(ficrespow,"\n");
1.136 brouard 6334: #ifdef GSL
6335: /* gsl starts here */
6336: T = gsl_multimin_fminimizer_nmsimplex;
6337: gsl_multimin_fminimizer *sfm = NULL;
6338: gsl_vector *ss, *x;
6339: gsl_multimin_function minex_func;
6340:
6341: /* Initial vertex size vector */
6342: ss = gsl_vector_alloc (NDIM);
6343:
6344: if (ss == NULL){
6345: GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
6346: }
6347: /* Set all step sizes to 1 */
6348: gsl_vector_set_all (ss, 0.001);
6349:
6350: /* Starting point */
1.126 brouard 6351:
1.136 brouard 6352: x = gsl_vector_alloc (NDIM);
6353:
6354: if (x == NULL){
6355: gsl_vector_free(ss);
6356: GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
6357: }
6358:
6359: /* Initialize method and iterate */
6360: /* p[1]=0.0268; p[NDIM]=0.083; */
6361: /* gsl_vector_set(x, 0, 0.0268); */
6362: /* gsl_vector_set(x, 1, 0.083); */
6363: gsl_vector_set(x, 0, p[1]);
6364: gsl_vector_set(x, 1, p[2]);
6365:
6366: minex_func.f = &gompertz_f;
6367: minex_func.n = NDIM;
6368: minex_func.params = (void *)&p; /* ??? */
6369:
6370: sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
6371: gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
6372:
6373: printf("Iterations beginning .....\n\n");
6374: printf("Iter. # Intercept Slope -Log Likelihood Simplex size\n");
6375:
6376: iteri=0;
6377: while (rval == GSL_CONTINUE){
6378: iteri++;
6379: status = gsl_multimin_fminimizer_iterate(sfm);
6380:
6381: if (status) printf("error: %s\n", gsl_strerror (status));
6382: fflush(0);
6383:
6384: if (status)
6385: break;
6386:
6387: rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
6388: ssval = gsl_multimin_fminimizer_size (sfm);
6389:
6390: if (rval == GSL_SUCCESS)
6391: printf ("converged to a local maximum at\n");
6392:
6393: printf("%5d ", iteri);
6394: for (it = 0; it < NDIM; it++){
6395: printf ("%10.5f ", gsl_vector_get (sfm->x, it));
6396: }
6397: printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
6398: }
6399:
6400: printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
6401:
6402: gsl_vector_free(x); /* initial values */
6403: gsl_vector_free(ss); /* inital step size */
6404: for (it=0; it<NDIM; it++){
6405: p[it+1]=gsl_vector_get(sfm->x,it);
6406: fprintf(ficrespow," %.12lf", p[it]);
6407: }
6408: gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1) */
6409: #endif
6410: #ifdef POWELL
6411: powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
6412: #endif
1.126 brouard 6413: fclose(ficrespow);
6414:
6415: hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);
6416:
6417: for(i=1; i <=NDIM; i++)
6418: for(j=i+1;j<=NDIM;j++)
6419: matcov[i][j]=matcov[j][i];
6420:
6421: printf("\nCovariance matrix\n ");
6422: for(i=1; i <=NDIM; i++) {
6423: for(j=1;j<=NDIM;j++){
6424: printf("%f ",matcov[i][j]);
6425: }
6426: printf("\n ");
6427: }
6428:
6429: printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
6430: for (i=1;i<=NDIM;i++)
6431: printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
6432:
6433: lsurv=vector(1,AGESUP);
6434: lpop=vector(1,AGESUP);
6435: tpop=vector(1,AGESUP);
6436: lsurv[agegomp]=100000;
6437:
6438: for (k=agegomp;k<=AGESUP;k++) {
6439: agemortsup=k;
6440: if (p[1]*exp(p[2]*(k-agegomp))>1) break;
6441: }
6442:
6443: for (k=agegomp;k<agemortsup;k++)
6444: lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
6445:
6446: for (k=agegomp;k<agemortsup;k++){
6447: lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
6448: sumlpop=sumlpop+lpop[k];
6449: }
6450:
6451: tpop[agegomp]=sumlpop;
6452: for (k=agegomp;k<(agemortsup-3);k++){
6453: /* tpop[k+1]=2;*/
6454: tpop[k+1]=tpop[k]-lpop[k];
6455: }
6456:
6457:
6458: printf("\nAge lx qx dx Lx Tx e(x)\n");
6459: for (k=agegomp;k<(agemortsup-2);k++)
6460: 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]);
6461:
6462:
6463: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6464: printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6465:
6466: printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
6467: stepm, weightopt,\
6468: model,imx,p,matcov,agemortsup);
6469:
6470: free_vector(lsurv,1,AGESUP);
6471: free_vector(lpop,1,AGESUP);
6472: free_vector(tpop,1,AGESUP);
1.136 brouard 6473: #ifdef GSL
6474: free_ivector(cens,1,n);
6475: free_vector(agecens,1,n);
6476: free_ivector(dcwave,1,n);
6477: free_matrix(ximort,1,NDIM,1,NDIM);
6478: #endif
1.126 brouard 6479: } /* Endof if mle==-3 */
6480:
6481: else{ /* For mle >=1 */
1.132 brouard 6482: globpr=0;/* debug */
6483: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126 brouard 6484: printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6485: for (k=1; k<=npar;k++)
6486: printf(" %d %8.5f",k,p[k]);
6487: printf("\n");
6488: globpr=1; /* to print the contributions */
6489: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
6490: printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6491: for (k=1; k<=npar;k++)
6492: printf(" %d %8.5f",k,p[k]);
6493: printf("\n");
6494: if(mle>=1){ /* Could be 1 or 2 */
6495: mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
6496: }
6497:
6498: /*--------- results files --------------*/
6499: 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);
6500:
6501:
6502: fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6503: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6504: fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6505: for(i=1,jk=1; i <=nlstate; i++){
6506: for(k=1; k <=(nlstate+ndeath); k++){
6507: if (k != i) {
6508: printf("%d%d ",i,k);
6509: fprintf(ficlog,"%d%d ",i,k);
6510: fprintf(ficres,"%1d%1d ",i,k);
6511: for(j=1; j <=ncovmodel; j++){
6512: printf("%lf ",p[jk]);
6513: fprintf(ficlog,"%lf ",p[jk]);
6514: fprintf(ficres,"%lf ",p[jk]);
6515: jk++;
6516: }
6517: printf("\n");
6518: fprintf(ficlog,"\n");
6519: fprintf(ficres,"\n");
6520: }
6521: }
6522: }
6523: if(mle!=0){
6524: /* Computing hessian and covariance matrix */
6525: ftolhess=ftol; /* Usually correct */
6526: hesscov(matcov, p, npar, delti, ftolhess, func);
6527: }
6528: fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
6529: printf("# Scales (for hessian or gradient estimation)\n");
6530: fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
6531: for(i=1,jk=1; i <=nlstate; i++){
6532: for(j=1; j <=nlstate+ndeath; j++){
6533: if (j!=i) {
6534: fprintf(ficres,"%1d%1d",i,j);
6535: printf("%1d%1d",i,j);
6536: fprintf(ficlog,"%1d%1d",i,j);
6537: for(k=1; k<=ncovmodel;k++){
6538: printf(" %.5e",delti[jk]);
6539: fprintf(ficlog," %.5e",delti[jk]);
6540: fprintf(ficres," %.5e",delti[jk]);
6541: jk++;
6542: }
6543: printf("\n");
6544: fprintf(ficlog,"\n");
6545: fprintf(ficres,"\n");
6546: }
6547: }
6548: }
6549:
6550: 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");
6551: if(mle>=1)
6552: 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");
6553: 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");
6554: /* # 121 Var(a12)\n\ */
6555: /* # 122 Cov(b12,a12) Var(b12)\n\ */
6556: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
6557: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
6558: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
6559: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
6560: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
6561: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
6562:
6563:
6564: /* Just to have a covariance matrix which will be more understandable
6565: even is we still don't want to manage dictionary of variables
6566: */
6567: for(itimes=1;itimes<=2;itimes++){
6568: jj=0;
6569: for(i=1; i <=nlstate; i++){
6570: for(j=1; j <=nlstate+ndeath; j++){
6571: if(j==i) continue;
6572: for(k=1; k<=ncovmodel;k++){
6573: jj++;
6574: ca[0]= k+'a'-1;ca[1]='\0';
6575: if(itimes==1){
6576: if(mle>=1)
6577: printf("#%1d%1d%d",i,j,k);
6578: fprintf(ficlog,"#%1d%1d%d",i,j,k);
6579: fprintf(ficres,"#%1d%1d%d",i,j,k);
6580: }else{
6581: if(mle>=1)
6582: printf("%1d%1d%d",i,j,k);
6583: fprintf(ficlog,"%1d%1d%d",i,j,k);
6584: fprintf(ficres,"%1d%1d%d",i,j,k);
6585: }
6586: ll=0;
6587: for(li=1;li <=nlstate; li++){
6588: for(lj=1;lj <=nlstate+ndeath; lj++){
6589: if(lj==li) continue;
6590: for(lk=1;lk<=ncovmodel;lk++){
6591: ll++;
6592: if(ll<=jj){
6593: cb[0]= lk +'a'-1;cb[1]='\0';
6594: if(ll<jj){
6595: if(itimes==1){
6596: if(mle>=1)
6597: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6598: fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6599: fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6600: }else{
6601: if(mle>=1)
6602: printf(" %.5e",matcov[jj][ll]);
6603: fprintf(ficlog," %.5e",matcov[jj][ll]);
6604: fprintf(ficres," %.5e",matcov[jj][ll]);
6605: }
6606: }else{
6607: if(itimes==1){
6608: if(mle>=1)
6609: printf(" Var(%s%1d%1d)",ca,i,j);
6610: fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
6611: fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
6612: }else{
6613: if(mle>=1)
6614: printf(" %.5e",matcov[jj][ll]);
6615: fprintf(ficlog," %.5e",matcov[jj][ll]);
6616: fprintf(ficres," %.5e",matcov[jj][ll]);
6617: }
6618: }
6619: }
6620: } /* end lk */
6621: } /* end lj */
6622: } /* end li */
6623: if(mle>=1)
6624: printf("\n");
6625: fprintf(ficlog,"\n");
6626: fprintf(ficres,"\n");
6627: numlinepar++;
6628: } /* end k*/
6629: } /*end j */
6630: } /* end i */
6631: } /* end itimes */
6632:
6633: fflush(ficlog);
6634: fflush(ficres);
6635:
6636: while((c=getc(ficpar))=='#' && c!= EOF){
6637: ungetc(c,ficpar);
6638: fgets(line, MAXLINE, ficpar);
1.141 brouard 6639: fputs(line,stdout);
1.126 brouard 6640: fputs(line,ficparo);
6641: }
6642: ungetc(c,ficpar);
6643:
6644: estepm=0;
6645: fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
6646: if (estepm==0 || estepm < stepm) estepm=stepm;
6647: if (fage <= 2) {
6648: bage = ageminpar;
6649: fage = agemaxpar;
6650: }
6651:
6652: fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
6653: fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6654: fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6655:
6656: while((c=getc(ficpar))=='#' && c!= EOF){
6657: ungetc(c,ficpar);
6658: fgets(line, MAXLINE, ficpar);
1.141 brouard 6659: fputs(line,stdout);
1.126 brouard 6660: fputs(line,ficparo);
6661: }
6662: ungetc(c,ficpar);
6663:
6664: 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);
6665: 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);
6666: 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);
6667: printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
6668: 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);
6669:
6670: while((c=getc(ficpar))=='#' && c!= EOF){
6671: ungetc(c,ficpar);
6672: fgets(line, MAXLINE, ficpar);
1.141 brouard 6673: fputs(line,stdout);
1.126 brouard 6674: fputs(line,ficparo);
6675: }
6676: ungetc(c,ficpar);
6677:
6678:
6679: dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
6680: dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
6681:
6682: fscanf(ficpar,"pop_based=%d\n",&popbased);
6683: fprintf(ficparo,"pop_based=%d\n",popbased);
6684: fprintf(ficres,"pop_based=%d\n",popbased);
6685:
6686: while((c=getc(ficpar))=='#' && c!= EOF){
6687: ungetc(c,ficpar);
6688: fgets(line, MAXLINE, ficpar);
1.141 brouard 6689: fputs(line,stdout);
1.126 brouard 6690: fputs(line,ficparo);
6691: }
6692: ungetc(c,ficpar);
6693:
6694: 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);
6695: 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);
6696: 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);
6697: 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);
6698: 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);
6699: /* day and month of proj2 are not used but only year anproj2.*/
6700:
6701:
6702:
1.145 brouard 6703: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
6704: /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126 brouard 6705:
6706: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6707: printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6708:
6709: printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
6710: model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
6711: jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
6712:
6713: /*------------ free_vector -------------*/
6714: /* chdir(path); */
6715:
6716: free_ivector(wav,1,imx);
6717: free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
6718: free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
6719: free_imatrix(mw,1,lastpass-firstpass+1,1,imx);
6720: free_lvector(num,1,n);
6721: free_vector(agedc,1,n);
6722: /*free_matrix(covar,0,NCOVMAX,1,n);*/
6723: /*free_matrix(covar,1,NCOVMAX,1,n);*/
6724: fclose(ficparo);
6725: fclose(ficres);
6726:
6727:
6728: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
1.145 brouard 6729: #include "prevlim.h" /* Use ficrespl, ficlog */
1.126 brouard 6730: fclose(ficrespl);
6731:
1.145 brouard 6732: #ifdef FREEEXIT2
6733: #include "freeexit2.h"
6734: #endif
6735:
1.126 brouard 6736: /*------------- h Pij x at various ages ------------*/
1.145 brouard 6737: #include "hpijx.h"
6738: fclose(ficrespij);
1.126 brouard 6739:
1.145 brouard 6740: /*-------------- Variance of one-step probabilities---*/
6741: k=1;
1.126 brouard 6742: varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
6743:
6744:
6745: probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
6746: for(i=1;i<=AGESUP;i++)
6747: for(j=1;j<=NCOVMAX;j++)
6748: for(k=1;k<=NCOVMAX;k++)
6749: probs[i][j][k]=0.;
6750:
6751: /*---------- Forecasting ------------------*/
6752: /*if((stepm == 1) && (strcmp(model,".")==0)){*/
6753: if(prevfcast==1){
6754: /* if(stepm ==1){*/
6755: prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
6756: /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
6757: /* } */
6758: /* else{ */
6759: /* erreur=108; */
6760: /* 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); */
6761: /* 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); */
6762: /* } */
6763: }
6764:
6765:
1.127 brouard 6766: /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
6767:
6768: prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
6769: /* 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",\
6770: ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
6771: */
1.126 brouard 6772:
1.127 brouard 6773: if (mobilav!=0) {
6774: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
6775: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
6776: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
6777: printf(" Error in movingaverage mobilav=%d\n",mobilav);
6778: }
1.126 brouard 6779: }
6780:
6781:
1.127 brouard 6782: /*---------- Health expectancies, no variances ------------*/
6783:
1.126 brouard 6784: strcpy(filerese,"e");
6785: strcat(filerese,fileres);
6786: if((ficreseij=fopen(filerese,"w"))==NULL) {
6787: printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
6788: fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
6789: }
6790: printf("Computing Health Expectancies: result on file '%s' \n", filerese);
6791: fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
1.145 brouard 6792: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6793: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6794:
6795: for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127 brouard 6796: fprintf(ficreseij,"\n#****** ");
6797: for(j=1;j<=cptcoveff;j++) {
6798: fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6799: }
6800: fprintf(ficreseij,"******\n");
6801:
6802: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6803: oldm=oldms;savm=savms;
6804: evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);
6805:
6806: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145 brouard 6807: /*}*/
1.127 brouard 6808: }
6809: fclose(ficreseij);
6810:
6811:
6812: /*---------- Health expectancies and variances ------------*/
6813:
6814:
6815: strcpy(filerest,"t");
6816: strcat(filerest,fileres);
6817: if((ficrest=fopen(filerest,"w"))==NULL) {
6818: printf("Problem with total LE resultfile: %s\n", filerest);goto end;
6819: fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
6820: }
6821: printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
6822: fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
6823:
1.126 brouard 6824:
6825: strcpy(fileresstde,"stde");
6826: strcat(fileresstde,fileres);
6827: if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
6828: printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
6829: fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
6830: }
6831: printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
6832: fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
6833:
6834: strcpy(filerescve,"cve");
6835: strcat(filerescve,fileres);
6836: if((ficrescveij=fopen(filerescve,"w"))==NULL) {
6837: printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
6838: fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
6839: }
6840: printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
6841: fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
6842:
6843: strcpy(fileresv,"v");
6844: strcat(fileresv,fileres);
6845: if((ficresvij=fopen(fileresv,"w"))==NULL) {
6846: printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
6847: fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
6848: }
6849: printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
6850: fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
6851:
1.145 brouard 6852: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6853: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6854:
6855: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6856: fprintf(ficrest,"\n#****** ");
1.126 brouard 6857: for(j=1;j<=cptcoveff;j++)
6858: fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6859: fprintf(ficrest,"******\n");
6860:
6861: fprintf(ficresstdeij,"\n#****** ");
6862: fprintf(ficrescveij,"\n#****** ");
6863: for(j=1;j<=cptcoveff;j++) {
6864: fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6865: fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6866: }
6867: fprintf(ficresstdeij,"******\n");
6868: fprintf(ficrescveij,"******\n");
6869:
6870: fprintf(ficresvij,"\n#****** ");
6871: for(j=1;j<=cptcoveff;j++)
6872: fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6873: fprintf(ficresvij,"******\n");
6874:
6875: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6876: oldm=oldms;savm=savms;
1.127 brouard 6877: cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
1.145 brouard 6878: /*
6879: */
6880: /* goto endfree; */
1.126 brouard 6881:
6882: vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6883: pstamp(ficrest);
1.145 brouard 6884:
6885:
1.128 brouard 6886: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.145 brouard 6887: oldm=oldms;savm=savms; /* Segmentation fault */
1.161 brouard 6888: cptcod= 0; /* To be deleted */
6889: 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 6890: 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 6891: if(vpopbased==1)
6892: 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);
6893: else
6894: fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
6895: fprintf(ficrest,"# Age e.. (std) ");
6896: for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
6897: fprintf(ficrest,"\n");
1.126 brouard 6898:
1.128 brouard 6899: epj=vector(1,nlstate+1);
6900: for(age=bage; age <=fage ;age++){
6901: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
6902: if (vpopbased==1) {
6903: if(mobilav ==0){
6904: for(i=1; i<=nlstate;i++)
6905: prlim[i][i]=probs[(int)age][i][k];
6906: }else{ /* mobilav */
6907: for(i=1; i<=nlstate;i++)
6908: prlim[i][i]=mobaverage[(int)age][i][k];
6909: }
1.126 brouard 6910: }
6911:
1.128 brouard 6912: fprintf(ficrest," %4.0f",age);
6913: for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
6914: for(i=1, epj[j]=0.;i <=nlstate;i++) {
6915: epj[j] += prlim[i][i]*eij[i][j][(int)age];
6916: /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
6917: }
6918: epj[nlstate+1] +=epj[j];
1.126 brouard 6919: }
6920:
1.128 brouard 6921: for(i=1, vepp=0.;i <=nlstate;i++)
6922: for(j=1;j <=nlstate;j++)
6923: vepp += vareij[i][j][(int)age];
6924: fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
6925: for(j=1;j <=nlstate;j++){
6926: fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
6927: }
6928: fprintf(ficrest,"\n");
1.126 brouard 6929: }
6930: }
6931: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
6932: free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
6933: free_vector(epj,1,nlstate+1);
1.145 brouard 6934: /*}*/
1.126 brouard 6935: }
6936: free_vector(weight,1,n);
1.145 brouard 6937: free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126 brouard 6938: free_imatrix(s,1,maxwav+1,1,n);
6939: free_matrix(anint,1,maxwav,1,n);
6940: free_matrix(mint,1,maxwav,1,n);
6941: free_ivector(cod,1,n);
6942: free_ivector(tab,1,NCOVMAX);
6943: fclose(ficresstdeij);
6944: fclose(ficrescveij);
6945: fclose(ficresvij);
6946: fclose(ficrest);
6947: fclose(ficpar);
6948:
6949: /*------- Variance of period (stable) prevalence------*/
6950:
6951: strcpy(fileresvpl,"vpl");
6952: strcat(fileresvpl,fileres);
6953: if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
6954: printf("Problem with variance of period (stable) prevalence resultfile: %s\n", fileresvpl);
6955: exit(0);
6956: }
6957: printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
6958:
1.145 brouard 6959: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6960: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6961:
6962: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6963: fprintf(ficresvpl,"\n#****** ");
1.126 brouard 6964: for(j=1;j<=cptcoveff;j++)
6965: fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6966: fprintf(ficresvpl,"******\n");
6967:
6968: varpl=matrix(1,nlstate,(int) bage, (int) fage);
6969: oldm=oldms;savm=savms;
6970: varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
6971: free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145 brouard 6972: /*}*/
1.126 brouard 6973: }
6974:
6975: fclose(ficresvpl);
6976:
6977: /*---------- End : free ----------------*/
6978: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
6979: free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
6980: } /* mle==-3 arrives here for freeing */
1.164 brouard 6981: /* endfree:*/
1.141 brouard 6982: free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126 brouard 6983: free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
6984: free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
6985: free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
6986: free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
6987: free_matrix(covar,0,NCOVMAX,1,n);
6988: free_matrix(matcov,1,npar,1,npar);
6989: /*free_vector(delti,1,npar);*/
6990: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
6991: free_matrix(agev,1,maxwav,1,imx);
6992: free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
6993:
1.145 brouard 6994: free_ivector(ncodemax,1,NCOVMAX);
6995: free_ivector(Tvar,1,NCOVMAX);
6996: free_ivector(Tprod,1,NCOVMAX);
6997: free_ivector(Tvaraff,1,NCOVMAX);
6998: free_ivector(Tage,1,NCOVMAX);
1.126 brouard 6999:
7000: free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
7001: free_imatrix(codtab,1,100,1,10);
7002: fflush(fichtm);
7003: fflush(ficgp);
7004:
7005:
7006: if((nberr >0) || (nbwarn>0)){
7007: printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
7008: fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
7009: }else{
7010: printf("End of Imach\n");
7011: fprintf(ficlog,"End of Imach\n");
7012: }
7013: printf("See log file on %s\n",filelog);
7014: /* gettimeofday(&end_time, (struct timezone*)0);*/ /* after time */
1.157 brouard 7015: /*(void) gettimeofday(&end_time,&tzp);*/
7016: rend_time = time(NULL);
7017: end_time = *localtime(&rend_time);
7018: /* tml = *localtime(&end_time.tm_sec); */
7019: strcpy(strtend,asctime(&end_time));
1.126 brouard 7020: printf("Local time at start %s\nLocal time at end %s",strstart, strtend);
7021: fprintf(ficlog,"Local time at start %s\nLocal time at end %s\n",strstart, strtend);
1.157 brouard 7022: printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126 brouard 7023:
1.157 brouard 7024: printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
7025: fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
7026: fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126 brouard 7027: /* printf("Total time was %d uSec.\n", total_usecs);*/
7028: /* if(fileappend(fichtm,optionfilehtm)){ */
7029: fprintf(fichtm,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
7030: fclose(fichtm);
7031: fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
7032: fclose(fichtmcov);
7033: fclose(ficgp);
7034: fclose(ficlog);
7035: /*------ End -----------*/
7036:
7037:
7038: printf("Before Current directory %s!\n",pathcd);
7039: if(chdir(pathcd) != 0)
7040: printf("Can't move to directory %s!\n",path);
7041: if(getcwd(pathcd,MAXLINE) > 0)
7042: printf("Current directory %s!\n",pathcd);
7043: /*strcat(plotcmd,CHARSEPARATOR);*/
7044: sprintf(plotcmd,"gnuplot");
1.157 brouard 7045: #ifdef _WIN32
1.126 brouard 7046: sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
7047: #endif
7048: if(!stat(plotcmd,&info)){
1.158 brouard 7049: printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 7050: if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158 brouard 7051: printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126 brouard 7052: }else
7053: strcpy(pplotcmd,plotcmd);
1.157 brouard 7054: #ifdef __unix
1.126 brouard 7055: strcpy(plotcmd,GNUPLOTPROGRAM);
7056: if(!stat(plotcmd,&info)){
1.158 brouard 7057: printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 7058: }else
7059: strcpy(pplotcmd,plotcmd);
7060: #endif
7061: }else
7062: strcpy(pplotcmd,plotcmd);
7063:
7064: sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158 brouard 7065: printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 7066:
7067: if((outcmd=system(plotcmd)) != 0){
1.158 brouard 7068: printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154 brouard 7069: printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152 brouard 7070: sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150 brouard 7071: if((outcmd=system(plotcmd)) != 0)
1.153 brouard 7072: printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126 brouard 7073: }
1.158 brouard 7074: printf(" Successful, please wait...");
1.126 brouard 7075: while (z[0] != 'q') {
7076: /* chdir(path); */
1.154 brouard 7077: printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126 brouard 7078: scanf("%s",z);
7079: /* if (z[0] == 'c') system("./imach"); */
7080: if (z[0] == 'e') {
1.158 brouard 7081: #ifdef __APPLE__
1.152 brouard 7082: sprintf(pplotcmd, "open %s", optionfilehtm);
1.157 brouard 7083: #elif __linux
7084: sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153 brouard 7085: #else
1.152 brouard 7086: sprintf(pplotcmd, "%s", optionfilehtm);
1.153 brouard 7087: #endif
7088: printf("Starting browser with: %s",pplotcmd);fflush(stdout);
7089: system(pplotcmd);
1.126 brouard 7090: }
7091: else if (z[0] == 'g') system(plotcmd);
7092: else if (z[0] == 'q') exit(0);
7093: }
7094: end:
7095: while (z[0] != 'q') {
7096: printf("\nType q for exiting: ");
7097: scanf("%s",z);
7098: }
7099: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>