Annotation of imach/src/imach.c, revision 1.165
1.165 ! brouard 1: /* $Id: imach.c,v 1.164 2014/12/16 10:52:11 brouard Exp $
1.126 brouard 2: $State: Exp $
1.163 brouard 3: $Log: imach.c,v $
1.165 ! brouard 4: Revision 1.164 2014/12/16 10:52:11 brouard
! 5: Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
! 6:
! 7: * imach.c (Module): Merging 1.61 to 1.162
! 8:
1.164 brouard 9: Revision 1.163 2014/12/16 10:30:11 brouard
10: * imach.c (Module): Merging 1.61 to 1.162
11:
1.163 brouard 12: Revision 1.162 2014/09/25 11:43:39 brouard
13: Summary: temporary backup 0.99!
14:
1.162 brouard 15: Revision 1.1 2014/09/16 11:06:58 brouard
16: Summary: With some code (wrong) for nlopt
17:
18: Author:
19:
20: Revision 1.161 2014/09/15 20:41:41 brouard
21: Summary: Problem with macro SQR on Intel compiler
22:
1.161 brouard 23: Revision 1.160 2014/09/02 09:24:05 brouard
24: *** empty log message ***
25:
1.160 brouard 26: Revision 1.159 2014/09/01 10:34:10 brouard
27: Summary: WIN32
28: Author: Brouard
29:
1.159 brouard 30: Revision 1.158 2014/08/27 17:11:51 brouard
31: *** empty log message ***
32:
1.158 brouard 33: Revision 1.157 2014/08/27 16:26:55 brouard
34: Summary: Preparing windows Visual studio version
35: Author: Brouard
36:
37: In order to compile on Visual studio, time.h is now correct and time_t
38: and tm struct should be used. difftime should be used but sometimes I
39: just make the differences in raw time format (time(&now).
40: Trying to suppress #ifdef LINUX
41: Add xdg-open for __linux in order to open default browser.
42:
1.157 brouard 43: Revision 1.156 2014/08/25 20:10:10 brouard
44: *** empty log message ***
45:
1.156 brouard 46: Revision 1.155 2014/08/25 18:32:34 brouard
47: Summary: New compile, minor changes
48: Author: Brouard
49:
1.155 brouard 50: Revision 1.154 2014/06/20 17:32:08 brouard
51: Summary: Outputs now all graphs of convergence to period prevalence
52:
1.154 brouard 53: Revision 1.153 2014/06/20 16:45:46 brouard
54: Summary: If 3 live state, convergence to period prevalence on same graph
55: Author: Brouard
56:
1.153 brouard 57: Revision 1.152 2014/06/18 17:54:09 brouard
58: Summary: open browser, use gnuplot on same dir than imach if not found in the path
59:
1.152 brouard 60: Revision 1.151 2014/06/18 16:43:30 brouard
61: *** empty log message ***
62:
1.151 brouard 63: Revision 1.150 2014/06/18 16:42:35 brouard
64: Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
65: Author: brouard
66:
1.150 brouard 67: Revision 1.149 2014/06/18 15:51:14 brouard
68: Summary: Some fixes in parameter files errors
69: Author: Nicolas Brouard
70:
1.149 brouard 71: Revision 1.148 2014/06/17 17:38:48 brouard
72: Summary: Nothing new
73: Author: Brouard
74:
75: Just a new packaging for OS/X version 0.98nS
76:
1.148 brouard 77: Revision 1.147 2014/06/16 10:33:11 brouard
78: *** empty log message ***
79:
1.147 brouard 80: Revision 1.146 2014/06/16 10:20:28 brouard
81: Summary: Merge
82: Author: Brouard
83:
84: Merge, before building revised version.
85:
1.146 brouard 86: Revision 1.145 2014/06/10 21:23:15 brouard
87: Summary: Debugging with valgrind
88: Author: Nicolas Brouard
89:
90: Lot of changes in order to output the results with some covariates
91: After the Edimburgh REVES conference 2014, it seems mandatory to
92: improve the code.
93: No more memory valgrind error but a lot has to be done in order to
94: continue the work of splitting the code into subroutines.
95: Also, decodemodel has been improved. Tricode is still not
96: optimal. nbcode should be improved. Documentation has been added in
97: the source code.
98:
1.144 brouard 99: Revision 1.143 2014/01/26 09:45:38 brouard
100: Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
101:
102: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
103: (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
104:
1.143 brouard 105: Revision 1.142 2014/01/26 03:57:36 brouard
106: Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
107:
108: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
109:
1.142 brouard 110: Revision 1.141 2014/01/26 02:42:01 brouard
111: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
112:
1.141 brouard 113: Revision 1.140 2011/09/02 10:37:54 brouard
114: Summary: times.h is ok with mingw32 now.
115:
1.140 brouard 116: Revision 1.139 2010/06/14 07:50:17 brouard
117: After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
118: I remember having already fixed agemin agemax which are pointers now but not cvs saved.
119:
1.139 brouard 120: Revision 1.138 2010/04/30 18:19:40 brouard
121: *** empty log message ***
122:
1.138 brouard 123: Revision 1.137 2010/04/29 18:11:38 brouard
124: (Module): Checking covariates for more complex models
125: than V1+V2. A lot of change to be done. Unstable.
126:
1.137 brouard 127: Revision 1.136 2010/04/26 20:30:53 brouard
128: (Module): merging some libgsl code. Fixing computation
129: of likelione (using inter/intrapolation if mle = 0) in order to
130: get same likelihood as if mle=1.
131: Some cleaning of code and comments added.
132:
1.136 brouard 133: Revision 1.135 2009/10/29 15:33:14 brouard
134: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
135:
1.135 brouard 136: Revision 1.134 2009/10/29 13:18:53 brouard
137: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
138:
1.134 brouard 139: Revision 1.133 2009/07/06 10:21:25 brouard
140: just nforces
141:
1.133 brouard 142: Revision 1.132 2009/07/06 08:22:05 brouard
143: Many tings
144:
1.132 brouard 145: Revision 1.131 2009/06/20 16:22:47 brouard
146: Some dimensions resccaled
147:
1.131 brouard 148: Revision 1.130 2009/05/26 06:44:34 brouard
149: (Module): Max Covariate is now set to 20 instead of 8. A
150: lot of cleaning with variables initialized to 0. Trying to make
151: V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
152:
1.130 brouard 153: Revision 1.129 2007/08/31 13:49:27 lievre
154: Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
155:
1.129 lievre 156: Revision 1.128 2006/06/30 13:02:05 brouard
157: (Module): Clarifications on computing e.j
158:
1.128 brouard 159: Revision 1.127 2006/04/28 18:11:50 brouard
160: (Module): Yes the sum of survivors was wrong since
161: imach-114 because nhstepm was no more computed in the age
162: loop. Now we define nhstepma in the age loop.
163: (Module): In order to speed up (in case of numerous covariates) we
164: compute health expectancies (without variances) in a first step
165: and then all the health expectancies with variances or standard
166: deviation (needs data from the Hessian matrices) which slows the
167: computation.
168: In the future we should be able to stop the program is only health
169: expectancies and graph are needed without standard deviations.
170:
1.127 brouard 171: Revision 1.126 2006/04/28 17:23:28 brouard
172: (Module): Yes the sum of survivors was wrong since
173: imach-114 because nhstepm was no more computed in the age
174: loop. Now we define nhstepma in the age loop.
175: Version 0.98h
176:
1.126 brouard 177: Revision 1.125 2006/04/04 15:20:31 lievre
178: Errors in calculation of health expectancies. Age was not initialized.
179: Forecasting file added.
180:
181: Revision 1.124 2006/03/22 17:13:53 lievre
182: Parameters are printed with %lf instead of %f (more numbers after the comma).
183: The log-likelihood is printed in the log file
184:
185: Revision 1.123 2006/03/20 10:52:43 brouard
186: * imach.c (Module): <title> changed, corresponds to .htm file
187: name. <head> headers where missing.
188:
189: * imach.c (Module): Weights can have a decimal point as for
190: English (a comma might work with a correct LC_NUMERIC environment,
191: otherwise the weight is truncated).
192: Modification of warning when the covariates values are not 0 or
193: 1.
194: Version 0.98g
195:
196: Revision 1.122 2006/03/20 09:45:41 brouard
197: (Module): Weights can have a decimal point as for
198: English (a comma might work with a correct LC_NUMERIC environment,
199: otherwise the weight is truncated).
200: Modification of warning when the covariates values are not 0 or
201: 1.
202: Version 0.98g
203:
204: Revision 1.121 2006/03/16 17:45:01 lievre
205: * imach.c (Module): Comments concerning covariates added
206:
207: * imach.c (Module): refinements in the computation of lli if
208: status=-2 in order to have more reliable computation if stepm is
209: not 1 month. Version 0.98f
210:
211: Revision 1.120 2006/03/16 15:10:38 lievre
212: (Module): refinements in the computation of lli if
213: status=-2 in order to have more reliable computation if stepm is
214: not 1 month. Version 0.98f
215:
216: Revision 1.119 2006/03/15 17:42:26 brouard
217: (Module): Bug if status = -2, the loglikelihood was
218: computed as likelihood omitting the logarithm. Version O.98e
219:
220: Revision 1.118 2006/03/14 18:20:07 brouard
221: (Module): varevsij Comments added explaining the second
222: table of variances if popbased=1 .
223: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
224: (Module): Function pstamp added
225: (Module): Version 0.98d
226:
227: Revision 1.117 2006/03/14 17:16:22 brouard
228: (Module): varevsij Comments added explaining the second
229: table of variances if popbased=1 .
230: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
231: (Module): Function pstamp added
232: (Module): Version 0.98d
233:
234: Revision 1.116 2006/03/06 10:29:27 brouard
235: (Module): Variance-covariance wrong links and
236: varian-covariance of ej. is needed (Saito).
237:
238: Revision 1.115 2006/02/27 12:17:45 brouard
239: (Module): One freematrix added in mlikeli! 0.98c
240:
241: Revision 1.114 2006/02/26 12:57:58 brouard
242: (Module): Some improvements in processing parameter
243: filename with strsep.
244:
245: Revision 1.113 2006/02/24 14:20:24 brouard
246: (Module): Memory leaks checks with valgrind and:
247: datafile was not closed, some imatrix were not freed and on matrix
248: allocation too.
249:
250: Revision 1.112 2006/01/30 09:55:26 brouard
251: (Module): Back to gnuplot.exe instead of wgnuplot.exe
252:
253: Revision 1.111 2006/01/25 20:38:18 brouard
254: (Module): Lots of cleaning and bugs added (Gompertz)
255: (Module): Comments can be added in data file. Missing date values
256: can be a simple dot '.'.
257:
258: Revision 1.110 2006/01/25 00:51:50 brouard
259: (Module): Lots of cleaning and bugs added (Gompertz)
260:
261: Revision 1.109 2006/01/24 19:37:15 brouard
262: (Module): Comments (lines starting with a #) are allowed in data.
263:
264: Revision 1.108 2006/01/19 18:05:42 lievre
265: Gnuplot problem appeared...
266: To be fixed
267:
268: Revision 1.107 2006/01/19 16:20:37 brouard
269: Test existence of gnuplot in imach path
270:
271: Revision 1.106 2006/01/19 13:24:36 brouard
272: Some cleaning and links added in html output
273:
274: Revision 1.105 2006/01/05 20:23:19 lievre
275: *** empty log message ***
276:
277: Revision 1.104 2005/09/30 16:11:43 lievre
278: (Module): sump fixed, loop imx fixed, and simplifications.
279: (Module): If the status is missing at the last wave but we know
280: that the person is alive, then we can code his/her status as -2
281: (instead of missing=-1 in earlier versions) and his/her
282: contributions to the likelihood is 1 - Prob of dying from last
283: health status (= 1-p13= p11+p12 in the easiest case of somebody in
284: the healthy state at last known wave). Version is 0.98
285:
286: Revision 1.103 2005/09/30 15:54:49 lievre
287: (Module): sump fixed, loop imx fixed, and simplifications.
288:
289: Revision 1.102 2004/09/15 17:31:30 brouard
290: Add the possibility to read data file including tab characters.
291:
292: Revision 1.101 2004/09/15 10:38:38 brouard
293: Fix on curr_time
294:
295: Revision 1.100 2004/07/12 18:29:06 brouard
296: Add version for Mac OS X. Just define UNIX in Makefile
297:
298: Revision 1.99 2004/06/05 08:57:40 brouard
299: *** empty log message ***
300:
301: Revision 1.98 2004/05/16 15:05:56 brouard
302: New version 0.97 . First attempt to estimate force of mortality
303: directly from the data i.e. without the need of knowing the health
304: state at each age, but using a Gompertz model: log u =a + b*age .
305: This is the basic analysis of mortality and should be done before any
306: other analysis, in order to test if the mortality estimated from the
307: cross-longitudinal survey is different from the mortality estimated
308: from other sources like vital statistic data.
309:
310: The same imach parameter file can be used but the option for mle should be -3.
311:
1.133 brouard 312: Agnès, who wrote this part of the code, tried to keep most of the
1.126 brouard 313: former routines in order to include the new code within the former code.
314:
315: The output is very simple: only an estimate of the intercept and of
316: the slope with 95% confident intervals.
317:
318: Current limitations:
319: A) Even if you enter covariates, i.e. with the
320: model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
321: B) There is no computation of Life Expectancy nor Life Table.
322:
323: Revision 1.97 2004/02/20 13:25:42 lievre
324: Version 0.96d. Population forecasting command line is (temporarily)
325: suppressed.
326:
327: Revision 1.96 2003/07/15 15:38:55 brouard
328: * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
329: rewritten within the same printf. Workaround: many printfs.
330:
331: Revision 1.95 2003/07/08 07:54:34 brouard
332: * imach.c (Repository):
333: (Repository): Using imachwizard code to output a more meaningful covariance
334: matrix (cov(a12,c31) instead of numbers.
335:
336: Revision 1.94 2003/06/27 13:00:02 brouard
337: Just cleaning
338:
339: Revision 1.93 2003/06/25 16:33:55 brouard
340: (Module): On windows (cygwin) function asctime_r doesn't
341: exist so I changed back to asctime which exists.
342: (Module): Version 0.96b
343:
344: Revision 1.92 2003/06/25 16:30:45 brouard
345: (Module): On windows (cygwin) function asctime_r doesn't
346: exist so I changed back to asctime which exists.
347:
348: Revision 1.91 2003/06/25 15:30:29 brouard
349: * imach.c (Repository): Duplicated warning errors corrected.
350: (Repository): Elapsed time after each iteration is now output. It
351: helps to forecast when convergence will be reached. Elapsed time
352: is stamped in powell. We created a new html file for the graphs
353: concerning matrix of covariance. It has extension -cov.htm.
354:
355: Revision 1.90 2003/06/24 12:34:15 brouard
356: (Module): Some bugs corrected for windows. Also, when
357: mle=-1 a template is output in file "or"mypar.txt with the design
358: of the covariance matrix to be input.
359:
360: Revision 1.89 2003/06/24 12:30:52 brouard
361: (Module): Some bugs corrected for windows. Also, when
362: mle=-1 a template is output in file "or"mypar.txt with the design
363: of the covariance matrix to be input.
364:
365: Revision 1.88 2003/06/23 17:54:56 brouard
366: * 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.
367:
368: Revision 1.87 2003/06/18 12:26:01 brouard
369: Version 0.96
370:
371: Revision 1.86 2003/06/17 20:04:08 brouard
372: (Module): Change position of html and gnuplot routines and added
373: routine fileappend.
374:
375: Revision 1.85 2003/06/17 13:12:43 brouard
376: * imach.c (Repository): Check when date of death was earlier that
377: current date of interview. It may happen when the death was just
378: prior to the death. In this case, dh was negative and likelihood
379: was wrong (infinity). We still send an "Error" but patch by
380: assuming that the date of death was just one stepm after the
381: interview.
382: (Repository): Because some people have very long ID (first column)
383: we changed int to long in num[] and we added a new lvector for
384: memory allocation. But we also truncated to 8 characters (left
385: truncation)
386: (Repository): No more line truncation errors.
387:
388: Revision 1.84 2003/06/13 21:44:43 brouard
389: * imach.c (Repository): Replace "freqsummary" at a correct
390: place. It differs from routine "prevalence" which may be called
391: many times. Probs is memory consuming and must be used with
392: parcimony.
393: Version 0.95a3 (should output exactly the same maximization than 0.8a2)
394:
395: Revision 1.83 2003/06/10 13:39:11 lievre
396: *** empty log message ***
397:
398: Revision 1.82 2003/06/05 15:57:20 brouard
399: Add log in imach.c and fullversion number is now printed.
400:
401: */
402: /*
403: Interpolated Markov Chain
404:
405: Short summary of the programme:
406:
407: This program computes Healthy Life Expectancies from
408: cross-longitudinal data. Cross-longitudinal data consist in: -1- a
409: first survey ("cross") where individuals from different ages are
410: interviewed on their health status or degree of disability (in the
411: case of a health survey which is our main interest) -2- at least a
412: second wave of interviews ("longitudinal") which measure each change
413: (if any) in individual health status. Health expectancies are
414: computed from the time spent in each health state according to a
415: model. More health states you consider, more time is necessary to reach the
416: Maximum Likelihood of the parameters involved in the model. The
417: simplest model is the multinomial logistic model where pij is the
418: probability to be observed in state j at the second wave
419: conditional to be observed in state i at the first wave. Therefore
420: the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
421: 'age' is age and 'sex' is a covariate. If you want to have a more
422: complex model than "constant and age", you should modify the program
423: where the markup *Covariates have to be included here again* invites
424: you to do it. More covariates you add, slower the
425: convergence.
426:
427: The advantage of this computer programme, compared to a simple
428: multinomial logistic model, is clear when the delay between waves is not
429: identical for each individual. Also, if a individual missed an
430: intermediate interview, the information is lost, but taken into
431: account using an interpolation or extrapolation.
432:
433: hPijx is the probability to be observed in state i at age x+h
434: conditional to the observed state i at age x. The delay 'h' can be
435: split into an exact number (nh*stepm) of unobserved intermediate
436: states. This elementary transition (by month, quarter,
437: semester or year) is modelled as a multinomial logistic. The hPx
438: matrix is simply the matrix product of nh*stepm elementary matrices
439: and the contribution of each individual to the likelihood is simply
440: hPijx.
441:
442: Also this programme outputs the covariance matrix of the parameters but also
443: of the life expectancies. It also computes the period (stable) prevalence.
444:
1.133 brouard 445: Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
446: Institut national d'études démographiques, Paris.
1.126 brouard 447: This software have been partly granted by Euro-REVES, a concerted action
448: from the European Union.
449: It is copyrighted identically to a GNU software product, ie programme and
450: software can be distributed freely for non commercial use. Latest version
451: can be accessed at http://euroreves.ined.fr/imach .
452:
453: Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
454: or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
455:
456: **********************************************************************/
457: /*
458: main
459: read parameterfile
460: read datafile
461: concatwav
462: freqsummary
463: if (mle >= 1)
464: mlikeli
465: print results files
466: if mle==1
467: computes hessian
468: read end of parameter file: agemin, agemax, bage, fage, estepm
469: begin-prev-date,...
470: open gnuplot file
471: open html file
1.145 brouard 472: period (stable) prevalence | pl_nom 1-1 2-2 etc by covariate
473: for age prevalim() | #****** V1=0 V2=1 V3=1 V4=0 ******
474: | 65 1 0 2 1 3 1 4 0 0.96326 0.03674
475: freexexit2 possible for memory heap.
476:
477: h Pij x | pij_nom ficrestpij
478: # Cov Agex agex+h hpijx with i,j= 1-1 1-2 1-3 2-1 2-2 2-3
479: 1 85 85 1.00000 0.00000 0.00000 0.00000 1.00000 0.00000
480: 1 85 86 0.68299 0.22291 0.09410 0.71093 0.00000 0.28907
481:
482: 1 65 99 0.00364 0.00322 0.99314 0.00350 0.00310 0.99340
483: 1 65 100 0.00214 0.00204 0.99581 0.00206 0.00196 0.99597
484: variance of p one-step probabilities varprob | prob_nom ficresprob #One-step probabilities and stand. devi in ()
485: Standard deviation of one-step probabilities | probcor_nom ficresprobcor #One-step probabilities and correlation matrix
486: Matrix of variance covariance of one-step probabilities | probcov_nom ficresprobcov #One-step probabilities and covariance matrix
487:
1.126 brouard 488: forecasting if prevfcast==1 prevforecast call prevalence()
489: health expectancies
490: Variance-covariance of DFLE
491: prevalence()
492: movingaverage()
493: varevsij()
494: if popbased==1 varevsij(,popbased)
495: total life expectancies
496: Variance of period (stable) prevalence
497: end
498: */
499:
1.165 ! brouard 500: #define POWELL /* Instead of NLOPT */
1.126 brouard 501:
502: #include <math.h>
503: #include <stdio.h>
504: #include <stdlib.h>
505: #include <string.h>
1.159 brouard 506:
507: #ifdef _WIN32
508: #include <io.h>
509: #else
1.126 brouard 510: #include <unistd.h>
1.159 brouard 511: #endif
1.126 brouard 512:
513: #include <limits.h>
514: #include <sys/types.h>
515: #include <sys/stat.h>
516: #include <errno.h>
1.159 brouard 517: /* extern int errno; */
1.126 brouard 518:
1.157 brouard 519: /* #ifdef LINUX */
520: /* #include <time.h> */
521: /* #include "timeval.h" */
522: /* #else */
523: /* #include <sys/time.h> */
524: /* #endif */
525:
1.126 brouard 526: #include <time.h>
527:
1.136 brouard 528: #ifdef GSL
529: #include <gsl/gsl_errno.h>
530: #include <gsl/gsl_multimin.h>
531: #endif
532:
1.162 brouard 533: #ifdef NLOPT
534: #include <nlopt.h>
535: typedef struct {
536: double (* function)(double [] );
537: } myfunc_data ;
538: #endif
539:
1.126 brouard 540: /* #include <libintl.h> */
541: /* #define _(String) gettext (String) */
542:
1.141 brouard 543: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126 brouard 544:
545: #define GNUPLOTPROGRAM "gnuplot"
546: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
547: #define FILENAMELENGTH 132
548:
549: #define GLOCK_ERROR_NOPATH -1 /* empty path */
550: #define GLOCK_ERROR_GETCWD -2 /* cannot get cwd */
551:
1.144 brouard 552: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
553: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126 brouard 554:
555: #define NINTERVMAX 8
1.144 brouard 556: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
557: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
558: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.145 brouard 559: #define codtabm(h,k) 1 & (h-1) >> (k-1) ;
1.126 brouard 560: #define MAXN 20000
1.144 brouard 561: #define YEARM 12. /**< Number of months per year */
1.126 brouard 562: #define AGESUP 130
563: #define AGEBASE 40
1.164 brouard 564: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157 brouard 565: #ifdef _WIN32
566: #define DIRSEPARATOR '\\'
567: #define CHARSEPARATOR "\\"
568: #define ODIRSEPARATOR '/'
569: #else
1.126 brouard 570: #define DIRSEPARATOR '/'
571: #define CHARSEPARATOR "/"
572: #define ODIRSEPARATOR '\\'
573: #endif
574:
1.165 ! brouard 575: /* $Id: imach.c,v 1.164 2014/12/16 10:52:11 brouard Exp $ */
1.126 brouard 576: /* $State: Exp $ */
577:
1.162 brouard 578: char version[]="Imach version 0.99, September 2014,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121)";
1.165 ! brouard 579: char fullversion[]="$Revision: 1.164 $ $Date: 2014/12/16 10:52:11 $";
1.126 brouard 580: char strstart[80];
581: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130 brouard 582: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings */
1.133 brouard 583: int nvar=0, nforce=0; /* Number of variables, number of forces */
1.145 brouard 584: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
585: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
586: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
587: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
588: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
589: int cptcovprodnoage=0; /**< Number of covariate products without age */
590: int cptcoveff=0; /* Total number of covariates to vary for printing results */
591: int cptcov=0; /* Working variable */
1.126 brouard 592: int npar=NPARMAX;
593: int nlstate=2; /* Number of live states */
594: int ndeath=1; /* Number of dead states */
1.130 brouard 595: int ncovmodel=0, ncovcol=0; /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126 brouard 596: int popbased=0;
597:
598: int *wav; /* Number of waves for this individuual 0 is possible */
1.130 brouard 599: int maxwav=0; /* Maxim number of waves */
600: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
601: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */
602: int gipmx=0, gsw=0; /* Global variables on the number of contributions
1.126 brouard 603: to the likelihood and the sum of weights (done by funcone)*/
1.130 brouard 604: int mle=1, weightopt=0;
1.126 brouard 605: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
606: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
607: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
608: * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162 brouard 609: int countcallfunc=0; /* Count the number of calls to func */
1.130 brouard 610: double jmean=1; /* Mean space between 2 waves */
1.145 brouard 611: double **matprod2(); /* test */
1.126 brouard 612: double **oldm, **newm, **savm; /* Working pointers to matrices */
613: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136 brouard 614: /*FILE *fic ; */ /* Used in readdata only */
615: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126 brouard 616: FILE *ficlog, *ficrespow;
1.130 brouard 617: int globpr=0; /* Global variable for printing or not */
1.126 brouard 618: double fretone; /* Only one call to likelihood */
1.130 brouard 619: long ipmx=0; /* Number of contributions */
1.126 brouard 620: double sw; /* Sum of weights */
621: char filerespow[FILENAMELENGTH];
622: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
623: FILE *ficresilk;
624: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
625: FILE *ficresprobmorprev;
626: FILE *fichtm, *fichtmcov; /* Html File */
627: FILE *ficreseij;
628: char filerese[FILENAMELENGTH];
629: FILE *ficresstdeij;
630: char fileresstde[FILENAMELENGTH];
631: FILE *ficrescveij;
632: char filerescve[FILENAMELENGTH];
633: FILE *ficresvij;
634: char fileresv[FILENAMELENGTH];
635: FILE *ficresvpl;
636: char fileresvpl[FILENAMELENGTH];
637: char title[MAXLINE];
638: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH], filerespl[FILENAMELENGTH];
639: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
640: char tmpout[FILENAMELENGTH], tmpout2[FILENAMELENGTH];
641: char command[FILENAMELENGTH];
642: int outcmd=0;
643:
644: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
645:
646: char filelog[FILENAMELENGTH]; /* Log file */
647: char filerest[FILENAMELENGTH];
648: char fileregp[FILENAMELENGTH];
649: char popfile[FILENAMELENGTH];
650:
651: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
652:
1.157 brouard 653: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
654: /* struct timezone tzp; */
655: /* extern int gettimeofday(); */
656: struct tm tml, *gmtime(), *localtime();
657:
658: extern time_t time();
659:
660: struct tm start_time, end_time, curr_time, last_time, forecast_time;
661: time_t rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
662: struct tm tm;
663:
1.126 brouard 664: char strcurr[80], strfor[80];
665:
666: char *endptr;
667: long lval;
668: double dval;
669:
670: #define NR_END 1
671: #define FREE_ARG char*
672: #define FTOL 1.0e-10
673:
674: #define NRANSI
675: #define ITMAX 200
676:
677: #define TOL 2.0e-4
678:
679: #define CGOLD 0.3819660
680: #define ZEPS 1.0e-10
681: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
682:
683: #define GOLD 1.618034
684: #define GLIMIT 100.0
685: #define TINY 1.0e-20
686:
687: static double maxarg1,maxarg2;
688: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
689: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
690:
691: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
692: #define rint(a) floor(a+0.5)
693:
694: static double sqrarg;
695: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
696: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
697: int agegomp= AGEGOMP;
698:
699: int imx;
700: int stepm=1;
701: /* Stepm, step in month: minimum step interpolation*/
702:
703: int estepm;
704: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
705:
706: int m,nb;
707: long *num;
708: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
709: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
710: double **pmmij, ***probs;
711: double *ageexmed,*agecens;
712: double dateintmean=0;
713:
714: double *weight;
715: int **s; /* Status */
1.141 brouard 716: double *agedc;
1.145 brouard 717: double **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141 brouard 718: * covar=matrix(0,NCOVMAX,1,n);
719: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; */
720: double idx;
721: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.145 brouard 722: int *Ndum; /** Freq of modality (tricode */
1.141 brouard 723: int **codtab; /**< codtab=imatrix(1,100,1,10); */
724: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126 brouard 725: double *lsurv, *lpop, *tpop;
726:
1.143 brouard 727: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
728: double ftolhess; /**< Tolerance for computing hessian */
1.126 brouard 729:
730: /**************** split *************************/
731: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
732: {
733: /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
734: the name of the file (name), its extension only (ext) and its first part of the name (finame)
735: */
736: char *ss; /* pointer */
737: int l1, l2; /* length counters */
738:
739: l1 = strlen(path ); /* length of path */
740: if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
741: ss= strrchr( path, DIRSEPARATOR ); /* find last / */
742: if ( ss == NULL ) { /* no directory, so determine current directory */
743: strcpy( name, path ); /* we got the fullname name because no directory */
744: /*if(strrchr(path, ODIRSEPARATOR )==NULL)
745: printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
746: /* get current working directory */
747: /* extern char* getcwd ( char *buf , int len);*/
748: if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
749: return( GLOCK_ERROR_GETCWD );
750: }
751: /* got dirc from getcwd*/
752: printf(" DIRC = %s \n",dirc);
753: } else { /* strip direcotry from path */
754: ss++; /* after this, the filename */
755: l2 = strlen( ss ); /* length of filename */
756: if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
757: strcpy( name, ss ); /* save file name */
758: strncpy( dirc, path, l1 - l2 ); /* now the directory */
759: dirc[l1-l2] = 0; /* add zero */
760: printf(" DIRC2 = %s \n",dirc);
761: }
762: /* We add a separator at the end of dirc if not exists */
763: l1 = strlen( dirc ); /* length of directory */
764: if( dirc[l1-1] != DIRSEPARATOR ){
765: dirc[l1] = DIRSEPARATOR;
766: dirc[l1+1] = 0;
767: printf(" DIRC3 = %s \n",dirc);
768: }
769: ss = strrchr( name, '.' ); /* find last / */
770: if (ss >0){
771: ss++;
772: strcpy(ext,ss); /* save extension */
773: l1= strlen( name);
774: l2= strlen(ss)+1;
775: strncpy( finame, name, l1-l2);
776: finame[l1-l2]= 0;
777: }
778:
779: return( 0 ); /* we're done */
780: }
781:
782:
783: /******************************************/
784:
785: void replace_back_to_slash(char *s, char*t)
786: {
787: int i;
788: int lg=0;
789: i=0;
790: lg=strlen(t);
791: for(i=0; i<= lg; i++) {
792: (s[i] = t[i]);
793: if (t[i]== '\\') s[i]='/';
794: }
795: }
796:
1.132 brouard 797: char *trimbb(char *out, char *in)
1.137 brouard 798: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132 brouard 799: char *s;
800: s=out;
801: while (*in != '\0'){
1.137 brouard 802: while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132 brouard 803: in++;
804: }
805: *out++ = *in++;
806: }
807: *out='\0';
808: return s;
809: }
810:
1.145 brouard 811: char *cutl(char *blocc, char *alocc, char *in, char occ)
812: {
813: /* cuts string in into blocc and alocc where blocc ends before first occurence of char 'occ'
814: and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
815: gives blocc="abcdef2ghi" and alocc="j".
816: If occ is not found blocc is null and alocc is equal to in. Returns blocc
817: */
1.160 brouard 818: char *s, *t;
1.145 brouard 819: t=in;s=in;
820: while ((*in != occ) && (*in != '\0')){
821: *alocc++ = *in++;
822: }
823: if( *in == occ){
824: *(alocc)='\0';
825: s=++in;
826: }
827:
828: if (s == t) {/* occ not found */
829: *(alocc-(in-s))='\0';
830: in=s;
831: }
832: while ( *in != '\0'){
833: *blocc++ = *in++;
834: }
835:
836: *blocc='\0';
837: return t;
838: }
1.137 brouard 839: char *cutv(char *blocc, char *alocc, char *in, char occ)
840: {
841: /* cuts string in into blocc and alocc where blocc ends before last occurence of char 'occ'
842: and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
843: gives blocc="abcdef2ghi" and alocc="j".
844: If occ is not found blocc is null and alocc is equal to in. Returns alocc
845: */
846: char *s, *t;
847: t=in;s=in;
848: while (*in != '\0'){
849: while( *in == occ){
850: *blocc++ = *in++;
851: s=in;
852: }
853: *blocc++ = *in++;
854: }
855: if (s == t) /* occ not found */
856: *(blocc-(in-s))='\0';
857: else
858: *(blocc-(in-s)-1)='\0';
859: in=s;
860: while ( *in != '\0'){
861: *alocc++ = *in++;
862: }
863:
864: *alocc='\0';
865: return s;
866: }
867:
1.126 brouard 868: int nbocc(char *s, char occ)
869: {
870: int i,j=0;
871: int lg=20;
872: i=0;
873: lg=strlen(s);
874: for(i=0; i<= lg; i++) {
875: if (s[i] == occ ) j++;
876: }
877: return j;
878: }
879:
1.137 brouard 880: /* void cutv(char *u,char *v, char*t, char occ) */
881: /* { */
882: /* /\* cuts string t into u and v where u ends before last occurence of char 'occ' */
883: /* and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
884: /* gives u="abcdef2ghi" and v="j" *\/ */
885: /* int i,lg,j,p=0; */
886: /* i=0; */
887: /* lg=strlen(t); */
888: /* for(j=0; j<=lg-1; j++) { */
889: /* if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
890: /* } */
1.126 brouard 891:
1.137 brouard 892: /* for(j=0; j<p; j++) { */
893: /* (u[j] = t[j]); */
894: /* } */
895: /* u[p]='\0'; */
1.126 brouard 896:
1.137 brouard 897: /* for(j=0; j<= lg; j++) { */
898: /* if (j>=(p+1))(v[j-p-1] = t[j]); */
899: /* } */
900: /* } */
1.126 brouard 901:
1.160 brouard 902: #ifdef _WIN32
903: char * strsep(char **pp, const char *delim)
904: {
905: char *p, *q;
906:
907: if ((p = *pp) == NULL)
908: return 0;
909: if ((q = strpbrk (p, delim)) != NULL)
910: {
911: *pp = q + 1;
912: *q = '\0';
913: }
914: else
915: *pp = 0;
916: return p;
917: }
918: #endif
919:
1.126 brouard 920: /********************** nrerror ********************/
921:
922: void nrerror(char error_text[])
923: {
924: fprintf(stderr,"ERREUR ...\n");
925: fprintf(stderr,"%s\n",error_text);
926: exit(EXIT_FAILURE);
927: }
928: /*********************** vector *******************/
929: double *vector(int nl, int nh)
930: {
931: double *v;
932: v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
933: if (!v) nrerror("allocation failure in vector");
934: return v-nl+NR_END;
935: }
936:
937: /************************ free vector ******************/
938: void free_vector(double*v, int nl, int nh)
939: {
940: free((FREE_ARG)(v+nl-NR_END));
941: }
942:
943: /************************ivector *******************************/
944: int *ivector(long nl,long nh)
945: {
946: int *v;
947: v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
948: if (!v) nrerror("allocation failure in ivector");
949: return v-nl+NR_END;
950: }
951:
952: /******************free ivector **************************/
953: void free_ivector(int *v, long nl, long nh)
954: {
955: free((FREE_ARG)(v+nl-NR_END));
956: }
957:
958: /************************lvector *******************************/
959: long *lvector(long nl,long nh)
960: {
961: long *v;
962: v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
963: if (!v) nrerror("allocation failure in ivector");
964: return v-nl+NR_END;
965: }
966:
967: /******************free lvector **************************/
968: void free_lvector(long *v, long nl, long nh)
969: {
970: free((FREE_ARG)(v+nl-NR_END));
971: }
972:
973: /******************* imatrix *******************************/
974: int **imatrix(long nrl, long nrh, long ncl, long nch)
975: /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
976: {
977: long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
978: int **m;
979:
980: /* allocate pointers to rows */
981: m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
982: if (!m) nrerror("allocation failure 1 in matrix()");
983: m += NR_END;
984: m -= nrl;
985:
986:
987: /* allocate rows and set pointers to them */
988: m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
989: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
990: m[nrl] += NR_END;
991: m[nrl] -= ncl;
992:
993: for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
994:
995: /* return pointer to array of pointers to rows */
996: return m;
997: }
998:
999: /****************** free_imatrix *************************/
1000: void free_imatrix(m,nrl,nrh,ncl,nch)
1001: int **m;
1002: long nch,ncl,nrh,nrl;
1003: /* free an int matrix allocated by imatrix() */
1004: {
1005: free((FREE_ARG) (m[nrl]+ncl-NR_END));
1006: free((FREE_ARG) (m+nrl-NR_END));
1007: }
1008:
1009: /******************* matrix *******************************/
1010: double **matrix(long nrl, long nrh, long ncl, long nch)
1011: {
1012: long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
1013: double **m;
1014:
1015: m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1016: if (!m) nrerror("allocation failure 1 in matrix()");
1017: m += NR_END;
1018: m -= nrl;
1019:
1020: m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1021: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1022: m[nrl] += NR_END;
1023: m[nrl] -= ncl;
1024:
1025: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1026: return m;
1.145 brouard 1027: /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
1028: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
1029: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126 brouard 1030: */
1031: }
1032:
1033: /*************************free matrix ************************/
1034: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
1035: {
1036: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1037: free((FREE_ARG)(m+nrl-NR_END));
1038: }
1039:
1040: /******************* ma3x *******************************/
1041: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
1042: {
1043: long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
1044: double ***m;
1045:
1046: m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1047: if (!m) nrerror("allocation failure 1 in matrix()");
1048: m += NR_END;
1049: m -= nrl;
1050:
1051: m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1052: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1053: m[nrl] += NR_END;
1054: m[nrl] -= ncl;
1055:
1056: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1057:
1058: m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
1059: if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
1060: m[nrl][ncl] += NR_END;
1061: m[nrl][ncl] -= nll;
1062: for (j=ncl+1; j<=nch; j++)
1063: m[nrl][j]=m[nrl][j-1]+nlay;
1064:
1065: for (i=nrl+1; i<=nrh; i++) {
1066: m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
1067: for (j=ncl+1; j<=nch; j++)
1068: m[i][j]=m[i][j-1]+nlay;
1069: }
1070: return m;
1071: /* gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
1072: &(m[i][j][k]) <=> *((*(m+i) + j)+k)
1073: */
1074: }
1075:
1076: /*************************free ma3x ************************/
1077: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
1078: {
1079: free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
1080: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1081: free((FREE_ARG)(m+nrl-NR_END));
1082: }
1083:
1084: /*************** function subdirf ***********/
1085: char *subdirf(char fileres[])
1086: {
1087: /* Caution optionfilefiname is hidden */
1088: strcpy(tmpout,optionfilefiname);
1089: strcat(tmpout,"/"); /* Add to the right */
1090: strcat(tmpout,fileres);
1091: return tmpout;
1092: }
1093:
1094: /*************** function subdirf2 ***********/
1095: char *subdirf2(char fileres[], char *preop)
1096: {
1097:
1098: /* Caution optionfilefiname is hidden */
1099: strcpy(tmpout,optionfilefiname);
1100: strcat(tmpout,"/");
1101: strcat(tmpout,preop);
1102: strcat(tmpout,fileres);
1103: return tmpout;
1104: }
1105:
1106: /*************** function subdirf3 ***********/
1107: char *subdirf3(char fileres[], char *preop, char *preop2)
1108: {
1109:
1110: /* Caution optionfilefiname is hidden */
1111: strcpy(tmpout,optionfilefiname);
1112: strcat(tmpout,"/");
1113: strcat(tmpout,preop);
1114: strcat(tmpout,preop2);
1115: strcat(tmpout,fileres);
1116: return tmpout;
1117: }
1118:
1.162 brouard 1119: char *asc_diff_time(long time_sec, char ascdiff[])
1120: {
1121: long sec_left, days, hours, minutes;
1122: days = (time_sec) / (60*60*24);
1123: sec_left = (time_sec) % (60*60*24);
1124: hours = (sec_left) / (60*60) ;
1125: sec_left = (sec_left) %(60*60);
1126: minutes = (sec_left) /60;
1127: sec_left = (sec_left) % (60);
1128: sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);
1129: return ascdiff;
1130: }
1131:
1.126 brouard 1132: /***************** f1dim *************************/
1133: extern int ncom;
1134: extern double *pcom,*xicom;
1135: extern double (*nrfunc)(double []);
1136:
1137: double f1dim(double x)
1138: {
1139: int j;
1140: double f;
1141: double *xt;
1142:
1143: xt=vector(1,ncom);
1144: for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
1145: f=(*nrfunc)(xt);
1146: free_vector(xt,1,ncom);
1147: return f;
1148: }
1149:
1150: /*****************brent *************************/
1151: double brent(double ax, double bx, double cx, double (*f)(double), double tol, double *xmin)
1152: {
1153: int iter;
1154: double a,b,d,etemp;
1.159 brouard 1155: double fu=0,fv,fw,fx;
1.164 brouard 1156: double ftemp=0.;
1.126 brouard 1157: double p,q,r,tol1,tol2,u,v,w,x,xm;
1158: double e=0.0;
1159:
1160: a=(ax < cx ? ax : cx);
1161: b=(ax > cx ? ax : cx);
1162: x=w=v=bx;
1163: fw=fv=fx=(*f)(x);
1164: for (iter=1;iter<=ITMAX;iter++) {
1165: xm=0.5*(a+b);
1166: tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
1167: /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
1168: printf(".");fflush(stdout);
1169: fprintf(ficlog,".");fflush(ficlog);
1.162 brouard 1170: #ifdef DEBUGBRENT
1.126 brouard 1171: 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);
1172: 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);
1173: /* if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
1174: #endif
1175: if (fabs(x-xm) <= (tol2-0.5*(b-a))){
1176: *xmin=x;
1177: return fx;
1178: }
1179: ftemp=fu;
1180: if (fabs(e) > tol1) {
1181: r=(x-w)*(fx-fv);
1182: q=(x-v)*(fx-fw);
1183: p=(x-v)*q-(x-w)*r;
1184: q=2.0*(q-r);
1185: if (q > 0.0) p = -p;
1186: q=fabs(q);
1187: etemp=e;
1188: e=d;
1189: if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
1190: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1191: else {
1192: d=p/q;
1193: u=x+d;
1194: if (u-a < tol2 || b-u < tol2)
1195: d=SIGN(tol1,xm-x);
1196: }
1197: } else {
1198: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1199: }
1200: u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
1201: fu=(*f)(u);
1202: if (fu <= fx) {
1203: if (u >= x) a=x; else b=x;
1204: SHFT(v,w,x,u)
1205: SHFT(fv,fw,fx,fu)
1206: } else {
1207: if (u < x) a=u; else b=u;
1208: if (fu <= fw || w == x) {
1209: v=w;
1210: w=u;
1211: fv=fw;
1212: fw=fu;
1213: } else if (fu <= fv || v == x || v == w) {
1214: v=u;
1215: fv=fu;
1216: }
1217: }
1218: }
1219: nrerror("Too many iterations in brent");
1220: *xmin=x;
1221: return fx;
1222: }
1223:
1224: /****************** mnbrak ***********************/
1225:
1226: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
1227: double (*func)(double))
1228: {
1229: double ulim,u,r,q, dum;
1230: double fu;
1231:
1232: *fa=(*func)(*ax);
1233: *fb=(*func)(*bx);
1234: if (*fb > *fa) {
1235: SHFT(dum,*ax,*bx,dum)
1236: SHFT(dum,*fb,*fa,dum)
1237: }
1238: *cx=(*bx)+GOLD*(*bx-*ax);
1239: *fc=(*func)(*cx);
1.162 brouard 1240: while (*fb > *fc) { /* Declining fa, fb, fc */
1.126 brouard 1241: r=(*bx-*ax)*(*fb-*fc);
1242: q=(*bx-*cx)*(*fb-*fa);
1243: u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
1.162 brouard 1244: (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscisse of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
1245: ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscisse where function can be evaluated */
1246: if ((*bx-u)*(u-*cx) > 0.0) { /* if u between b and c */
1.126 brouard 1247: fu=(*func)(u);
1.163 brouard 1248: #ifdef DEBUG
1249: /* f(x)=A(x-u)**2+f(u) */
1250: double A, fparabu;
1251: A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
1252: fparabu= *fa - A*(*ax-u)*(*ax-u);
1253: 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);
1254: 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);
1255: #endif
1.162 brouard 1256: } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.126 brouard 1257: fu=(*func)(u);
1258: if (fu < *fc) {
1259: SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
1260: SHFT(*fb,*fc,fu,(*func)(u))
1261: }
1.162 brouard 1262: } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.126 brouard 1263: u=ulim;
1264: fu=(*func)(u);
1265: } else {
1266: u=(*cx)+GOLD*(*cx-*bx);
1267: fu=(*func)(u);
1268: }
1269: SHFT(*ax,*bx,*cx,u)
1270: SHFT(*fa,*fb,*fc,fu)
1271: }
1272: }
1273:
1274: /*************** linmin ************************/
1.162 brouard 1275: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
1276: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
1277: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
1278: the value of func at the returned location p . This is actually all accomplished by calling the
1279: routines mnbrak and brent .*/
1.126 brouard 1280: int ncom;
1281: double *pcom,*xicom;
1282: double (*nrfunc)(double []);
1283:
1284: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
1285: {
1286: double brent(double ax, double bx, double cx,
1287: double (*f)(double), double tol, double *xmin);
1288: double f1dim(double x);
1289: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
1290: double *fc, double (*func)(double));
1291: int j;
1292: double xx,xmin,bx,ax;
1293: double fx,fb,fa;
1294:
1295: ncom=n;
1296: pcom=vector(1,n);
1297: xicom=vector(1,n);
1298: nrfunc=func;
1299: for (j=1;j<=n;j++) {
1300: pcom[j]=p[j];
1301: xicom[j]=xi[j];
1302: }
1303: ax=0.0;
1304: xx=1.0;
1.162 brouard 1305: mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Find a bracket a,x,b in direction n=xi ie xicom */
1306: *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 1307: #ifdef DEBUG
1308: printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1309: fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1310: #endif
1311: for (j=1;j<=n;j++) {
1312: xi[j] *= xmin;
1313: p[j] += xi[j];
1314: }
1315: free_vector(xicom,1,n);
1316: free_vector(pcom,1,n);
1317: }
1318:
1319:
1320: /*************** powell ************************/
1.162 brouard 1321: /*
1322: Minimization of a function func of n variables. Input consists of an initial starting point
1323: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
1324: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
1325: such that failure to decrease by more than this amount on one iteration signals doneness. On
1326: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
1327: function value at p , and iter is the number of iterations taken. The routine linmin is used.
1328: */
1.126 brouard 1329: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
1330: double (*func)(double []))
1331: {
1332: void linmin(double p[], double xi[], int n, double *fret,
1333: double (*func)(double []));
1334: int i,ibig,j;
1335: double del,t,*pt,*ptt,*xit;
1336: double fp,fptt;
1337: double *xits;
1338: int niterf, itmp;
1339:
1340: pt=vector(1,n);
1341: ptt=vector(1,n);
1342: xit=vector(1,n);
1343: xits=vector(1,n);
1344: *fret=(*func)(p);
1345: for (j=1;j<=n;j++) pt[j]=p[j];
1.157 brouard 1346: rcurr_time = time(NULL);
1.126 brouard 1347: for (*iter=1;;++(*iter)) {
1348: fp=(*fret);
1349: ibig=0;
1350: del=0.0;
1.157 brouard 1351: rlast_time=rcurr_time;
1352: /* (void) gettimeofday(&curr_time,&tzp); */
1353: rcurr_time = time(NULL);
1354: curr_time = *localtime(&rcurr_time);
1355: printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
1356: fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1357: /* fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.126 brouard 1358: for (i=1;i<=n;i++) {
1359: printf(" %d %.12f",i, p[i]);
1360: fprintf(ficlog," %d %.12lf",i, p[i]);
1361: fprintf(ficrespow," %.12lf", p[i]);
1362: }
1363: printf("\n");
1364: fprintf(ficlog,"\n");
1365: fprintf(ficrespow,"\n");fflush(ficrespow);
1366: if(*iter <=3){
1.157 brouard 1367: tml = *localtime(&rcurr_time);
1368: strcpy(strcurr,asctime(&tml));
1369: rforecast_time=rcurr_time;
1.126 brouard 1370: itmp = strlen(strcurr);
1371: if(strcurr[itmp-1]=='\n') /* Windows outputs with a new line */
1372: strcurr[itmp-1]='\0';
1.162 brouard 1373: printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157 brouard 1374: fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126 brouard 1375: for(niterf=10;niterf<=30;niterf+=10){
1.157 brouard 1376: rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
1377: forecast_time = *localtime(&rforecast_time);
1378: strcpy(strfor,asctime(&forecast_time));
1.126 brouard 1379: itmp = strlen(strfor);
1380: if(strfor[itmp-1]=='\n')
1381: strfor[itmp-1]='\0';
1.157 brouard 1382: 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);
1383: 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 1384: }
1385: }
1386: for (i=1;i<=n;i++) {
1387: for (j=1;j<=n;j++) xit[j]=xi[j][i];
1388: fptt=(*fret);
1389: #ifdef DEBUG
1.164 brouard 1390: printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1391: fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126 brouard 1392: #endif
1393: printf("%d",i);fflush(stdout);
1394: fprintf(ficlog,"%d",i);fflush(ficlog);
1395: linmin(p,xit,n,fret,func);
1396: if (fabs(fptt-(*fret)) > del) {
1397: del=fabs(fptt-(*fret));
1398: ibig=i;
1399: }
1400: #ifdef DEBUG
1401: printf("%d %.12e",i,(*fret));
1402: fprintf(ficlog,"%d %.12e",i,(*fret));
1403: for (j=1;j<=n;j++) {
1404: xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
1405: printf(" x(%d)=%.12e",j,xit[j]);
1406: fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1407: }
1408: for(j=1;j<=n;j++) {
1.162 brouard 1409: printf(" p(%d)=%.12e",j,p[j]);
1410: fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126 brouard 1411: }
1412: printf("\n");
1413: fprintf(ficlog,"\n");
1414: #endif
1.162 brouard 1415: } /* end i */
1.126 brouard 1416: if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
1417: #ifdef DEBUG
1418: int k[2],l;
1419: k[0]=1;
1420: k[1]=-1;
1421: printf("Max: %.12e",(*func)(p));
1422: fprintf(ficlog,"Max: %.12e",(*func)(p));
1423: for (j=1;j<=n;j++) {
1424: printf(" %.12e",p[j]);
1425: fprintf(ficlog," %.12e",p[j]);
1426: }
1427: printf("\n");
1428: fprintf(ficlog,"\n");
1429: for(l=0;l<=1;l++) {
1430: for (j=1;j<=n;j++) {
1431: ptt[j]=p[j]+(p[j]-pt[j])*k[l];
1432: printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1433: fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1434: }
1435: printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1436: fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1437: }
1438: #endif
1439:
1440:
1441: free_vector(xit,1,n);
1442: free_vector(xits,1,n);
1443: free_vector(ptt,1,n);
1444: free_vector(pt,1,n);
1445: return;
1446: }
1447: if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
1.161 brouard 1448: for (j=1;j<=n;j++) { /* Computes an extrapolated point */
1.126 brouard 1449: ptt[j]=2.0*p[j]-pt[j];
1450: xit[j]=p[j]-pt[j];
1451: pt[j]=p[j];
1452: }
1453: fptt=(*func)(ptt);
1.161 brouard 1454: if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.162 brouard 1455: /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161 brouard 1456: /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162 brouard 1457: /* Let f"(x2) be the 2nd derivative equal everywhere. */
1458: /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
1459: /* will reach at f3 = fm + h^2/2 f"m ; f" = (f1 -2f2 +f3 ) / h**2 */
1.161 brouard 1460: /* f1-f3 = delta(2h) = 2 h**2 f'' = 2(f1- 2f2 +f3) */
1461: /* Thus we compare delta(2h) with observed f1-f3 */
1.162 brouard 1462: /* or best gain on one ancient line 'del' with total */
1463: /* gain f1-f2 = f1 - f2 - 'del' with del */
1.161 brouard 1464: /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.162 brouard 1465:
1.161 brouard 1466: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del);
1467: t= t- del*SQR(fp-fptt);
1468: printf("t1= %.12lf, t2= %.12lf, t=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t);
1469: 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);
1470: #ifdef DEBUG
1471: printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1472: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1473: fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1474: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1475: 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);
1476: 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);
1477: #endif
1478: if (t < 0.0) { /* Then we use it for last direction */
1479: linmin(p,xit,n,fret,func); /* computes mean on the extrapolated direction.*/
1.126 brouard 1480: for (j=1;j<=n;j++) {
1.161 brouard 1481: xi[j][ibig]=xi[j][n]; /* Replace the direction with biggest decrease by n */
1482: xi[j][n]=xit[j]; /* and nth direction by the extrapolated */
1.126 brouard 1483: }
1.161 brouard 1484: printf("Gaining to use average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1485: fprintf(ficlog,"Gaining to use average direction of P0 P%d instead of biggest increase direction :\n",n,ibig);
1486:
1.126 brouard 1487: #ifdef DEBUG
1.164 brouard 1488: printf("Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1489: fprintf(ficlog,"Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126 brouard 1490: for(j=1;j<=n;j++){
1491: printf(" %.12e",xit[j]);
1492: fprintf(ficlog," %.12e",xit[j]);
1493: }
1494: printf("\n");
1495: fprintf(ficlog,"\n");
1496: #endif
1.162 brouard 1497: } /* end of t negative */
1498: } /* end if (fptt < fp) */
1.126 brouard 1499: }
1500: }
1501:
1502: /**** Prevalence limit (stable or period prevalence) ****************/
1503:
1504: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
1505: {
1506: /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1507: matrix by transitions matrix until convergence is reached */
1508:
1509: int i, ii,j,k;
1510: double min, max, maxmin, maxmax,sumnew=0.;
1.145 brouard 1511: /* double **matprod2(); */ /* test */
1.131 brouard 1512: double **out, cov[NCOVMAX+1], **pmij();
1.126 brouard 1513: double **newm;
1514: double agefin, delaymax=50 ; /* Max number of years to converge */
1515:
1516: for (ii=1;ii<=nlstate+ndeath;ii++)
1517: for (j=1;j<=nlstate+ndeath;j++){
1518: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1519: }
1520:
1521: cov[1]=1.;
1522:
1523: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1524: for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1525: newm=savm;
1526: /* Covariates have to be included here again */
1.138 brouard 1527: cov[2]=agefin;
1528:
1529: for (k=1; k<=cptcovn;k++) {
1530: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.145 brouard 1531: /*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 1532: }
1.145 brouard 1533: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1534: /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
1535: /* 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 1536:
1537: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
1538: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
1539: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145 brouard 1540: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1541: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142 brouard 1542: out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138 brouard 1543:
1.126 brouard 1544: savm=oldm;
1545: oldm=newm;
1546: maxmax=0.;
1547: for(j=1;j<=nlstate;j++){
1548: min=1.;
1549: max=0.;
1550: for(i=1; i<=nlstate; i++) {
1551: sumnew=0;
1552: for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
1553: prlim[i][j]= newm[i][j]/(1-sumnew);
1.145 brouard 1554: /*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 1555: max=FMAX(max,prlim[i][j]);
1556: min=FMIN(min,prlim[i][j]);
1557: }
1558: maxmin=max-min;
1559: maxmax=FMAX(maxmax,maxmin);
1560: }
1561: if(maxmax < ftolpl){
1562: return prlim;
1563: }
1564: }
1565: }
1566:
1567: /*************** transition probabilities ***************/
1568:
1569: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1570: {
1.138 brouard 1571: /* According to parameters values stored in x and the covariate's values stored in cov,
1572: computes the probability to be observed in state j being in state i by appying the
1573: model to the ncovmodel covariates (including constant and age).
1574: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
1575: and, according on how parameters are entered, the position of the coefficient xij(nc) of the
1576: ncth covariate in the global vector x is given by the formula:
1577: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
1578: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
1579: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
1580: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1581: Outputs ps[i][j] the probability to be observed in j being in j according to
1582: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1583: */
1584: double s1, lnpijopii;
1.126 brouard 1585: /*double t34;*/
1.164 brouard 1586: int i,j, nc, ii, jj;
1.126 brouard 1587:
1588: for(i=1; i<= nlstate; i++){
1589: for(j=1; j<i;j++){
1.138 brouard 1590: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1591: /*lnpijopii += param[i][j][nc]*cov[nc];*/
1592: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
1593: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 1594: }
1.138 brouard 1595: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1596: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 1597: }
1598: for(j=i+1; j<=nlstate+ndeath;j++){
1.138 brouard 1599: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1600: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
1601: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
1602: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126 brouard 1603: }
1.138 brouard 1604: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126 brouard 1605: }
1606: }
1607:
1608: for(i=1; i<= nlstate; i++){
1609: s1=0;
1.131 brouard 1610: for(j=1; j<i; j++){
1.138 brouard 1611: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 1612: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1613: }
1614: for(j=i+1; j<=nlstate+ndeath; j++){
1.138 brouard 1615: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 1616: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1617: }
1.138 brouard 1618: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126 brouard 1619: ps[i][i]=1./(s1+1.);
1.138 brouard 1620: /* Computing other pijs */
1.126 brouard 1621: for(j=1; j<i; j++)
1622: ps[i][j]= exp(ps[i][j])*ps[i][i];
1623: for(j=i+1; j<=nlstate+ndeath; j++)
1624: ps[i][j]= exp(ps[i][j])*ps[i][i];
1625: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
1626: } /* end i */
1627:
1628: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
1629: for(jj=1; jj<= nlstate+ndeath; jj++){
1630: ps[ii][jj]=0;
1631: ps[ii][ii]=1;
1632: }
1633: }
1634:
1.145 brouard 1635:
1636: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
1637: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */
1638: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
1639: /* } */
1640: /* printf("\n "); */
1641: /* } */
1642: /* printf("\n ");printf("%lf ",cov[2]);*/
1643: /*
1.126 brouard 1644: for(i=1; i<= npar; i++) printf("%f ",x[i]);
1645: goto end;*/
1646: return ps;
1647: }
1648:
1649: /**************** Product of 2 matrices ******************/
1650:
1.145 brouard 1651: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126 brouard 1652: {
1653: /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
1654: b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
1655: /* in, b, out are matrice of pointers which should have been initialized
1656: before: only the contents of out is modified. The function returns
1657: a pointer to pointers identical to out */
1.145 brouard 1658: int i, j, k;
1.126 brouard 1659: for(i=nrl; i<= nrh; i++)
1.145 brouard 1660: for(k=ncolol; k<=ncoloh; k++){
1661: out[i][k]=0.;
1662: for(j=ncl; j<=nch; j++)
1663: out[i][k] +=in[i][j]*b[j][k];
1664: }
1.126 brouard 1665: return out;
1666: }
1667:
1668:
1669: /************* Higher Matrix Product ***************/
1670:
1671: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
1672: {
1673: /* Computes the transition matrix starting at age 'age' over
1674: 'nhstepm*hstepm*stepm' months (i.e. until
1675: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
1676: nhstepm*hstepm matrices.
1677: Output is stored in matrix po[i][j][h] for h every 'hstepm' step
1678: (typically every 2 years instead of every month which is too big
1679: for the memory).
1680: Model is determined by parameters x and covariates have to be
1681: included manually here.
1682:
1683: */
1684:
1685: int i, j, d, h, k;
1.131 brouard 1686: double **out, cov[NCOVMAX+1];
1.126 brouard 1687: double **newm;
1688:
1689: /* Hstepm could be zero and should return the unit matrix */
1690: for (i=1;i<=nlstate+ndeath;i++)
1691: for (j=1;j<=nlstate+ndeath;j++){
1692: oldm[i][j]=(i==j ? 1.0 : 0.0);
1693: po[i][j][0]=(i==j ? 1.0 : 0.0);
1694: }
1695: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1696: for(h=1; h <=nhstepm; h++){
1697: for(d=1; d <=hstepm; d++){
1698: newm=savm;
1699: /* Covariates have to be included here again */
1700: cov[1]=1.;
1701: cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
1.131 brouard 1702: for (k=1; k<=cptcovn;k++)
1703: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.126 brouard 1704: for (k=1; k<=cptcovage;k++)
1705: cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
1.145 brouard 1706: for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.126 brouard 1707: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
1708:
1709:
1710: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
1711: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1712: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
1713: pmij(pmmij,cov,ncovmodel,x,nlstate));
1714: savm=oldm;
1715: oldm=newm;
1716: }
1717: for(i=1; i<=nlstate+ndeath; i++)
1718: for(j=1;j<=nlstate+ndeath;j++) {
1719: po[i][j][h]=newm[i][j];
1.128 brouard 1720: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126 brouard 1721: }
1.128 brouard 1722: /*printf("h=%d ",h);*/
1.126 brouard 1723: } /* end h */
1.128 brouard 1724: /* printf("\n H=%d \n",h); */
1.126 brouard 1725: return po;
1726: }
1727:
1.162 brouard 1728: #ifdef NLOPT
1729: double myfunc(unsigned n, const double *p1, double *grad, void *pd){
1730: double fret;
1731: double *xt;
1732: int j;
1733: myfunc_data *d2 = (myfunc_data *) pd;
1734: /* xt = (p1-1); */
1735: xt=vector(1,n);
1736: for (j=1;j<=n;j++) xt[j]=p1[j-1]; /* xt[1]=p1[0] */
1737:
1738: fret=(d2->function)(xt); /* p xt[1]@8 is fine */
1739: /* fret=(*func)(xt); /\* p xt[1]@8 is fine *\/ */
1740: printf("Function = %.12lf ",fret);
1741: for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]);
1742: printf("\n");
1743: free_vector(xt,1,n);
1744: return fret;
1745: }
1746: #endif
1.126 brouard 1747:
1748: /*************** log-likelihood *************/
1749: double func( double *x)
1750: {
1751: int i, ii, j, k, mi, d, kk;
1.131 brouard 1752: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 1753: double **out;
1754: double sw; /* Sum of weights */
1755: double lli; /* Individual log likelihood */
1756: int s1, s2;
1757: double bbh, survp;
1758: long ipmx;
1759: /*extern weight */
1760: /* We are differentiating ll according to initial status */
1761: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
1762: /*for(i=1;i<imx;i++)
1763: printf(" %d\n",s[4][i]);
1764: */
1.162 brouard 1765:
1766: ++countcallfunc;
1767:
1.126 brouard 1768: cov[1]=1.;
1769:
1770: for(k=1; k<=nlstate; k++) ll[k]=0.;
1771:
1772: if(mle==1){
1773: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138 brouard 1774: /* Computes the values of the ncovmodel covariates of the model
1775: depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
1776: Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
1777: to be observed in j being in i according to the model.
1778: */
1.145 brouard 1779: for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1780: cov[2+k]=covar[Tvar[k]][i];
1781: }
1.137 brouard 1782: /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4]
1.138 brouard 1783: is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]
1.137 brouard 1784: has been calculated etc */
1.126 brouard 1785: for(mi=1; mi<= wav[i]-1; mi++){
1786: for (ii=1;ii<=nlstate+ndeath;ii++)
1787: for (j=1;j<=nlstate+ndeath;j++){
1788: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1789: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1790: }
1791: for(d=0; d<dh[mi][i]; d++){
1792: newm=savm;
1793: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1794: for (kk=1; kk<=cptcovage;kk++) {
1.137 brouard 1795: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; /* Tage[kk] gives the data-covariate associated with age */
1.126 brouard 1796: }
1797: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1798: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1799: savm=oldm;
1800: oldm=newm;
1801: } /* end mult */
1802:
1803: /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
1804: /* But now since version 0.9 we anticipate for bias at large stepm.
1805: * If stepm is larger than one month (smallest stepm) and if the exact delay
1806: * (in months) between two waves is not a multiple of stepm, we rounded to
1807: * the nearest (and in case of equal distance, to the lowest) interval but now
1808: * we keep into memory the bias bh[mi][i] and also the previous matrix product
1809: * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
1810: * probability in order to take into account the bias as a fraction of the way
1811: * from savm to out if bh is negative or even beyond if bh is positive. bh varies
1812: * -stepm/2 to stepm/2 .
1813: * For stepm=1 the results are the same as for previous versions of Imach.
1814: * For stepm > 1 the results are less biased than in previous versions.
1815: */
1816: s1=s[mw[mi][i]][i];
1817: s2=s[mw[mi+1][i]][i];
1818: bbh=(double)bh[mi][i]/(double)stepm;
1819: /* bias bh is positive if real duration
1820: * is higher than the multiple of stepm and negative otherwise.
1821: */
1822: /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
1823: if( s2 > nlstate){
1824: /* i.e. if s2 is a death state and if the date of death is known
1825: then the contribution to the likelihood is the probability to
1826: die between last step unit time and current step unit time,
1827: which is also equal to probability to die before dh
1828: minus probability to die before dh-stepm .
1829: In version up to 0.92 likelihood was computed
1830: as if date of death was unknown. Death was treated as any other
1831: health state: the date of the interview describes the actual state
1832: and not the date of a change in health state. The former idea was
1833: to consider that at each interview the state was recorded
1834: (healthy, disable or death) and IMaCh was corrected; but when we
1835: introduced the exact date of death then we should have modified
1836: the contribution of an exact death to the likelihood. This new
1837: contribution is smaller and very dependent of the step unit
1838: stepm. It is no more the probability to die between last interview
1839: and month of death but the probability to survive from last
1840: interview up to one month before death multiplied by the
1841: probability to die within a month. Thanks to Chris
1842: Jackson for correcting this bug. Former versions increased
1843: mortality artificially. The bad side is that we add another loop
1844: which slows down the processing. The difference can be up to 10%
1845: lower mortality.
1846: */
1847: lli=log(out[s1][s2] - savm[s1][s2]);
1848:
1849:
1850: } else if (s2==-2) {
1851: for (j=1,survp=0. ; j<=nlstate; j++)
1852: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1853: /*survp += out[s1][j]; */
1854: lli= log(survp);
1855: }
1856:
1857: else if (s2==-4) {
1858: for (j=3,survp=0. ; j<=nlstate; j++)
1859: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1860: lli= log(survp);
1861: }
1862:
1863: else if (s2==-5) {
1864: for (j=1,survp=0. ; j<=2; j++)
1865: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1866: lli= log(survp);
1867: }
1868:
1869: else{
1870: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1871: /* 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 */
1872: }
1873: /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
1874: /*if(lli ==000.0)*/
1875: /*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); */
1876: ipmx +=1;
1877: sw += weight[i];
1878: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1879: } /* end of wave */
1880: } /* end of individual */
1881: } else if(mle==2){
1882: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1883: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1884: for(mi=1; mi<= wav[i]-1; mi++){
1885: for (ii=1;ii<=nlstate+ndeath;ii++)
1886: for (j=1;j<=nlstate+ndeath;j++){
1887: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1888: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1889: }
1890: for(d=0; d<=dh[mi][i]; d++){
1891: newm=savm;
1892: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1893: for (kk=1; kk<=cptcovage;kk++) {
1894: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1895: }
1896: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1897: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1898: savm=oldm;
1899: oldm=newm;
1900: } /* end mult */
1901:
1902: s1=s[mw[mi][i]][i];
1903: s2=s[mw[mi+1][i]][i];
1904: bbh=(double)bh[mi][i]/(double)stepm;
1905: 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 */
1906: ipmx +=1;
1907: sw += weight[i];
1908: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1909: } /* end of wave */
1910: } /* end of individual */
1911: } else if(mle==3){ /* exponential inter-extrapolation */
1912: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1913: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1914: for(mi=1; mi<= wav[i]-1; mi++){
1915: for (ii=1;ii<=nlstate+ndeath;ii++)
1916: for (j=1;j<=nlstate+ndeath;j++){
1917: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1918: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1919: }
1920: for(d=0; d<dh[mi][i]; d++){
1921: newm=savm;
1922: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1923: for (kk=1; kk<=cptcovage;kk++) {
1924: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1925: }
1926: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1927: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1928: savm=oldm;
1929: oldm=newm;
1930: } /* end mult */
1931:
1932: s1=s[mw[mi][i]][i];
1933: s2=s[mw[mi+1][i]][i];
1934: bbh=(double)bh[mi][i]/(double)stepm;
1935: 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 */
1936: ipmx +=1;
1937: sw += weight[i];
1938: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1939: } /* end of wave */
1940: } /* end of individual */
1941: }else if (mle==4){ /* ml=4 no inter-extrapolation */
1942: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1943: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1944: for(mi=1; mi<= wav[i]-1; mi++){
1945: for (ii=1;ii<=nlstate+ndeath;ii++)
1946: for (j=1;j<=nlstate+ndeath;j++){
1947: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1948: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1949: }
1950: for(d=0; d<dh[mi][i]; d++){
1951: newm=savm;
1952: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1953: for (kk=1; kk<=cptcovage;kk++) {
1954: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1955: }
1956:
1957: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1958: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1959: savm=oldm;
1960: oldm=newm;
1961: } /* end mult */
1962:
1963: s1=s[mw[mi][i]][i];
1964: s2=s[mw[mi+1][i]][i];
1965: if( s2 > nlstate){
1966: lli=log(out[s1][s2] - savm[s1][s2]);
1967: }else{
1968: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
1969: }
1970: ipmx +=1;
1971: sw += weight[i];
1972: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1973: /* 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]); */
1974: } /* end of wave */
1975: } /* end of individual */
1976: }else{ /* ml=5 no inter-extrapolation no jackson =0.8a */
1977: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1978: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1979: for(mi=1; mi<= wav[i]-1; mi++){
1980: for (ii=1;ii<=nlstate+ndeath;ii++)
1981: for (j=1;j<=nlstate+ndeath;j++){
1982: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1983: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1984: }
1985: for(d=0; d<dh[mi][i]; d++){
1986: newm=savm;
1987: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1988: for (kk=1; kk<=cptcovage;kk++) {
1989: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1990: }
1991:
1992: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1993: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1994: savm=oldm;
1995: oldm=newm;
1996: } /* end mult */
1997:
1998: s1=s[mw[mi][i]][i];
1999: s2=s[mw[mi+1][i]][i];
2000: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2001: ipmx +=1;
2002: sw += weight[i];
2003: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2004: /*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]);*/
2005: } /* end of wave */
2006: } /* end of individual */
2007: } /* End of if */
2008: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2009: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2010: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2011: return -l;
2012: }
2013:
2014: /*************** log-likelihood *************/
2015: double funcone( double *x)
2016: {
2017: /* Same as likeli but slower because of a lot of printf and if */
2018: int i, ii, j, k, mi, d, kk;
1.131 brouard 2019: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 2020: double **out;
2021: double lli; /* Individual log likelihood */
2022: double llt;
2023: int s1, s2;
2024: double bbh, survp;
2025: /*extern weight */
2026: /* We are differentiating ll according to initial status */
2027: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2028: /*for(i=1;i<imx;i++)
2029: printf(" %d\n",s[4][i]);
2030: */
2031: cov[1]=1.;
2032:
2033: for(k=1; k<=nlstate; k++) ll[k]=0.;
2034:
2035: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2036: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2037: for(mi=1; mi<= wav[i]-1; mi++){
2038: for (ii=1;ii<=nlstate+ndeath;ii++)
2039: for (j=1;j<=nlstate+ndeath;j++){
2040: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2041: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2042: }
2043: for(d=0; d<dh[mi][i]; d++){
2044: newm=savm;
2045: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2046: for (kk=1; kk<=cptcovage;kk++) {
2047: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2048: }
1.145 brouard 2049: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126 brouard 2050: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2051: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145 brouard 2052: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
2053: /* 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126 brouard 2054: savm=oldm;
2055: oldm=newm;
2056: } /* end mult */
2057:
2058: s1=s[mw[mi][i]][i];
2059: s2=s[mw[mi+1][i]][i];
2060: bbh=(double)bh[mi][i]/(double)stepm;
2061: /* bias is positive if real duration
2062: * is higher than the multiple of stepm and negative otherwise.
2063: */
2064: if( s2 > nlstate && (mle <5) ){ /* Jackson */
2065: lli=log(out[s1][s2] - savm[s1][s2]);
2066: } else if (s2==-2) {
2067: for (j=1,survp=0. ; j<=nlstate; j++)
2068: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2069: lli= log(survp);
2070: }else if (mle==1){
2071: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2072: } else if(mle==2){
2073: 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 */
2074: } else if(mle==3){ /* exponential inter-extrapolation */
2075: 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 */
2076: } else if (mle==4){ /* mle=4 no inter-extrapolation */
2077: lli=log(out[s1][s2]); /* Original formula */
1.136 brouard 2078: } else{ /* mle=0 back to 1 */
2079: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2080: /*lli=log(out[s1][s2]); */ /* Original formula */
1.126 brouard 2081: } /* End of if */
2082: ipmx +=1;
2083: sw += weight[i];
2084: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132 brouard 2085: /*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 2086: if(globpr){
1.141 brouard 2087: fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
1.126 brouard 2088: %11.6f %11.6f %11.6f ", \
2089: num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
2090: 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
2091: for(k=1,llt=0.,l=0.; k<=nlstate; k++){
2092: llt +=ll[k]*gipmx/gsw;
2093: fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
2094: }
2095: fprintf(ficresilk," %10.6f\n", -llt);
2096: }
2097: } /* end of wave */
2098: } /* end of individual */
2099: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2100: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2101: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2102: if(globpr==0){ /* First time we count the contributions and weights */
2103: gipmx=ipmx;
2104: gsw=sw;
2105: }
2106: return -l;
2107: }
2108:
2109:
2110: /*************** function likelione ***********/
2111: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
2112: {
2113: /* This routine should help understanding what is done with
2114: the selection of individuals/waves and
2115: to check the exact contribution to the likelihood.
2116: Plotting could be done.
2117: */
2118: int k;
2119:
2120: if(*globpri !=0){ /* Just counts and sums, no printings */
2121: strcpy(fileresilk,"ilk");
2122: strcat(fileresilk,fileres);
2123: if((ficresilk=fopen(fileresilk,"w"))==NULL) {
2124: printf("Problem with resultfile: %s\n", fileresilk);
2125: fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
2126: }
2127: 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");
2128: fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
2129: /* i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
2130: for(k=1; k<=nlstate; k++)
2131: fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
2132: fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
2133: }
2134:
2135: *fretone=(*funcone)(p);
2136: if(*globpri !=0){
2137: fclose(ficresilk);
2138: fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
2139: fflush(fichtm);
2140: }
2141: return;
2142: }
2143:
2144:
2145: /*********** Maximum Likelihood Estimation ***************/
2146:
2147: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
2148: {
1.165 ! brouard 2149: int i,j, iter=0;
1.126 brouard 2150: double **xi;
2151: double fret;
2152: double fretone; /* Only one call to likelihood */
2153: /* char filerespow[FILENAMELENGTH];*/
1.162 brouard 2154:
2155: #ifdef NLOPT
2156: int creturn;
2157: nlopt_opt opt;
2158: /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
2159: double *lb;
2160: double minf; /* the minimum objective value, upon return */
2161: double * p1; /* Shifted parameters from 0 instead of 1 */
2162: myfunc_data dinst, *d = &dinst;
2163: #endif
2164:
2165:
1.126 brouard 2166: xi=matrix(1,npar,1,npar);
2167: for (i=1;i<=npar;i++)
2168: for (j=1;j<=npar;j++)
2169: xi[i][j]=(i==j ? 1.0 : 0.0);
2170: printf("Powell\n"); fprintf(ficlog,"Powell\n");
2171: strcpy(filerespow,"pow");
2172: strcat(filerespow,fileres);
2173: if((ficrespow=fopen(filerespow,"w"))==NULL) {
2174: printf("Problem with resultfile: %s\n", filerespow);
2175: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
2176: }
2177: fprintf(ficrespow,"# Powell\n# iter -2*LL");
2178: for (i=1;i<=nlstate;i++)
2179: for(j=1;j<=nlstate+ndeath;j++)
2180: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
2181: fprintf(ficrespow,"\n");
1.162 brouard 2182: #ifdef POWELL
1.126 brouard 2183: powell(p,xi,npar,ftol,&iter,&fret,func);
1.162 brouard 2184: #endif
1.126 brouard 2185:
1.162 brouard 2186: #ifdef NLOPT
2187: #ifdef NEWUOA
2188: opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
2189: #else
2190: opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
2191: #endif
2192: lb=vector(0,npar-1);
2193: for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
2194: nlopt_set_lower_bounds(opt, lb);
2195: nlopt_set_initial_step1(opt, 0.1);
2196:
2197: p1= (p+1); /* p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
2198: d->function = func;
2199: printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
2200: nlopt_set_min_objective(opt, myfunc, d);
2201: nlopt_set_xtol_rel(opt, ftol);
2202: if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
2203: printf("nlopt failed! %d\n",creturn);
2204: }
2205: else {
2206: printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
2207: printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
2208: iter=1; /* not equal */
2209: }
2210: nlopt_destroy(opt);
2211: #endif
1.126 brouard 2212: free_matrix(xi,1,npar,1,npar);
2213: fclose(ficrespow);
1.162 brouard 2214: printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2215: fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2216: fprintf(ficres,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126 brouard 2217:
2218: }
2219:
2220: /**** Computes Hessian and covariance matrix ***/
2221: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
2222: {
2223: double **a,**y,*x,pd;
2224: double **hess;
1.164 brouard 2225: int i, j;
1.126 brouard 2226: int *indx;
2227:
2228: double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
2229: double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
2230: void lubksb(double **a, int npar, int *indx, double b[]) ;
2231: void ludcmp(double **a, int npar, int *indx, double *d) ;
2232: double gompertz(double p[]);
2233: hess=matrix(1,npar,1,npar);
2234:
2235: printf("\nCalculation of the hessian matrix. Wait...\n");
2236: fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
2237: for (i=1;i<=npar;i++){
2238: printf("%d",i);fflush(stdout);
2239: fprintf(ficlog,"%d",i);fflush(ficlog);
2240:
2241: hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
2242:
2243: /* printf(" %f ",p[i]);
2244: printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
2245: }
2246:
2247: for (i=1;i<=npar;i++) {
2248: for (j=1;j<=npar;j++) {
2249: if (j>i) {
2250: printf(".%d%d",i,j);fflush(stdout);
2251: fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
2252: hess[i][j]=hessij(p,delti,i,j,func,npar);
2253:
2254: hess[j][i]=hess[i][j];
2255: /*printf(" %lf ",hess[i][j]);*/
2256: }
2257: }
2258: }
2259: printf("\n");
2260: fprintf(ficlog,"\n");
2261:
2262: printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
2263: fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
2264:
2265: a=matrix(1,npar,1,npar);
2266: y=matrix(1,npar,1,npar);
2267: x=vector(1,npar);
2268: indx=ivector(1,npar);
2269: for (i=1;i<=npar;i++)
2270: for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
2271: ludcmp(a,npar,indx,&pd);
2272:
2273: for (j=1;j<=npar;j++) {
2274: for (i=1;i<=npar;i++) x[i]=0;
2275: x[j]=1;
2276: lubksb(a,npar,indx,x);
2277: for (i=1;i<=npar;i++){
2278: matcov[i][j]=x[i];
2279: }
2280: }
2281:
2282: printf("\n#Hessian matrix#\n");
2283: fprintf(ficlog,"\n#Hessian matrix#\n");
2284: for (i=1;i<=npar;i++) {
2285: for (j=1;j<=npar;j++) {
2286: printf("%.3e ",hess[i][j]);
2287: fprintf(ficlog,"%.3e ",hess[i][j]);
2288: }
2289: printf("\n");
2290: fprintf(ficlog,"\n");
2291: }
2292:
2293: /* Recompute Inverse */
2294: for (i=1;i<=npar;i++)
2295: for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
2296: ludcmp(a,npar,indx,&pd);
2297:
2298: /* printf("\n#Hessian matrix recomputed#\n");
2299:
2300: for (j=1;j<=npar;j++) {
2301: for (i=1;i<=npar;i++) x[i]=0;
2302: x[j]=1;
2303: lubksb(a,npar,indx,x);
2304: for (i=1;i<=npar;i++){
2305: y[i][j]=x[i];
2306: printf("%.3e ",y[i][j]);
2307: fprintf(ficlog,"%.3e ",y[i][j]);
2308: }
2309: printf("\n");
2310: fprintf(ficlog,"\n");
2311: }
2312: */
2313:
2314: free_matrix(a,1,npar,1,npar);
2315: free_matrix(y,1,npar,1,npar);
2316: free_vector(x,1,npar);
2317: free_ivector(indx,1,npar);
2318: free_matrix(hess,1,npar,1,npar);
2319:
2320:
2321: }
2322:
2323: /*************** hessian matrix ****************/
2324: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
2325: {
2326: int i;
2327: int l=1, lmax=20;
2328: double k1,k2;
1.132 brouard 2329: double p2[MAXPARM+1]; /* identical to x */
1.126 brouard 2330: double res;
2331: double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
2332: double fx;
2333: int k=0,kmax=10;
2334: double l1;
2335:
2336: fx=func(x);
2337: for (i=1;i<=npar;i++) p2[i]=x[i];
1.145 brouard 2338: for(l=0 ; l <=lmax; l++){ /* Enlarging the zone around the Maximum */
1.126 brouard 2339: l1=pow(10,l);
2340: delts=delt;
2341: for(k=1 ; k <kmax; k=k+1){
2342: delt = delta*(l1*k);
2343: p2[theta]=x[theta] +delt;
1.145 brouard 2344: k1=func(p2)-fx; /* Might be negative if too close to the theoretical maximum */
1.126 brouard 2345: p2[theta]=x[theta]-delt;
2346: k2=func(p2)-fx;
2347: /*res= (k1-2.0*fx+k2)/delt/delt; */
2348: res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
2349:
1.132 brouard 2350: #ifdef DEBUGHESS
1.126 brouard 2351: 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);
2352: 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);
2353: #endif
2354: /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
2355: if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
2356: k=kmax;
2357: }
2358: else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164 brouard 2359: k=kmax; l=lmax*10;
1.126 brouard 2360: }
2361: else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
2362: delts=delt;
2363: }
2364: }
2365: }
2366: delti[theta]=delts;
2367: return res;
2368:
2369: }
2370:
2371: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
2372: {
2373: int i;
1.164 brouard 2374: int l=1, lmax=20;
1.126 brouard 2375: double k1,k2,k3,k4,res,fx;
1.132 brouard 2376: double p2[MAXPARM+1];
1.126 brouard 2377: int k;
2378:
2379: fx=func(x);
2380: for (k=1; k<=2; k++) {
2381: for (i=1;i<=npar;i++) p2[i]=x[i];
2382: p2[thetai]=x[thetai]+delti[thetai]/k;
2383: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2384: k1=func(p2)-fx;
2385:
2386: p2[thetai]=x[thetai]+delti[thetai]/k;
2387: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2388: k2=func(p2)-fx;
2389:
2390: p2[thetai]=x[thetai]-delti[thetai]/k;
2391: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2392: k3=func(p2)-fx;
2393:
2394: p2[thetai]=x[thetai]-delti[thetai]/k;
2395: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2396: k4=func(p2)-fx;
2397: res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
2398: #ifdef DEBUG
2399: 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);
2400: 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);
2401: #endif
2402: }
2403: return res;
2404: }
2405:
2406: /************** Inverse of matrix **************/
2407: void ludcmp(double **a, int n, int *indx, double *d)
2408: {
2409: int i,imax,j,k;
2410: double big,dum,sum,temp;
2411: double *vv;
2412:
2413: vv=vector(1,n);
2414: *d=1.0;
2415: for (i=1;i<=n;i++) {
2416: big=0.0;
2417: for (j=1;j<=n;j++)
2418: if ((temp=fabs(a[i][j])) > big) big=temp;
2419: if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
2420: vv[i]=1.0/big;
2421: }
2422: for (j=1;j<=n;j++) {
2423: for (i=1;i<j;i++) {
2424: sum=a[i][j];
2425: for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
2426: a[i][j]=sum;
2427: }
2428: big=0.0;
2429: for (i=j;i<=n;i++) {
2430: sum=a[i][j];
2431: for (k=1;k<j;k++)
2432: sum -= a[i][k]*a[k][j];
2433: a[i][j]=sum;
2434: if ( (dum=vv[i]*fabs(sum)) >= big) {
2435: big=dum;
2436: imax=i;
2437: }
2438: }
2439: if (j != imax) {
2440: for (k=1;k<=n;k++) {
2441: dum=a[imax][k];
2442: a[imax][k]=a[j][k];
2443: a[j][k]=dum;
2444: }
2445: *d = -(*d);
2446: vv[imax]=vv[j];
2447: }
2448: indx[j]=imax;
2449: if (a[j][j] == 0.0) a[j][j]=TINY;
2450: if (j != n) {
2451: dum=1.0/(a[j][j]);
2452: for (i=j+1;i<=n;i++) a[i][j] *= dum;
2453: }
2454: }
2455: free_vector(vv,1,n); /* Doesn't work */
2456: ;
2457: }
2458:
2459: void lubksb(double **a, int n, int *indx, double b[])
2460: {
2461: int i,ii=0,ip,j;
2462: double sum;
2463:
2464: for (i=1;i<=n;i++) {
2465: ip=indx[i];
2466: sum=b[ip];
2467: b[ip]=b[i];
2468: if (ii)
2469: for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
2470: else if (sum) ii=i;
2471: b[i]=sum;
2472: }
2473: for (i=n;i>=1;i--) {
2474: sum=b[i];
2475: for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
2476: b[i]=sum/a[i][i];
2477: }
2478: }
2479:
2480: void pstamp(FILE *fichier)
2481: {
2482: fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
2483: }
2484:
2485: /************ Frequencies ********************/
2486: 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[])
2487: { /* Some frequencies */
2488:
1.164 brouard 2489: int i, m, jk, j1, bool, z1,j;
1.126 brouard 2490: int first;
2491: double ***freq; /* Frequencies */
2492: double *pp, **prop;
2493: double pos,posprop, k2, dateintsum=0,k2cpt=0;
2494: char fileresp[FILENAMELENGTH];
2495:
2496: pp=vector(1,nlstate);
2497: prop=matrix(1,nlstate,iagemin,iagemax+3);
2498: strcpy(fileresp,"p");
2499: strcat(fileresp,fileres);
2500: if((ficresp=fopen(fileresp,"w"))==NULL) {
2501: printf("Problem with prevalence resultfile: %s\n", fileresp);
2502: fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
2503: exit(0);
2504: }
2505: freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
2506: j1=0;
2507:
2508: j=cptcoveff;
2509: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2510:
2511: first=1;
2512:
1.145 brouard 2513: /* for(k1=1; k1<=j ; k1++){ /* Loop on covariates */
2514: /* for(i1=1; i1<=ncodemax[k1];i1++){ /* Now it is 2 */
2515: /* j1++;
2516: */
2517: for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126 brouard 2518: /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
2519: scanf("%d", i);*/
2520: for (i=-5; i<=nlstate+ndeath; i++)
2521: for (jk=-5; jk<=nlstate+ndeath; jk++)
2522: for(m=iagemin; m <= iagemax+3; m++)
2523: freq[i][jk][m]=0;
1.143 brouard 2524:
2525: for (i=1; i<=nlstate; i++)
2526: for(m=iagemin; m <= iagemax+3; m++)
2527: prop[i][m]=0;
1.126 brouard 2528:
2529: dateintsum=0;
2530: k2cpt=0;
2531: for (i=1; i<=imx; i++) {
2532: bool=1;
1.144 brouard 2533: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
2534: for (z1=1; z1<=cptcoveff; z1++)
2535: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
1.145 brouard 2536: /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144 brouard 2537: bool=0;
1.145 brouard 2538: /* 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",
2539: bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
2540: j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
1.144 brouard 2541: /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
2542: }
1.126 brouard 2543: }
1.144 brouard 2544:
1.126 brouard 2545: if (bool==1){
2546: for(m=firstpass; m<=lastpass; m++){
2547: k2=anint[m][i]+(mint[m][i]/12.);
2548: /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
2549: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2550: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2551: if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
2552: if (m<lastpass) {
2553: freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
2554: freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
2555: }
2556:
2557: if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
2558: dateintsum=dateintsum+k2;
2559: k2cpt++;
2560: }
2561: /*}*/
2562: }
2563: }
1.145 brouard 2564: } /* end i */
1.126 brouard 2565:
2566: /* fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
2567: pstamp(ficresp);
2568: if (cptcovn>0) {
2569: fprintf(ficresp, "\n#********** Variable ");
2570: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2571: fprintf(ficresp, "**********\n#");
1.143 brouard 2572: fprintf(ficlog, "\n#********** Variable ");
2573: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2574: fprintf(ficlog, "**********\n#");
1.126 brouard 2575: }
2576: for(i=1; i<=nlstate;i++)
2577: fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
2578: fprintf(ficresp, "\n");
2579:
2580: for(i=iagemin; i <= iagemax+3; i++){
2581: if(i==iagemax+3){
2582: fprintf(ficlog,"Total");
2583: }else{
2584: if(first==1){
2585: first=0;
2586: printf("See log file for details...\n");
2587: }
2588: fprintf(ficlog,"Age %d", i);
2589: }
2590: for(jk=1; jk <=nlstate ; jk++){
2591: for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
2592: pp[jk] += freq[jk][m][i];
2593: }
2594: for(jk=1; jk <=nlstate ; jk++){
2595: for(m=-1, pos=0; m <=0 ; m++)
2596: pos += freq[jk][m][i];
2597: if(pp[jk]>=1.e-10){
2598: if(first==1){
1.132 brouard 2599: printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126 brouard 2600: }
2601: fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
2602: }else{
2603: if(first==1)
2604: printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2605: fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2606: }
2607: }
2608:
2609: for(jk=1; jk <=nlstate ; jk++){
2610: for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
2611: pp[jk] += freq[jk][m][i];
2612: }
2613: for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
2614: pos += pp[jk];
2615: posprop += prop[jk][i];
2616: }
2617: for(jk=1; jk <=nlstate ; jk++){
2618: if(pos>=1.e-5){
2619: if(first==1)
2620: printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2621: fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2622: }else{
2623: if(first==1)
2624: printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2625: fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2626: }
2627: if( i <= iagemax){
2628: if(pos>=1.e-5){
2629: fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
2630: /*probs[i][jk][j1]= pp[jk]/pos;*/
2631: /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
2632: }
2633: else
2634: fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
2635: }
2636: }
2637:
2638: for(jk=-1; jk <=nlstate+ndeath; jk++)
2639: for(m=-1; m <=nlstate+ndeath; m++)
2640: if(freq[jk][m][i] !=0 ) {
2641: if(first==1)
2642: printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
2643: fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
2644: }
2645: if(i <= iagemax)
2646: fprintf(ficresp,"\n");
2647: if(first==1)
2648: printf("Others in log...\n");
2649: fprintf(ficlog,"\n");
2650: }
1.145 brouard 2651: /*}*/
1.126 brouard 2652: }
2653: dateintmean=dateintsum/k2cpt;
2654:
2655: fclose(ficresp);
2656: free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
2657: free_vector(pp,1,nlstate);
2658: free_matrix(prop,1,nlstate,iagemin, iagemax+3);
2659: /* End of Freq */
2660: }
2661:
2662: /************ Prevalence ********************/
2663: 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)
2664: {
2665: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
2666: in each health status at the date of interview (if between dateprev1 and dateprev2).
2667: We still use firstpass and lastpass as another selection.
2668: */
2669:
1.164 brouard 2670: int i, m, jk, j1, bool, z1,j;
2671:
2672: double **prop;
2673: double posprop;
1.126 brouard 2674: double y2; /* in fractional years */
2675: int iagemin, iagemax;
1.145 brouard 2676: int first; /** to stop verbosity which is redirected to log file */
1.126 brouard 2677:
2678: iagemin= (int) agemin;
2679: iagemax= (int) agemax;
2680: /*pp=vector(1,nlstate);*/
2681: prop=matrix(1,nlstate,iagemin,iagemax+3);
2682: /* freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
2683: j1=0;
2684:
1.145 brouard 2685: /*j=cptcoveff;*/
1.126 brouard 2686: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2687:
1.145 brouard 2688: first=1;
2689: for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
2690: /*for(i1=1; i1<=ncodemax[k1];i1++){
2691: j1++;*/
1.126 brouard 2692:
2693: for (i=1; i<=nlstate; i++)
2694: for(m=iagemin; m <= iagemax+3; m++)
2695: prop[i][m]=0.0;
2696:
2697: for (i=1; i<=imx; i++) { /* Each individual */
2698: bool=1;
2699: if (cptcovn>0) {
2700: for (z1=1; z1<=cptcoveff; z1++)
2701: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
2702: bool=0;
2703: }
2704: if (bool==1) {
2705: for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
2706: y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
2707: if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
2708: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2709: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2710: 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);
2711: if (s[m][i]>0 && s[m][i]<=nlstate) {
2712: /*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]]);*/
2713: prop[s[m][i]][(int)agev[m][i]] += weight[i];
2714: prop[s[m][i]][iagemax+3] += weight[i];
2715: }
2716: }
2717: } /* end selection of waves */
2718: }
2719: }
2720: for(i=iagemin; i <= iagemax+3; i++){
2721: for(jk=1,posprop=0; jk <=nlstate ; jk++) {
2722: posprop += prop[jk][i];
2723: }
1.145 brouard 2724:
1.126 brouard 2725: for(jk=1; jk <=nlstate ; jk++){
2726: if( i <= iagemax){
2727: if(posprop>=1.e-5){
2728: probs[i][jk][j1]= prop[jk][i]/posprop;
1.145 brouard 2729: } else{
2730: if(first==1){
2731: first=0;
2732: 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]);
2733: }
2734: }
1.126 brouard 2735: }
2736: }/* end jk */
2737: }/* end i */
1.145 brouard 2738: /*} *//* end i1 */
2739: } /* end j1 */
1.126 brouard 2740:
2741: /* free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
2742: /*free_vector(pp,1,nlstate);*/
2743: free_matrix(prop,1,nlstate, iagemin,iagemax+3);
2744: } /* End of prevalence */
2745:
2746: /************* Waves Concatenation ***************/
2747:
2748: 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)
2749: {
2750: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
2751: Death is a valid wave (if date is known).
2752: mw[mi][i] is the mi (mi=1 to wav[i]) effective wave of individual i
2753: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
2754: and mw[mi+1][i]. dh depends on stepm.
2755: */
2756:
2757: int i, mi, m;
2758: /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
2759: double sum=0., jmean=0.;*/
2760: int first;
2761: int j, k=0,jk, ju, jl;
2762: double sum=0.;
2763: first=0;
1.164 brouard 2764: jmin=100000;
1.126 brouard 2765: jmax=-1;
2766: jmean=0.;
2767: for(i=1; i<=imx; i++){
2768: mi=0;
2769: m=firstpass;
2770: while(s[m][i] <= nlstate){
2771: if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
2772: mw[++mi][i]=m;
2773: if(m >=lastpass)
2774: break;
2775: else
2776: m++;
2777: }/* end while */
2778: if (s[m][i] > nlstate){
2779: mi++; /* Death is another wave */
2780: /* if(mi==0) never been interviewed correctly before death */
2781: /* Only death is a correct wave */
2782: mw[mi][i]=m;
2783: }
2784:
2785: wav[i]=mi;
2786: if(mi==0){
2787: nbwarn++;
2788: if(first==0){
2789: printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
2790: first=1;
2791: }
2792: if(first==1){
2793: fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
2794: }
2795: } /* end mi==0 */
2796: } /* End individuals */
2797:
2798: for(i=1; i<=imx; i++){
2799: for(mi=1; mi<wav[i];mi++){
2800: if (stepm <=0)
2801: dh[mi][i]=1;
2802: else{
2803: if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
2804: if (agedc[i] < 2*AGESUP) {
2805: j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
2806: if(j==0) j=1; /* Survives at least one month after exam */
2807: else if(j<0){
2808: nberr++;
2809: 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]);
2810: j=1; /* Temporary Dangerous patch */
2811: 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);
2812: 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]);
2813: 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);
2814: }
2815: k=k+1;
2816: if (j >= jmax){
2817: jmax=j;
2818: ijmax=i;
2819: }
2820: if (j <= jmin){
2821: jmin=j;
2822: ijmin=i;
2823: }
2824: sum=sum+j;
2825: /*if (j<0) printf("j=%d num=%d \n",j,i);*/
2826: /* printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
2827: }
2828: }
2829: else{
2830: j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
2831: /* 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]); */
2832:
2833: k=k+1;
2834: if (j >= jmax) {
2835: jmax=j;
2836: ijmax=i;
2837: }
2838: else if (j <= jmin){
2839: jmin=j;
2840: ijmin=i;
2841: }
2842: /* if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
2843: /*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]);*/
2844: if(j<0){
2845: nberr++;
2846: 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]);
2847: 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]);
2848: }
2849: sum=sum+j;
2850: }
2851: jk= j/stepm;
2852: jl= j -jk*stepm;
2853: ju= j -(jk+1)*stepm;
2854: if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
2855: if(jl==0){
2856: dh[mi][i]=jk;
2857: bh[mi][i]=0;
2858: }else{ /* We want a negative bias in order to only have interpolation ie
1.136 brouard 2859: * to avoid the price of an extra matrix product in likelihood */
1.126 brouard 2860: dh[mi][i]=jk+1;
2861: bh[mi][i]=ju;
2862: }
2863: }else{
2864: if(jl <= -ju){
2865: dh[mi][i]=jk;
2866: bh[mi][i]=jl; /* bias is positive if real duration
2867: * is higher than the multiple of stepm and negative otherwise.
2868: */
2869: }
2870: else{
2871: dh[mi][i]=jk+1;
2872: bh[mi][i]=ju;
2873: }
2874: if(dh[mi][i]==0){
2875: dh[mi][i]=1; /* At least one step */
2876: bh[mi][i]=ju; /* At least one step */
2877: /* 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);*/
2878: }
2879: } /* end if mle */
2880: }
2881: } /* end wave */
2882: }
2883: jmean=sum/k;
2884: 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 2885: 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 2886: }
2887:
2888: /*********** Tricode ****************************/
1.145 brouard 2889: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126 brouard 2890: {
1.144 brouard 2891: /**< Uses cptcovn+2*cptcovprod as the number of covariates */
2892: /* Tvar[i]=atoi(stre); find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1
2893: /* Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145 brouard 2894: * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
2895: /* nbcode[Tvar[j]][1]=
1.144 brouard 2896: */
1.130 brouard 2897:
1.145 brouard 2898: int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136 brouard 2899: int modmaxcovj=0; /* Modality max of covariates j */
1.145 brouard 2900: int cptcode=0; /* Modality max of covariates j */
2901: int modmincovj=0; /* Modality min of covariates j */
2902:
2903:
1.126 brouard 2904: cptcoveff=0;
2905:
1.145 brouard 2906: for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.144 brouard 2907: for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126 brouard 2908:
1.145 brouard 2909: /* Loop on covariates without age and products */
2910: for (j=1; j<=(cptcovs); j++) { /* model V1 + V2*age+ V3 + V3*V4 : V1 + V3 = 2 only */
2911: for (i=1; i<=imx; i++) { /* Lopp on individuals: reads the data file to get the maximum value of the
1.136 brouard 2912: modality of this covariate Vj*/
1.145 brouard 2913: ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
2914: * If product of Vn*Vm, still boolean *:
2915: * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
2916: * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0 */
2917: /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136 brouard 2918: modality of the nth covariate of individual i. */
1.145 brouard 2919: if (ij > modmaxcovj)
2920: modmaxcovj=ij;
2921: else if (ij < modmincovj)
2922: modmincovj=ij;
2923: if ((ij < -1) && (ij > NCOVMAX)){
2924: printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
2925: exit(1);
2926: }else
1.136 brouard 2927: Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145 brouard 2928: /* If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126 brouard 2929: /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136 brouard 2930: /* getting the maximum value of the modality of the covariate
2931: (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
2932: female is 1, then modmaxcovj=1.*/
1.126 brouard 2933: }
1.145 brouard 2934: printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
2935: cptcode=modmaxcovj;
1.137 brouard 2936: /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145 brouard 2937: /*for (i=0; i<=cptcode; i++) {*/
2938: for (i=modmincovj; i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
2939: printf("Frequencies of covariates %d V%d %d\n", j, Tvar[j], Ndum[i]);
2940: if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
2941: ncodemax[j]++; /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
2942: }
2943: /* In fact ncodemax[j]=2 (dichotom. variables only) but it could be more for
2944: historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131 brouard 2945: } /* Ndum[-1] number of undefined modalities */
1.126 brouard 2946:
1.136 brouard 2947: /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.145 brouard 2948: /* For covariate j, modalities could be 1, 2, 3, 4. If Ndum[2]=0 ncodemax[j] is not 4 but 3 */
2949: /* If Ndum[3}= 635; Ndum[4]=0; Ndum[5]=0; Ndum[6]=27; Ndum[7]=125;
2950: modmincovj=3; modmaxcovj = 7;
2951: There are only 3 modalities non empty (or 2 if 27 is too few) : ncodemax[j]=3;
2952: which will be coded 0, 1, 2 which in binary on 3-1 digits are 0=00 1=01, 2=10; defining two dummy
2953: variables V1_1 and V1_2.
2954: nbcode[Tvar[j]][ij]=k;
2955: nbcode[Tvar[j]][1]=0;
2956: nbcode[Tvar[j]][2]=1;
2957: nbcode[Tvar[j]][3]=2;
2958: */
2959: ij=1; /* ij is similar to i but can jumps over null modalities */
2960: for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
2961: for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
2962: /*recode from 0 */
1.131 brouard 2963: if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
2964: nbcode[Tvar[j]][ij]=k; /* stores the modality in an array nbcode.
2965: k is a modality. If we have model=V1+V1*sex
2966: then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
1.126 brouard 2967: ij++;
2968: }
2969: if (ij > ncodemax[j]) break;
1.137 brouard 2970: } /* end of loop on */
2971: } /* end of loop on modality */
2972: } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/
2973:
1.145 brouard 2974: for (k=-1; k< maxncov; k++) Ndum[k]=0;
1.137 brouard 2975:
1.145 brouard 2976: for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */
2977: /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
2978: ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
2979: Ndum[ij]++;
2980: }
1.126 brouard 2981:
2982: ij=1;
1.145 brouard 2983: for (i=0; i<= maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
2984: /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126 brouard 2985: if((Ndum[i]!=0) && (i<=ncovcol)){
1.145 brouard 2986: /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
2987: Tvaraff[ij]=i; /*For printing (unclear) */
1.126 brouard 2988: ij++;
1.145 brouard 2989: }else
2990: Tvaraff[ij]=0;
1.126 brouard 2991: }
1.131 brouard 2992: ij--;
1.144 brouard 2993: cptcoveff=ij; /*Number of total covariates*/
1.145 brouard 2994:
1.126 brouard 2995: }
2996:
1.145 brouard 2997:
1.126 brouard 2998: /*********** Health Expectancies ****************/
2999:
1.127 brouard 3000: 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 3001:
3002: {
3003: /* Health expectancies, no variances */
1.164 brouard 3004: int i, j, nhstepm, hstepm, h, nstepm;
1.126 brouard 3005: int nhstepma, nstepma; /* Decreasing with age */
3006: double age, agelim, hf;
3007: double ***p3mat;
3008: double eip;
3009:
3010: pstamp(ficreseij);
3011: fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
3012: fprintf(ficreseij,"# Age");
3013: for(i=1; i<=nlstate;i++){
3014: for(j=1; j<=nlstate;j++){
3015: fprintf(ficreseij," e%1d%1d ",i,j);
3016: }
3017: fprintf(ficreseij," e%1d. ",i);
3018: }
3019: fprintf(ficreseij,"\n");
3020:
3021:
3022: if(estepm < stepm){
3023: printf ("Problem %d lower than %d\n",estepm, stepm);
3024: }
3025: else hstepm=estepm;
3026: /* We compute the life expectancy from trapezoids spaced every estepm months
3027: * This is mainly to measure the difference between two models: for example
3028: * if stepm=24 months pijx are given only every 2 years and by summing them
3029: * we are calculating an estimate of the Life Expectancy assuming a linear
3030: * progression in between and thus overestimating or underestimating according
3031: * to the curvature of the survival function. If, for the same date, we
3032: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3033: * to compare the new estimate of Life expectancy with the same linear
3034: * hypothesis. A more precise result, taking into account a more precise
3035: * curvature will be obtained if estepm is as small as stepm. */
3036:
3037: /* For example we decided to compute the life expectancy with the smallest unit */
3038: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3039: nhstepm is the number of hstepm from age to agelim
3040: nstepm is the number of stepm from age to agelin.
3041: Look at hpijx to understand the reason of that which relies in memory size
3042: and note for a fixed period like estepm months */
3043: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3044: survival function given by stepm (the optimization length). Unfortunately it
3045: means that if the survival funtion is printed only each two years of age and if
3046: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3047: results. So we changed our mind and took the option of the best precision.
3048: */
3049: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3050:
3051: agelim=AGESUP;
3052: /* If stepm=6 months */
3053: /* Computed by stepm unit matrices, product of hstepm matrices, stored
3054: in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
3055:
3056: /* nhstepm age range expressed in number of stepm */
3057: nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3058: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3059: /* if (stepm >= YEARM) hstepm=1;*/
3060: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3061: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3062:
3063: for (age=bage; age<=fage; age ++){
3064: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3065: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3066: /* if (stepm >= YEARM) hstepm=1;*/
3067: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3068:
3069: /* If stepm=6 months */
3070: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3071: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3072:
3073: hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3074:
3075: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3076:
3077: printf("%d|",(int)age);fflush(stdout);
3078: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3079:
3080: /* Computing expectancies */
3081: for(i=1; i<=nlstate;i++)
3082: for(j=1; j<=nlstate;j++)
3083: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3084: eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
3085:
3086: /* 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]);*/
3087:
3088: }
3089:
3090: fprintf(ficreseij,"%3.0f",age );
3091: for(i=1; i<=nlstate;i++){
3092: eip=0;
3093: for(j=1; j<=nlstate;j++){
3094: eip +=eij[i][j][(int)age];
3095: fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
3096: }
3097: fprintf(ficreseij,"%9.4f", eip );
3098: }
3099: fprintf(ficreseij,"\n");
3100:
3101: }
3102: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3103: printf("\n");
3104: fprintf(ficlog,"\n");
3105:
3106: }
3107:
1.127 brouard 3108: 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 3109:
3110: {
3111: /* Covariances of health expectancies eij and of total life expectancies according
3112: to initial status i, ei. .
3113: */
3114: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
3115: int nhstepma, nstepma; /* Decreasing with age */
3116: double age, agelim, hf;
3117: double ***p3matp, ***p3matm, ***varhe;
3118: double **dnewm,**doldm;
3119: double *xp, *xm;
3120: double **gp, **gm;
3121: double ***gradg, ***trgradg;
3122: int theta;
3123:
3124: double eip, vip;
3125:
3126: varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
3127: xp=vector(1,npar);
3128: xm=vector(1,npar);
3129: dnewm=matrix(1,nlstate*nlstate,1,npar);
3130: doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
3131:
3132: pstamp(ficresstdeij);
3133: fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
3134: fprintf(ficresstdeij,"# Age");
3135: for(i=1; i<=nlstate;i++){
3136: for(j=1; j<=nlstate;j++)
3137: fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
3138: fprintf(ficresstdeij," e%1d. ",i);
3139: }
3140: fprintf(ficresstdeij,"\n");
3141:
3142: pstamp(ficrescveij);
3143: fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
3144: fprintf(ficrescveij,"# Age");
3145: for(i=1; i<=nlstate;i++)
3146: for(j=1; j<=nlstate;j++){
3147: cptj= (j-1)*nlstate+i;
3148: for(i2=1; i2<=nlstate;i2++)
3149: for(j2=1; j2<=nlstate;j2++){
3150: cptj2= (j2-1)*nlstate+i2;
3151: if(cptj2 <= cptj)
3152: fprintf(ficrescveij," %1d%1d,%1d%1d",i,j,i2,j2);
3153: }
3154: }
3155: fprintf(ficrescveij,"\n");
3156:
3157: if(estepm < stepm){
3158: printf ("Problem %d lower than %d\n",estepm, stepm);
3159: }
3160: else hstepm=estepm;
3161: /* We compute the life expectancy from trapezoids spaced every estepm months
3162: * This is mainly to measure the difference between two models: for example
3163: * if stepm=24 months pijx are given only every 2 years and by summing them
3164: * we are calculating an estimate of the Life Expectancy assuming a linear
3165: * progression in between and thus overestimating or underestimating according
3166: * to the curvature of the survival function. If, for the same date, we
3167: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3168: * to compare the new estimate of Life expectancy with the same linear
3169: * hypothesis. A more precise result, taking into account a more precise
3170: * curvature will be obtained if estepm is as small as stepm. */
3171:
3172: /* For example we decided to compute the life expectancy with the smallest unit */
3173: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3174: nhstepm is the number of hstepm from age to agelim
3175: nstepm is the number of stepm from age to agelin.
3176: Look at hpijx to understand the reason of that which relies in memory size
3177: and note for a fixed period like estepm months */
3178: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3179: survival function given by stepm (the optimization length). Unfortunately it
3180: means that if the survival funtion is printed only each two years of age and if
3181: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3182: results. So we changed our mind and took the option of the best precision.
3183: */
3184: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3185:
3186: /* If stepm=6 months */
3187: /* nhstepm age range expressed in number of stepm */
3188: agelim=AGESUP;
3189: nstepm=(int) rint((agelim-bage)*YEARM/stepm);
3190: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3191: /* if (stepm >= YEARM) hstepm=1;*/
3192: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3193:
3194: p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3195: p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3196: gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
3197: trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
3198: gp=matrix(0,nhstepm,1,nlstate*nlstate);
3199: gm=matrix(0,nhstepm,1,nlstate*nlstate);
3200:
3201: for (age=bage; age<=fage; age ++){
3202: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3203: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3204: /* if (stepm >= YEARM) hstepm=1;*/
3205: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3206:
3207: /* If stepm=6 months */
3208: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3209: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3210:
3211: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3212:
3213: /* Computing Variances of health expectancies */
3214: /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
3215: decrease memory allocation */
3216: for(theta=1; theta <=npar; theta++){
3217: for(i=1; i<=npar; i++){
3218: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3219: xm[i] = x[i] - (i==theta ?delti[theta]:0);
3220: }
3221: hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);
3222: hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);
3223:
3224: for(j=1; j<= nlstate; j++){
3225: for(i=1; i<=nlstate; i++){
3226: for(h=0; h<=nhstepm-1; h++){
3227: gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
3228: gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
3229: }
3230: }
3231: }
3232:
3233: for(ij=1; ij<= nlstate*nlstate; ij++)
3234: for(h=0; h<=nhstepm-1; h++){
3235: gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
3236: }
3237: }/* End theta */
3238:
3239:
3240: for(h=0; h<=nhstepm-1; h++)
3241: for(j=1; j<=nlstate*nlstate;j++)
3242: for(theta=1; theta <=npar; theta++)
3243: trgradg[h][j][theta]=gradg[h][theta][j];
3244:
3245:
3246: for(ij=1;ij<=nlstate*nlstate;ij++)
3247: for(ji=1;ji<=nlstate*nlstate;ji++)
3248: varhe[ij][ji][(int)age] =0.;
3249:
3250: printf("%d|",(int)age);fflush(stdout);
3251: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3252: for(h=0;h<=nhstepm-1;h++){
3253: for(k=0;k<=nhstepm-1;k++){
3254: matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
3255: matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
3256: for(ij=1;ij<=nlstate*nlstate;ij++)
3257: for(ji=1;ji<=nlstate*nlstate;ji++)
3258: varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
3259: }
3260: }
3261:
3262: /* Computing expectancies */
3263: hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3264: for(i=1; i<=nlstate;i++)
3265: for(j=1; j<=nlstate;j++)
3266: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3267: eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
3268:
3269: /* 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]);*/
3270:
3271: }
3272:
3273: fprintf(ficresstdeij,"%3.0f",age );
3274: for(i=1; i<=nlstate;i++){
3275: eip=0.;
3276: vip=0.;
3277: for(j=1; j<=nlstate;j++){
3278: eip += eij[i][j][(int)age];
3279: for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
3280: vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
3281: fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
3282: }
3283: fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
3284: }
3285: fprintf(ficresstdeij,"\n");
3286:
3287: fprintf(ficrescveij,"%3.0f",age );
3288: for(i=1; i<=nlstate;i++)
3289: for(j=1; j<=nlstate;j++){
3290: cptj= (j-1)*nlstate+i;
3291: for(i2=1; i2<=nlstate;i2++)
3292: for(j2=1; j2<=nlstate;j2++){
3293: cptj2= (j2-1)*nlstate+i2;
3294: if(cptj2 <= cptj)
3295: fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
3296: }
3297: }
3298: fprintf(ficrescveij,"\n");
3299:
3300: }
3301: free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
3302: free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
3303: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
3304: free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
3305: free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3306: free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3307: printf("\n");
3308: fprintf(ficlog,"\n");
3309:
3310: free_vector(xm,1,npar);
3311: free_vector(xp,1,npar);
3312: free_matrix(dnewm,1,nlstate*nlstate,1,npar);
3313: free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
3314: free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
3315: }
3316:
3317: /************ Variance ******************/
3318: 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[])
3319: {
3320: /* Variance of health expectancies */
3321: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
3322: /* double **newm;*/
3323: double **dnewm,**doldm;
3324: double **dnewmp,**doldmp;
3325: int i, j, nhstepm, hstepm, h, nstepm ;
1.164 brouard 3326: int k;
1.126 brouard 3327: double *xp;
3328: double **gp, **gm; /* for var eij */
3329: double ***gradg, ***trgradg; /*for var eij */
3330: double **gradgp, **trgradgp; /* for var p point j */
3331: double *gpp, *gmp; /* for var p point j */
3332: double **varppt; /* for var p point j nlstate to nlstate+ndeath */
3333: double ***p3mat;
3334: double age,agelim, hf;
3335: double ***mobaverage;
3336: int theta;
3337: char digit[4];
3338: char digitp[25];
3339:
3340: char fileresprobmorprev[FILENAMELENGTH];
3341:
3342: if(popbased==1){
3343: if(mobilav!=0)
3344: strcpy(digitp,"-populbased-mobilav-");
3345: else strcpy(digitp,"-populbased-nomobil-");
3346: }
3347: else
3348: strcpy(digitp,"-stablbased-");
3349:
3350: if (mobilav!=0) {
3351: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3352: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
3353: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
3354: printf(" Error in movingaverage mobilav=%d\n",mobilav);
3355: }
3356: }
3357:
3358: strcpy(fileresprobmorprev,"prmorprev");
3359: sprintf(digit,"%-d",ij);
3360: /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
3361: strcat(fileresprobmorprev,digit); /* Tvar to be done */
3362: strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
3363: strcat(fileresprobmorprev,fileres);
3364: if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
3365: printf("Problem with resultfile: %s\n", fileresprobmorprev);
3366: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
3367: }
3368: printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3369:
3370: fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3371: pstamp(ficresprobmorprev);
3372: 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);
3373: fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
3374: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3375: fprintf(ficresprobmorprev," p.%-d SE",j);
3376: for(i=1; i<=nlstate;i++)
3377: fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
3378: }
3379: fprintf(ficresprobmorprev,"\n");
3380: fprintf(ficgp,"\n# Routine varevsij");
3381: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
3382: 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");
3383: fprintf(fichtm,"\n<br>%s <br>\n",digitp);
3384: /* } */
3385: varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3386: pstamp(ficresvij);
3387: fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n# (weighted average of eij where weights are ");
3388: if(popbased==1)
1.128 brouard 3389: 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 3390: else
3391: fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
3392: fprintf(ficresvij,"# Age");
3393: for(i=1; i<=nlstate;i++)
3394: for(j=1; j<=nlstate;j++)
3395: fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
3396: fprintf(ficresvij,"\n");
3397:
3398: xp=vector(1,npar);
3399: dnewm=matrix(1,nlstate,1,npar);
3400: doldm=matrix(1,nlstate,1,nlstate);
3401: dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
3402: doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3403:
3404: gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
3405: gpp=vector(nlstate+1,nlstate+ndeath);
3406: gmp=vector(nlstate+1,nlstate+ndeath);
3407: trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
3408:
3409: if(estepm < stepm){
3410: printf ("Problem %d lower than %d\n",estepm, stepm);
3411: }
3412: else hstepm=estepm;
3413: /* For example we decided to compute the life expectancy with the smallest unit */
3414: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3415: nhstepm is the number of hstepm from age to agelim
3416: nstepm is the number of stepm from age to agelin.
1.128 brouard 3417: Look at function hpijx to understand why (it is linked to memory size questions) */
1.126 brouard 3418: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3419: survival function given by stepm (the optimization length). Unfortunately it
3420: means that if the survival funtion is printed every two years of age and if
3421: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3422: results. So we changed our mind and took the option of the best precision.
3423: */
3424: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3425: agelim = AGESUP;
3426: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3427: nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3428: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3429: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3430: gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
3431: gp=matrix(0,nhstepm,1,nlstate);
3432: gm=matrix(0,nhstepm,1,nlstate);
3433:
3434:
3435: for(theta=1; theta <=npar; theta++){
3436: for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
3437: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3438: }
3439: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3440: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3441:
3442: if (popbased==1) {
3443: if(mobilav ==0){
3444: for(i=1; i<=nlstate;i++)
3445: prlim[i][i]=probs[(int)age][i][ij];
3446: }else{ /* mobilav */
3447: for(i=1; i<=nlstate;i++)
3448: prlim[i][i]=mobaverage[(int)age][i][ij];
3449: }
3450: }
3451:
3452: for(j=1; j<= nlstate; j++){
3453: for(h=0; h<=nhstepm; h++){
3454: for(i=1, gp[h][j]=0.;i<=nlstate;i++)
3455: gp[h][j] += prlim[i][i]*p3mat[i][j][h];
3456: }
3457: }
3458: /* This for computing probability of death (h=1 means
3459: computed over hstepm matrices product = hstepm*stepm months)
3460: as a weighted average of prlim.
3461: */
3462: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3463: for(i=1,gpp[j]=0.; i<= nlstate; i++)
3464: gpp[j] += prlim[i][i]*p3mat[i][j][1];
3465: }
3466: /* end probability of death */
3467:
3468: for(i=1; i<=npar; i++) /* Computes gradient x - delta */
3469: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3470: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3471: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3472:
3473: if (popbased==1) {
3474: if(mobilav ==0){
3475: for(i=1; i<=nlstate;i++)
3476: prlim[i][i]=probs[(int)age][i][ij];
3477: }else{ /* mobilav */
3478: for(i=1; i<=nlstate;i++)
3479: prlim[i][i]=mobaverage[(int)age][i][ij];
3480: }
3481: }
3482:
1.128 brouard 3483: for(j=1; j<= nlstate; j++){ /* Sum of wi * eij = e.j */
1.126 brouard 3484: for(h=0; h<=nhstepm; h++){
3485: for(i=1, gm[h][j]=0.;i<=nlstate;i++)
3486: gm[h][j] += prlim[i][i]*p3mat[i][j][h];
3487: }
3488: }
3489: /* This for computing probability of death (h=1 means
3490: computed over hstepm matrices product = hstepm*stepm months)
3491: as a weighted average of prlim.
3492: */
3493: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3494: for(i=1,gmp[j]=0.; i<= nlstate; i++)
3495: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3496: }
3497: /* end probability of death */
3498:
3499: for(j=1; j<= nlstate; j++) /* vareij */
3500: for(h=0; h<=nhstepm; h++){
3501: gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
3502: }
3503:
3504: for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
3505: gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
3506: }
3507:
3508: } /* End theta */
3509:
3510: trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
3511:
3512: for(h=0; h<=nhstepm; h++) /* veij */
3513: for(j=1; j<=nlstate;j++)
3514: for(theta=1; theta <=npar; theta++)
3515: trgradg[h][j][theta]=gradg[h][theta][j];
3516:
3517: for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
3518: for(theta=1; theta <=npar; theta++)
3519: trgradgp[j][theta]=gradgp[theta][j];
3520:
3521:
3522: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3523: for(i=1;i<=nlstate;i++)
3524: for(j=1;j<=nlstate;j++)
3525: vareij[i][j][(int)age] =0.;
3526:
3527: for(h=0;h<=nhstepm;h++){
3528: for(k=0;k<=nhstepm;k++){
3529: matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
3530: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
3531: for(i=1;i<=nlstate;i++)
3532: for(j=1;j<=nlstate;j++)
3533: vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
3534: }
3535: }
3536:
3537: /* pptj */
3538: matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
3539: matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
3540: for(j=nlstate+1;j<=nlstate+ndeath;j++)
3541: for(i=nlstate+1;i<=nlstate+ndeath;i++)
3542: varppt[j][i]=doldmp[j][i];
3543: /* end ppptj */
3544: /* x centered again */
3545: hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);
3546: prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
3547:
3548: if (popbased==1) {
3549: if(mobilav ==0){
3550: for(i=1; i<=nlstate;i++)
3551: prlim[i][i]=probs[(int)age][i][ij];
3552: }else{ /* mobilav */
3553: for(i=1; i<=nlstate;i++)
3554: prlim[i][i]=mobaverage[(int)age][i][ij];
3555: }
3556: }
3557:
3558: /* This for computing probability of death (h=1 means
3559: computed over hstepm (estepm) matrices product = hstepm*stepm months)
3560: as a weighted average of prlim.
3561: */
3562: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3563: for(i=1,gmp[j]=0.;i<= nlstate; i++)
3564: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3565: }
3566: /* end probability of death */
3567:
3568: fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
3569: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3570: fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
3571: for(i=1; i<=nlstate;i++){
3572: fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
3573: }
3574: }
3575: fprintf(ficresprobmorprev,"\n");
3576:
3577: fprintf(ficresvij,"%.0f ",age );
3578: for(i=1; i<=nlstate;i++)
3579: for(j=1; j<=nlstate;j++){
3580: fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
3581: }
3582: fprintf(ficresvij,"\n");
3583: free_matrix(gp,0,nhstepm,1,nlstate);
3584: free_matrix(gm,0,nhstepm,1,nlstate);
3585: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
3586: free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
3587: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3588: } /* End age */
3589: free_vector(gpp,nlstate+1,nlstate+ndeath);
3590: free_vector(gmp,nlstate+1,nlstate+ndeath);
3591: free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
3592: free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.145 brouard 3593: fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
1.126 brouard 3594: /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131 brouard 3595: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.126 brouard 3596: /* fprintf(ficgp,"\n plot \"%s\" u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
3597: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
3598: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145 brouard 3599: fprintf(ficgp,"\n plot \"%s\" u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
3600: fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)) t \"95\%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
3601: fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126 brouard 3602: fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
3603: 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);
3604: /* 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);
3605: */
3606: /* fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
3607: fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
3608:
3609: free_vector(xp,1,npar);
3610: free_matrix(doldm,1,nlstate,1,nlstate);
3611: free_matrix(dnewm,1,nlstate,1,npar);
3612: free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3613: free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
3614: free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3615: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3616: fclose(ficresprobmorprev);
3617: fflush(ficgp);
3618: fflush(fichtm);
3619: } /* end varevsij */
3620:
3621: /************ Variance of prevlim ******************/
3622: 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[])
3623: {
3624: /* Variance of prevalence limit */
3625: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164 brouard 3626:
1.126 brouard 3627: double **dnewm,**doldm;
3628: int i, j, nhstepm, hstepm;
3629: double *xp;
3630: double *gp, *gm;
3631: double **gradg, **trgradg;
3632: double age,agelim;
3633: int theta;
3634:
3635: pstamp(ficresvpl);
3636: fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
3637: fprintf(ficresvpl,"# Age");
3638: for(i=1; i<=nlstate;i++)
3639: fprintf(ficresvpl," %1d-%1d",i,i);
3640: fprintf(ficresvpl,"\n");
3641:
3642: xp=vector(1,npar);
3643: dnewm=matrix(1,nlstate,1,npar);
3644: doldm=matrix(1,nlstate,1,nlstate);
3645:
3646: hstepm=1*YEARM; /* Every year of age */
3647: hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
3648: agelim = AGESUP;
3649: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3650: nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3651: if (stepm >= YEARM) hstepm=1;
3652: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
3653: gradg=matrix(1,npar,1,nlstate);
3654: gp=vector(1,nlstate);
3655: gm=vector(1,nlstate);
3656:
3657: for(theta=1; theta <=npar; theta++){
3658: for(i=1; i<=npar; i++){ /* Computes gradient */
3659: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3660: }
3661: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3662: for(i=1;i<=nlstate;i++)
3663: gp[i] = prlim[i][i];
3664:
3665: for(i=1; i<=npar; i++) /* Computes gradient */
3666: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3667: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3668: for(i=1;i<=nlstate;i++)
3669: gm[i] = prlim[i][i];
3670:
3671: for(i=1;i<=nlstate;i++)
3672: gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
3673: } /* End theta */
3674:
3675: trgradg =matrix(1,nlstate,1,npar);
3676:
3677: for(j=1; j<=nlstate;j++)
3678: for(theta=1; theta <=npar; theta++)
3679: trgradg[j][theta]=gradg[theta][j];
3680:
3681: for(i=1;i<=nlstate;i++)
3682: varpl[i][(int)age] =0.;
3683: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
3684: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
3685: for(i=1;i<=nlstate;i++)
3686: varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
3687:
3688: fprintf(ficresvpl,"%.0f ",age );
3689: for(i=1; i<=nlstate;i++)
3690: fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
3691: fprintf(ficresvpl,"\n");
3692: free_vector(gp,1,nlstate);
3693: free_vector(gm,1,nlstate);
3694: free_matrix(gradg,1,npar,1,nlstate);
3695: free_matrix(trgradg,1,nlstate,1,npar);
3696: } /* End age */
3697:
3698: free_vector(xp,1,npar);
3699: free_matrix(doldm,1,nlstate,1,npar);
3700: free_matrix(dnewm,1,nlstate,1,nlstate);
3701:
3702: }
3703:
3704: /************ Variance of one-step probabilities ******************/
3705: 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[])
3706: {
1.164 brouard 3707: int i, j=0, k1, l1, tj;
1.126 brouard 3708: int k2, l2, j1, z1;
1.164 brouard 3709: int k=0, l;
1.145 brouard 3710: int first=1, first1, first2;
1.126 brouard 3711: double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
3712: double **dnewm,**doldm;
3713: double *xp;
3714: double *gp, *gm;
3715: double **gradg, **trgradg;
3716: double **mu;
1.164 brouard 3717: double age, cov[NCOVMAX+1];
1.126 brouard 3718: double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
3719: int theta;
3720: char fileresprob[FILENAMELENGTH];
3721: char fileresprobcov[FILENAMELENGTH];
3722: char fileresprobcor[FILENAMELENGTH];
3723: double ***varpij;
3724:
3725: strcpy(fileresprob,"prob");
3726: strcat(fileresprob,fileres);
3727: if((ficresprob=fopen(fileresprob,"w"))==NULL) {
3728: printf("Problem with resultfile: %s\n", fileresprob);
3729: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
3730: }
3731: strcpy(fileresprobcov,"probcov");
3732: strcat(fileresprobcov,fileres);
3733: if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
3734: printf("Problem with resultfile: %s\n", fileresprobcov);
3735: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
3736: }
3737: strcpy(fileresprobcor,"probcor");
3738: strcat(fileresprobcor,fileres);
3739: if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
3740: printf("Problem with resultfile: %s\n", fileresprobcor);
3741: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
3742: }
3743: printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3744: fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3745: printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3746: fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3747: printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3748: fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3749: pstamp(ficresprob);
3750: fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
3751: fprintf(ficresprob,"# Age");
3752: pstamp(ficresprobcov);
3753: fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
3754: fprintf(ficresprobcov,"# Age");
3755: pstamp(ficresprobcor);
3756: fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
3757: fprintf(ficresprobcor,"# Age");
3758:
3759:
3760: for(i=1; i<=nlstate;i++)
3761: for(j=1; j<=(nlstate+ndeath);j++){
3762: fprintf(ficresprob," p%1d-%1d (SE)",i,j);
3763: fprintf(ficresprobcov," p%1d-%1d ",i,j);
3764: fprintf(ficresprobcor," p%1d-%1d ",i,j);
3765: }
3766: /* fprintf(ficresprob,"\n");
3767: fprintf(ficresprobcov,"\n");
3768: fprintf(ficresprobcor,"\n");
3769: */
1.131 brouard 3770: xp=vector(1,npar);
1.126 brouard 3771: dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3772: doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
3773: mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
3774: varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
3775: first=1;
3776: fprintf(ficgp,"\n# Routine varprob");
3777: fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
3778: fprintf(fichtm,"\n");
3779:
3780: fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
3781: fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
3782: file %s<br>\n",optionfilehtmcov);
3783: fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
3784: and drawn. It helps understanding how is the covariance between two incidences.\
3785: They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
3786: 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. \
3787: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
3788: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
3789: standard deviations wide on each axis. <br>\
3790: Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
3791: and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
3792: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
3793:
3794: cov[1]=1;
1.145 brouard 3795: /* tj=cptcoveff; */
3796: tj = (int) pow(2,cptcoveff);
1.126 brouard 3797: if (cptcovn<1) {tj=1;ncodemax[1]=1;}
3798: j1=0;
1.145 brouard 3799: for(j1=1; j1<=tj;j1++){
3800: /*for(i1=1; i1<=ncodemax[t];i1++){ */
3801: /*j1++;*/
1.126 brouard 3802: if (cptcovn>0) {
3803: fprintf(ficresprob, "\n#********** Variable ");
3804: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3805: fprintf(ficresprob, "**********\n#\n");
3806: fprintf(ficresprobcov, "\n#********** Variable ");
3807: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3808: fprintf(ficresprobcov, "**********\n#\n");
3809:
3810: fprintf(ficgp, "\n#********** Variable ");
3811: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3812: fprintf(ficgp, "**********\n#\n");
3813:
3814:
3815: fprintf(fichtmcov, "\n<hr size=\"2\" color=\"#EC5E5E\">********** Variable ");
3816: for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3817: fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
3818:
3819: fprintf(ficresprobcor, "\n#********** Variable ");
3820: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3821: fprintf(ficresprobcor, "**********\n#");
3822: }
3823:
1.145 brouard 3824: gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
3825: trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3826: gp=vector(1,(nlstate)*(nlstate+ndeath));
3827: gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126 brouard 3828: for (age=bage; age<=fage; age ++){
3829: cov[2]=age;
3830: for (k=1; k<=cptcovn;k++) {
1.145 brouard 3831: cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
3832: * 1 1 1 1 1
3833: * 2 2 1 1 1
3834: * 3 1 2 1 1
3835: */
3836: /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126 brouard 3837: }
3838: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
3839: for (k=1; k<=cptcovprod;k++)
3840: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
3841:
3842:
3843: for(theta=1; theta <=npar; theta++){
3844: for(i=1; i<=npar; i++)
3845: xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
3846:
3847: pmij(pmmij,cov,ncovmodel,xp,nlstate);
3848:
3849: k=0;
3850: for(i=1; i<= (nlstate); i++){
3851: for(j=1; j<=(nlstate+ndeath);j++){
3852: k=k+1;
3853: gp[k]=pmmij[i][j];
3854: }
3855: }
3856:
3857: for(i=1; i<=npar; i++)
3858: xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
3859:
3860: pmij(pmmij,cov,ncovmodel,xp,nlstate);
3861: k=0;
3862: for(i=1; i<=(nlstate); i++){
3863: for(j=1; j<=(nlstate+ndeath);j++){
3864: k=k+1;
3865: gm[k]=pmmij[i][j];
3866: }
3867: }
3868:
3869: for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
3870: gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];
3871: }
3872:
3873: for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
3874: for(theta=1; theta <=npar; theta++)
3875: trgradg[j][theta]=gradg[theta][j];
3876:
3877: matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
3878: matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
3879:
3880: pmij(pmmij,cov,ncovmodel,x,nlstate);
3881:
3882: k=0;
3883: for(i=1; i<=(nlstate); i++){
3884: for(j=1; j<=(nlstate+ndeath);j++){
3885: k=k+1;
3886: mu[k][(int) age]=pmmij[i][j];
3887: }
3888: }
3889: for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
3890: for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
3891: varpij[i][j][(int)age] = doldm[i][j];
3892:
3893: /*printf("\n%d ",(int)age);
3894: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
3895: printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
3896: fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
3897: }*/
3898:
3899: fprintf(ficresprob,"\n%d ",(int)age);
3900: fprintf(ficresprobcov,"\n%d ",(int)age);
3901: fprintf(ficresprobcor,"\n%d ",(int)age);
3902:
3903: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
3904: fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
3905: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
3906: fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
3907: fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
3908: }
3909: i=0;
3910: for (k=1; k<=(nlstate);k++){
3911: for (l=1; l<=(nlstate+ndeath);l++){
1.145 brouard 3912: i++;
1.126 brouard 3913: fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
3914: fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
3915: for (j=1; j<=i;j++){
1.145 brouard 3916: /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126 brouard 3917: fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
3918: fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
3919: }
3920: }
3921: }/* end of loop for state */
3922: } /* end of loop for age */
1.145 brouard 3923: free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
3924: free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
3925: free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
3926: free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
3927:
1.126 brouard 3928: /* Confidence intervalle of pij */
3929: /*
1.131 brouard 3930: fprintf(ficgp,"\nunset parametric;unset label");
1.126 brouard 3931: fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
3932: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
3933: 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);
3934: fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
3935: fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
3936: fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
3937: */
3938:
3939: /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145 brouard 3940: first1=1;first2=2;
1.126 brouard 3941: for (k2=1; k2<=(nlstate);k2++){
3942: for (l2=1; l2<=(nlstate+ndeath);l2++){
3943: if(l2==k2) continue;
3944: j=(k2-1)*(nlstate+ndeath)+l2;
3945: for (k1=1; k1<=(nlstate);k1++){
3946: for (l1=1; l1<=(nlstate+ndeath);l1++){
3947: if(l1==k1) continue;
3948: i=(k1-1)*(nlstate+ndeath)+l1;
3949: if(i<=j) continue;
3950: for (age=bage; age<=fage; age ++){
3951: if ((int)age %5==0){
3952: v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
3953: v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
3954: cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
3955: mu1=mu[i][(int) age]/stepm*YEARM ;
3956: mu2=mu[j][(int) age]/stepm*YEARM;
3957: c12=cv12/sqrt(v1*v2);
3958: /* Computing eigen value of matrix of covariance */
3959: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
3960: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135 brouard 3961: if ((lc2 <0) || (lc1 <0) ){
1.145 brouard 3962: if(first2==1){
3963: first1=0;
3964: 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);
3965: }
3966: 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);
3967: /* lc1=fabs(lc1); */ /* If we want to have them positive */
3968: /* lc2=fabs(lc2); */
1.135 brouard 3969: }
3970:
1.126 brouard 3971: /* Eigen vectors */
3972: v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
3973: /*v21=sqrt(1.-v11*v11); *//* error */
3974: v21=(lc1-v1)/cv12*v11;
3975: v12=-v21;
3976: v22=v11;
3977: tnalp=v21/v11;
3978: if(first1==1){
3979: first1=0;
3980: 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);
3981: }
3982: 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);
3983: /*printf(fignu*/
3984: /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
3985: /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
3986: if(first==1){
3987: first=0;
3988: fprintf(ficgp,"\nset parametric;unset label");
3989: 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 3990: fprintf(ficgp,"\nset ter png small size 320, 240");
1.126 brouard 3991: fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
3992: :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
3993: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
3994: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
3995: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
3996: fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
3997: fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
3998: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
3999: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4000: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4001: 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",\
4002: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4003: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4004: }else{
4005: first=0;
4006: fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
4007: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4008: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4009: 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",\
4010: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4011: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4012: }/* if first */
4013: } /* age mod 5 */
4014: } /* end loop age */
4015: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4016: first=1;
4017: } /*l12 */
4018: } /* k12 */
4019: } /*l1 */
4020: }/* k1 */
1.145 brouard 4021: /* } /* loop covariates */
1.126 brouard 4022: }
4023: free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
4024: free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
4025: free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4026: free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
4027: free_vector(xp,1,npar);
4028: fclose(ficresprob);
4029: fclose(ficresprobcov);
4030: fclose(ficresprobcor);
4031: fflush(ficgp);
4032: fflush(fichtmcov);
4033: }
4034:
4035:
4036: /******************* Printing html file ***********/
4037: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
4038: int lastpass, int stepm, int weightopt, char model[],\
4039: int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
4040: int popforecast, int estepm ,\
4041: double jprev1, double mprev1,double anprev1, \
4042: double jprev2, double mprev2,double anprev2){
4043: int jj1, k1, i1, cpt;
4044:
4045: fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
4046: <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
4047: </ul>");
4048: fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
4049: - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
4050: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
4051: fprintf(fichtm,"\
4052: - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
4053: stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
4054: fprintf(fichtm,"\
4055: - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
4056: subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
4057: fprintf(fichtm,"\
1.128 brouard 4058: - (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 4059: <a href=\"%s\">%s</a> <br>\n",
4060: estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
4061: fprintf(fichtm,"\
4062: - Population projections by age and states: \
4063: <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
4064:
4065: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
4066:
1.145 brouard 4067: m=pow(2,cptcoveff);
1.126 brouard 4068: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4069:
4070: jj1=0;
4071: for(k1=1; k1<=m;k1++){
4072: for(i1=1; i1<=ncodemax[k1];i1++){
4073: jj1++;
4074: if (cptcovn > 0) {
4075: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4076: for (cpt=1; cpt<=cptcoveff;cpt++)
4077: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4078: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4079: }
4080: /* Pij */
1.145 brouard 4081: 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> \
4082: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
1.126 brouard 4083: /* Quasi-incidences */
4084: fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
1.145 brouard 4085: 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> \
4086: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
1.126 brouard 4087: /* Period (stable) prevalence in each health state */
1.154 brouard 4088: for(cpt=1; cpt<=nlstate;cpt++){
1.164 brouard 4089: fprintf(fichtm,"<br>- Convergence from cross-sectional prevalence in each state (1 to %d) to period (stable) prevalence in specific state %d <a href=\"%s%d_%d.png\">%s%d_%d.png</a><br> \
1.154 brouard 4090: <img src=\"%s%d_%d.png\">",nlstate, cpt, subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
1.126 brouard 4091: }
4092: for(cpt=1; cpt<=nlstate;cpt++) {
1.154 brouard 4093: 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> \
4094: <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 4095: }
4096: } /* end i1 */
4097: }/* End k1 */
4098: fprintf(fichtm,"</ul>");
4099:
4100:
4101: fprintf(fichtm,"\
4102: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
4103: - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
4104:
4105: fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4106: subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
4107: fprintf(fichtm,"\
4108: - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4109: subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
4110:
4111: fprintf(fichtm,"\
4112: - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4113: subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
4114: fprintf(fichtm,"\
4115: - 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): \
4116: <a href=\"%s\">%s</a> <br>\n</li>",
4117: estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
4118: fprintf(fichtm,"\
4119: - (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): \
4120: <a href=\"%s\">%s</a> <br>\n</li>",
4121: estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
4122: fprintf(fichtm,"\
1.128 brouard 4123: - 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 4124: estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
4125: fprintf(fichtm,"\
1.128 brouard 4126: - 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",
4127: estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
1.126 brouard 4128: fprintf(fichtm,"\
4129: - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
4130: subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
4131:
4132: /* if(popforecast==1) fprintf(fichtm,"\n */
4133: /* - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
4134: /* - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
4135: /* <br>",fileres,fileres,fileres,fileres); */
4136: /* else */
4137: /* 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); */
4138: fflush(fichtm);
4139: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
4140:
1.145 brouard 4141: m=pow(2,cptcoveff);
1.126 brouard 4142: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4143:
4144: jj1=0;
4145: for(k1=1; k1<=m;k1++){
4146: for(i1=1; i1<=ncodemax[k1];i1++){
4147: jj1++;
4148: if (cptcovn > 0) {
4149: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4150: for (cpt=1; cpt<=cptcoveff;cpt++)
4151: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4152: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4153: }
4154: for(cpt=1; cpt<=nlstate;cpt++) {
4155: fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.145 brouard 4156: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
4157: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);
1.126 brouard 4158: }
4159: fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128 brouard 4160: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
4161: true period expectancies (those weighted with period prevalences are also\
4162: drawn in addition to the population based expectancies computed using\
4163: observed and cahotic prevalences: %s%d.png<br>\
1.126 brouard 4164: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
4165: } /* end i1 */
4166: }/* End k1 */
4167: fprintf(fichtm,"</ul>");
4168: fflush(fichtm);
4169: }
4170:
4171: /******************* Gnuplot file **************/
4172: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4173:
4174: char dirfileres[132],optfileres[132];
1.164 brouard 4175: int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.130 brouard 4176: int ng=0;
1.126 brouard 4177: /* if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
4178: /* printf("Problem with file %s",optionfilegnuplot); */
4179: /* fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
4180: /* } */
4181:
4182: /*#ifdef windows */
4183: fprintf(ficgp,"cd \"%s\" \n",pathc);
4184: /*#endif */
4185: m=pow(2,cptcoveff);
4186:
4187: strcpy(dirfileres,optionfilefiname);
4188: strcpy(optfileres,"vpl");
4189: /* 1eme*/
1.153 brouard 4190: fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
1.126 brouard 4191: for (cpt=1; cpt<= nlstate ; cpt ++) {
1.145 brouard 4192: for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
4193: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
4194: fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
1.126 brouard 4195: fprintf(ficgp,"set xlabel \"Age\" \n\
4196: set ylabel \"Probability\" \n\
1.145 brouard 4197: set ter png small size 320, 240\n\
1.126 brouard 4198: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
4199:
4200: for (i=1; i<= nlstate ; i ++) {
4201: if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
1.131 brouard 4202: else fprintf(ficgp," \%%*lf (\%%*lf)");
1.126 brouard 4203: }
1.145 brouard 4204: 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 4205: for (i=1; i<= nlstate ; i ++) {
4206: if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
4207: else fprintf(ficgp," \%%*lf (\%%*lf)");
4208: }
1.145 brouard 4209: 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 4210: for (i=1; i<= nlstate ; i ++) {
4211: if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
4212: else fprintf(ficgp," \%%*lf (\%%*lf)");
4213: }
1.145 brouard 4214: 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 4215: }
4216: }
4217: /*2 eme*/
1.153 brouard 4218: fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
1.126 brouard 4219: for (k1=1; k1<= m ; k1 ++) {
4220: fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
1.145 brouard 4221: fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
1.126 brouard 4222:
4223: for (i=1; i<= nlstate+1 ; i ++) {
4224: k=2*i;
4225: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4226: for (j=1; j<= nlstate+1 ; j ++) {
4227: if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
4228: else fprintf(ficgp," \%%*lf (\%%*lf)");
4229: }
4230: if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
4231: else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
4232: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4233: for (j=1; j<= nlstate+1 ; j ++) {
4234: if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
4235: else fprintf(ficgp," \%%*lf (\%%*lf)");
4236: }
1.145 brouard 4237: fprintf(ficgp,"\" t\"\" w l lt 0,");
1.126 brouard 4238: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4239: for (j=1; j<= nlstate+1 ; j ++) {
4240: if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
4241: else fprintf(ficgp," \%%*lf (\%%*lf)");
4242: }
1.145 brouard 4243: if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
4244: else fprintf(ficgp,"\" t\"\" w l lt 0,");
1.126 brouard 4245: }
4246: }
4247:
4248: /*3eme*/
4249:
4250: for (k1=1; k1<= m ; k1 ++) {
4251: for (cpt=1; cpt<= nlstate ; cpt ++) {
4252: /* k=2+nlstate*(2*cpt-2); */
4253: k=2+(nlstate+1)*(cpt-1);
4254: fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
1.145 brouard 4255: fprintf(ficgp,"set ter png small size 320, 240\n\
1.126 brouard 4256: 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);
4257: /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4258: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4259: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4260: fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4261: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4262: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4263:
4264: */
4265: for (i=1; i< nlstate ; i ++) {
4266: 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);
4267: /* 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);*/
4268:
4269: }
4270: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
4271: }
4272: }
4273:
4274: /* CV preval stable (period) */
1.153 brouard 4275: for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
4276: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.126 brouard 4277: k=3;
1.153 brouard 4278: fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
1.145 brouard 4279: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
1.126 brouard 4280: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.145 brouard 4281: set ter png small size 320, 240\n\
1.126 brouard 4282: unset log y\n\
1.153 brouard 4283: plot [%.f:%.f] ", ageminpar, agemaxpar);
4284: for (i=1; i<= nlstate ; i ++){
4285: if(i==1)
4286: fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
4287: else
4288: fprintf(ficgp,", '' ");
1.154 brouard 4289: l=(nlstate+ndeath)*(i-1)+1;
4290: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.153 brouard 4291: for (j=1; j<= (nlstate-1) ; j ++)
4292: fprintf(ficgp,"+$%d",k+l+j);
4293: fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
4294: } /* nlstate */
4295: fprintf(ficgp,"\n");
4296: } /* end cpt state*/
4297: } /* end covariate */
1.126 brouard 4298:
4299: /* proba elementaires */
4300: for(i=1,jk=1; i <=nlstate; i++){
4301: for(k=1; k <=(nlstate+ndeath); k++){
4302: if (k != i) {
4303: for(j=1; j <=ncovmodel; j++){
4304: fprintf(ficgp,"p%d=%f ",jk,p[jk]);
4305: jk++;
4306: fprintf(ficgp,"\n");
4307: }
4308: }
4309: }
4310: }
1.145 brouard 4311: /*goto avoid;*/
1.126 brouard 4312: for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
4313: for(jk=1; jk <=m; jk++) {
1.145 brouard 4314: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);
1.126 brouard 4315: if (ng==2)
4316: fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
4317: else
4318: fprintf(ficgp,"\nset title \"Probability\"\n");
1.145 brouard 4319: fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot [%.f:%.f] ",ageminpar,agemaxpar);
1.126 brouard 4320: i=1;
4321: for(k2=1; k2<=nlstate; k2++) {
4322: k3=i;
4323: for(k=1; k<=(nlstate+ndeath); k++) {
4324: if (k != k2){
4325: if(ng==2)
4326: fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
4327: else
4328: fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
1.141 brouard 4329: ij=1;/* To be checked else nbcode[0][0] wrong */
1.126 brouard 4330: for(j=3; j <=ncovmodel; j++) {
1.145 brouard 4331: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /\* Bug valgrind *\/ */
4332: /* /\*fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);*\/ */
4333: /* ij++; */
4334: /* } */
4335: /* else */
1.126 brouard 4336: fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4337: }
4338: fprintf(ficgp,")/(1");
4339:
4340: for(k1=1; k1 <=nlstate; k1++){
4341: fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
4342: ij=1;
4343: for(j=3; j <=ncovmodel; j++){
1.145 brouard 4344: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { */
4345: /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]); */
4346: /* ij++; */
4347: /* } */
4348: /* else */
1.126 brouard 4349: fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4350: }
4351: fprintf(ficgp,")");
4352: }
4353: fprintf(ficgp,") t \"p%d%d\" ", k2,k);
4354: if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
4355: i=i+ncovmodel;
4356: }
4357: } /* end k */
4358: } /* end k2 */
4359: } /* end jk */
4360: } /* end ng */
1.164 brouard 4361: /* avoid: */
1.126 brouard 4362: fflush(ficgp);
4363: } /* end gnuplot */
4364:
4365:
4366: /*************** Moving average **************/
4367: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
4368:
4369: int i, cpt, cptcod;
4370: int modcovmax =1;
4371: int mobilavrange, mob;
4372: double age;
4373:
4374: modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
4375: a covariate has 2 modalities */
4376: if (cptcovn<1) modcovmax=1; /* At least 1 pass */
4377:
4378: if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
4379: if(mobilav==1) mobilavrange=5; /* default */
4380: else mobilavrange=mobilav;
4381: for (age=bage; age<=fage; age++)
4382: for (i=1; i<=nlstate;i++)
4383: for (cptcod=1;cptcod<=modcovmax;cptcod++)
4384: mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
4385: /* We keep the original values on the extreme ages bage, fage and for
4386: fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
4387: we use a 5 terms etc. until the borders are no more concerned.
4388: */
4389: for (mob=3;mob <=mobilavrange;mob=mob+2){
4390: for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
4391: for (i=1; i<=nlstate;i++){
4392: for (cptcod=1;cptcod<=modcovmax;cptcod++){
4393: mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
4394: for (cpt=1;cpt<=(mob-1)/2;cpt++){
4395: mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
4396: mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
4397: }
4398: mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
4399: }
4400: }
4401: }/* end age */
4402: }/* end mob */
4403: }else return -1;
4404: return 0;
4405: }/* End movingaverage */
4406:
4407:
4408: /************** Forecasting ******************/
4409: 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){
4410: /* proj1, year, month, day of starting projection
4411: agemin, agemax range of age
4412: dateprev1 dateprev2 range of dates during which prevalence is computed
4413: anproj2 year of en of projection (same day and month as proj1).
4414: */
1.164 brouard 4415: int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126 brouard 4416: double agec; /* generic age */
4417: double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
4418: double *popeffectif,*popcount;
4419: double ***p3mat;
4420: double ***mobaverage;
4421: char fileresf[FILENAMELENGTH];
4422:
4423: agelim=AGESUP;
4424: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4425:
4426: strcpy(fileresf,"f");
4427: strcat(fileresf,fileres);
4428: if((ficresf=fopen(fileresf,"w"))==NULL) {
4429: printf("Problem with forecast resultfile: %s\n", fileresf);
4430: fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
4431: }
4432: printf("Computing forecasting: result on file '%s' \n", fileresf);
4433: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
4434:
4435: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4436:
4437: if (mobilav!=0) {
4438: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4439: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4440: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4441: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4442: }
4443: }
4444:
4445: stepsize=(int) (stepm+YEARM-1)/YEARM;
4446: if (stepm<=12) stepsize=1;
4447: if(estepm < stepm){
4448: printf ("Problem %d lower than %d\n",estepm, stepm);
4449: }
4450: else hstepm=estepm;
4451:
4452: hstepm=hstepm/stepm;
4453: yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp and
4454: fractional in yp1 */
4455: anprojmean=yp;
4456: yp2=modf((yp1*12),&yp);
4457: mprojmean=yp;
4458: yp1=modf((yp2*30.5),&yp);
4459: jprojmean=yp;
4460: if(jprojmean==0) jprojmean=1;
4461: if(mprojmean==0) jprojmean=1;
4462:
4463: i1=cptcoveff;
4464: if (cptcovn < 1){i1=1;}
4465:
4466: fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
4467:
4468: fprintf(ficresf,"#****** Routine prevforecast **\n");
4469:
4470: /* if (h==(int)(YEARM*yearp)){ */
4471: for(cptcov=1, k=0;cptcov<=i1;cptcov++){
4472: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4473: k=k+1;
4474: fprintf(ficresf,"\n#******");
4475: for(j=1;j<=cptcoveff;j++) {
4476: 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]]);
4477: }
4478: fprintf(ficresf,"******\n");
4479: fprintf(ficresf,"# Covariate valuofcovar yearproj age");
4480: for(j=1; j<=nlstate+ndeath;j++){
4481: for(i=1; i<=nlstate;i++)
4482: fprintf(ficresf," p%d%d",i,j);
4483: fprintf(ficresf," p.%d",j);
4484: }
4485: for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
4486: fprintf(ficresf,"\n");
4487: fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);
4488:
4489: for (agec=fage; agec>=(ageminpar-1); agec--){
4490: nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
4491: nhstepm = nhstepm/hstepm;
4492: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4493: oldm=oldms;savm=savms;
4494: hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
4495:
4496: for (h=0; h<=nhstepm; h++){
4497: if (h*hstepm/YEARM*stepm ==yearp) {
4498: fprintf(ficresf,"\n");
4499: for(j=1;j<=cptcoveff;j++)
4500: fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4501: fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
4502: }
4503: for(j=1; j<=nlstate+ndeath;j++) {
4504: ppij=0.;
4505: for(i=1; i<=nlstate;i++) {
4506: if (mobilav==1)
4507: ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
4508: else {
4509: ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
4510: }
4511: if (h*hstepm/YEARM*stepm== yearp) {
4512: fprintf(ficresf," %.3f", p3mat[i][j][h]);
4513: }
4514: } /* end i */
4515: if (h*hstepm/YEARM*stepm==yearp) {
4516: fprintf(ficresf," %.3f", ppij);
4517: }
4518: }/* end j */
4519: } /* end h */
4520: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4521: } /* end agec */
4522: } /* end yearp */
4523: } /* end cptcod */
4524: } /* end cptcov */
4525:
4526: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4527:
4528: fclose(ficresf);
4529: }
4530:
4531: /************** Forecasting *****not tested NB*************/
4532: 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){
4533:
4534: int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
4535: int *popage;
4536: double calagedatem, agelim, kk1, kk2;
4537: double *popeffectif,*popcount;
4538: double ***p3mat,***tabpop,***tabpopprev;
4539: double ***mobaverage;
4540: char filerespop[FILENAMELENGTH];
4541:
4542: tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4543: tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4544: agelim=AGESUP;
4545: calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
4546:
4547: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4548:
4549:
4550: strcpy(filerespop,"pop");
4551: strcat(filerespop,fileres);
4552: if((ficrespop=fopen(filerespop,"w"))==NULL) {
4553: printf("Problem with forecast resultfile: %s\n", filerespop);
4554: fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
4555: }
4556: printf("Computing forecasting: result on file '%s' \n", filerespop);
4557: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
4558:
4559: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4560:
4561: if (mobilav!=0) {
4562: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4563: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4564: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4565: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4566: }
4567: }
4568:
4569: stepsize=(int) (stepm+YEARM-1)/YEARM;
4570: if (stepm<=12) stepsize=1;
4571:
4572: agelim=AGESUP;
4573:
4574: hstepm=1;
4575: hstepm=hstepm/stepm;
4576:
4577: if (popforecast==1) {
4578: if((ficpop=fopen(popfile,"r"))==NULL) {
4579: printf("Problem with population file : %s\n",popfile);exit(0);
4580: fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
4581: }
4582: popage=ivector(0,AGESUP);
4583: popeffectif=vector(0,AGESUP);
4584: popcount=vector(0,AGESUP);
4585:
4586: i=1;
4587: while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
4588:
4589: imx=i;
4590: for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
4591: }
4592:
4593: for(cptcov=1,k=0;cptcov<=i2;cptcov++){
4594: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4595: k=k+1;
4596: fprintf(ficrespop,"\n#******");
4597: for(j=1;j<=cptcoveff;j++) {
4598: fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4599: }
4600: fprintf(ficrespop,"******\n");
4601: fprintf(ficrespop,"# Age");
4602: for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
4603: if (popforecast==1) fprintf(ficrespop," [Population]");
4604:
4605: for (cpt=0; cpt<=0;cpt++) {
4606: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4607:
4608: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4609: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4610: nhstepm = nhstepm/hstepm;
4611:
4612: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4613: oldm=oldms;savm=savms;
4614: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4615:
4616: for (h=0; h<=nhstepm; h++){
4617: if (h==(int) (calagedatem+YEARM*cpt)) {
4618: fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4619: }
4620: for(j=1; j<=nlstate+ndeath;j++) {
4621: kk1=0.;kk2=0;
4622: for(i=1; i<=nlstate;i++) {
4623: if (mobilav==1)
4624: kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
4625: else {
4626: kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
4627: }
4628: }
4629: if (h==(int)(calagedatem+12*cpt)){
4630: tabpop[(int)(agedeb)][j][cptcod]=kk1;
4631: /*fprintf(ficrespop," %.3f", kk1);
4632: if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
4633: }
4634: }
4635: for(i=1; i<=nlstate;i++){
4636: kk1=0.;
4637: for(j=1; j<=nlstate;j++){
4638: kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
4639: }
4640: tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
4641: }
4642:
4643: if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
4644: fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
4645: }
4646: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4647: }
4648: }
4649:
4650: /******/
4651:
4652: for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
4653: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4654: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4655: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4656: nhstepm = nhstepm/hstepm;
4657:
4658: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4659: oldm=oldms;savm=savms;
4660: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4661: for (h=0; h<=nhstepm; h++){
4662: if (h==(int) (calagedatem+YEARM*cpt)) {
4663: fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4664: }
4665: for(j=1; j<=nlstate+ndeath;j++) {
4666: kk1=0.;kk2=0;
4667: for(i=1; i<=nlstate;i++) {
4668: kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];
4669: }
4670: if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);
4671: }
4672: }
4673: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4674: }
4675: }
4676: }
4677: }
4678:
4679: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4680:
4681: if (popforecast==1) {
4682: free_ivector(popage,0,AGESUP);
4683: free_vector(popeffectif,0,AGESUP);
4684: free_vector(popcount,0,AGESUP);
4685: }
4686: free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4687: free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4688: fclose(ficrespop);
4689: } /* End of popforecast */
4690:
4691: int fileappend(FILE *fichier, char *optionfich)
4692: {
4693: if((fichier=fopen(optionfich,"a"))==NULL) {
4694: printf("Problem with file: %s\n", optionfich);
4695: fprintf(ficlog,"Problem with file: %s\n", optionfich);
4696: return (0);
4697: }
4698: fflush(fichier);
4699: return (1);
4700: }
4701:
4702:
4703: /**************** function prwizard **********************/
4704: void prwizard(int ncovmodel, int nlstate, int ndeath, char model[], FILE *ficparo)
4705: {
4706:
4707: /* Wizard to print covariance matrix template */
4708:
1.164 brouard 4709: char ca[32], cb[32];
4710: int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126 brouard 4711: int numlinepar;
4712:
4713: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4714: fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4715: for(i=1; i <=nlstate; i++){
4716: jj=0;
4717: for(j=1; j <=nlstate+ndeath; j++){
4718: if(j==i) continue;
4719: jj++;
4720: /*ca[0]= k+'a'-1;ca[1]='\0';*/
4721: printf("%1d%1d",i,j);
4722: fprintf(ficparo,"%1d%1d",i,j);
4723: for(k=1; k<=ncovmodel;k++){
4724: /* printf(" %lf",param[i][j][k]); */
4725: /* fprintf(ficparo," %lf",param[i][j][k]); */
4726: printf(" 0.");
4727: fprintf(ficparo," 0.");
4728: }
4729: printf("\n");
4730: fprintf(ficparo,"\n");
4731: }
4732: }
4733: printf("# Scales (for hessian or gradient estimation)\n");
4734: fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
4735: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
4736: for(i=1; i <=nlstate; i++){
4737: jj=0;
4738: for(j=1; j <=nlstate+ndeath; j++){
4739: if(j==i) continue;
4740: jj++;
4741: fprintf(ficparo,"%1d%1d",i,j);
4742: printf("%1d%1d",i,j);
4743: fflush(stdout);
4744: for(k=1; k<=ncovmodel;k++){
4745: /* printf(" %le",delti3[i][j][k]); */
4746: /* fprintf(ficparo," %le",delti3[i][j][k]); */
4747: printf(" 0.");
4748: fprintf(ficparo," 0.");
4749: }
4750: numlinepar++;
4751: printf("\n");
4752: fprintf(ficparo,"\n");
4753: }
4754: }
4755: printf("# Covariance matrix\n");
4756: /* # 121 Var(a12)\n\ */
4757: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4758: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
4759: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
4760: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
4761: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
4762: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
4763: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4764: fflush(stdout);
4765: fprintf(ficparo,"# Covariance matrix\n");
4766: /* # 121 Var(a12)\n\ */
4767: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4768: /* # ...\n\ */
4769: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4770:
4771: for(itimes=1;itimes<=2;itimes++){
4772: jj=0;
4773: for(i=1; i <=nlstate; i++){
4774: for(j=1; j <=nlstate+ndeath; j++){
4775: if(j==i) continue;
4776: for(k=1; k<=ncovmodel;k++){
4777: jj++;
4778: ca[0]= k+'a'-1;ca[1]='\0';
4779: if(itimes==1){
4780: printf("#%1d%1d%d",i,j,k);
4781: fprintf(ficparo,"#%1d%1d%d",i,j,k);
4782: }else{
4783: printf("%1d%1d%d",i,j,k);
4784: fprintf(ficparo,"%1d%1d%d",i,j,k);
4785: /* printf(" %.5le",matcov[i][j]); */
4786: }
4787: ll=0;
4788: for(li=1;li <=nlstate; li++){
4789: for(lj=1;lj <=nlstate+ndeath; lj++){
4790: if(lj==li) continue;
4791: for(lk=1;lk<=ncovmodel;lk++){
4792: ll++;
4793: if(ll<=jj){
4794: cb[0]= lk +'a'-1;cb[1]='\0';
4795: if(ll<jj){
4796: if(itimes==1){
4797: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4798: fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4799: }else{
4800: printf(" 0.");
4801: fprintf(ficparo," 0.");
4802: }
4803: }else{
4804: if(itimes==1){
4805: printf(" Var(%s%1d%1d)",ca,i,j);
4806: fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
4807: }else{
4808: printf(" 0.");
4809: fprintf(ficparo," 0.");
4810: }
4811: }
4812: }
4813: } /* end lk */
4814: } /* end lj */
4815: } /* end li */
4816: printf("\n");
4817: fprintf(ficparo,"\n");
4818: numlinepar++;
4819: } /* end k*/
4820: } /*end j */
4821: } /* end i */
4822: } /* end itimes */
4823:
4824: } /* end of prwizard */
4825: /******************* Gompertz Likelihood ******************************/
4826: double gompertz(double x[])
4827: {
4828: double A,B,L=0.0,sump=0.,num=0.;
4829: int i,n=0; /* n is the size of the sample */
4830:
4831: for (i=0;i<=imx-1 ; i++) {
4832: sump=sump+weight[i];
4833: /* sump=sump+1;*/
4834: num=num+1;
4835: }
4836:
4837:
4838: /* for (i=0; i<=imx; i++)
4839: 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]);*/
4840:
4841: for (i=1;i<=imx ; i++)
4842: {
4843: if (cens[i] == 1 && wav[i]>1)
4844: A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
4845:
4846: if (cens[i] == 0 && wav[i]>1)
4847: A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
4848: +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);
4849:
4850: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
4851: if (wav[i] > 1 ) { /* ??? */
4852: L=L+A*weight[i];
4853: /* 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]);*/
4854: }
4855: }
4856:
4857: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
4858:
4859: return -2*L*num/sump;
4860: }
4861:
1.136 brouard 4862: #ifdef GSL
4863: /******************* Gompertz_f Likelihood ******************************/
4864: double gompertz_f(const gsl_vector *v, void *params)
4865: {
4866: double A,B,LL=0.0,sump=0.,num=0.;
4867: double *x= (double *) v->data;
4868: int i,n=0; /* n is the size of the sample */
4869:
4870: for (i=0;i<=imx-1 ; i++) {
4871: sump=sump+weight[i];
4872: /* sump=sump+1;*/
4873: num=num+1;
4874: }
4875:
4876:
4877: /* for (i=0; i<=imx; i++)
4878: 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]);*/
4879: printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
4880: for (i=1;i<=imx ; i++)
4881: {
4882: if (cens[i] == 1 && wav[i]>1)
4883: A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
4884:
4885: if (cens[i] == 0 && wav[i]>1)
4886: A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
4887: +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);
4888:
4889: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
4890: if (wav[i] > 1 ) { /* ??? */
4891: LL=LL+A*weight[i];
4892: /* 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]);*/
4893: }
4894: }
4895:
4896: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
4897: printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
4898:
4899: return -2*LL*num/sump;
4900: }
4901: #endif
4902:
1.126 brouard 4903: /******************* Printing html file ***********/
4904: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
4905: int lastpass, int stepm, int weightopt, char model[],\
4906: int imx, double p[],double **matcov,double agemortsup){
4907: int i,k;
4908:
4909: fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
4910: fprintf(fichtm," mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
4911: for (i=1;i<=2;i++)
4912: 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]));
4913: fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
4914: fprintf(fichtm,"</ul>");
4915:
4916: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
4917:
4918: 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>");
4919:
4920: for (k=agegomp;k<(agemortsup-2);k++)
4921: 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]);
4922:
4923:
4924: fflush(fichtm);
4925: }
4926:
4927: /******************* Gnuplot file **************/
4928: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4929:
4930: char dirfileres[132],optfileres[132];
1.164 brouard 4931:
1.126 brouard 4932: int ng;
4933:
4934:
4935: /*#ifdef windows */
4936: fprintf(ficgp,"cd \"%s\" \n",pathc);
4937: /*#endif */
4938:
4939:
4940: strcpy(dirfileres,optionfilefiname);
4941: strcpy(optfileres,"vpl");
4942: fprintf(ficgp,"set out \"graphmort.png\"\n ");
4943: fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
1.145 brouard 4944: fprintf(ficgp, "set ter png small size 320, 240\n set log y\n");
4945: /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126 brouard 4946: fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
4947:
4948: }
4949:
1.136 brouard 4950: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
4951: {
1.126 brouard 4952:
1.136 brouard 4953: /*-------- data file ----------*/
4954: FILE *fic;
4955: char dummy[]=" ";
1.164 brouard 4956: int i=0, j=0, n=0;
1.136 brouard 4957: int linei, month, year,iout;
4958: char line[MAXLINE], linetmp[MAXLINE];
1.164 brouard 4959: char stra[MAXLINE], strb[MAXLINE];
1.136 brouard 4960: char *stratrunc;
4961: int lstra;
1.126 brouard 4962:
4963:
1.136 brouard 4964: if((fic=fopen(datafile,"r"))==NULL) {
4965: printf("Problem while opening datafile: %s\n", datafile);return 1;
4966: fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
4967: }
1.126 brouard 4968:
1.136 brouard 4969: i=1;
4970: linei=0;
4971: while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
4972: linei=linei+1;
4973: for(j=strlen(line); j>=0;j--){ /* Untabifies line */
4974: if(line[j] == '\t')
4975: line[j] = ' ';
4976: }
4977: for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
4978: ;
4979: };
4980: line[j+1]=0; /* Trims blanks at end of line */
4981: if(line[0]=='#'){
4982: fprintf(ficlog,"Comment line\n%s\n",line);
4983: printf("Comment line\n%s\n",line);
4984: continue;
4985: }
4986: trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164 brouard 4987: strcpy(line, linetmp);
1.136 brouard 4988:
1.126 brouard 4989:
1.136 brouard 4990: for (j=maxwav;j>=1;j--){
1.137 brouard 4991: cutv(stra, strb, line, ' ');
1.136 brouard 4992: if(strb[0]=='.') { /* Missing status */
4993: lval=-1;
4994: }else{
4995: errno=0;
4996: lval=strtol(strb,&endptr,10);
4997: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
4998: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 4999: 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);
5000: 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 5001: return 1;
5002: }
5003: }
5004: s[j][i]=lval;
5005:
5006: strcpy(line,stra);
5007: cutv(stra, strb,line,' ');
5008: if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
5009: }
1.145 brouard 5010: else if(iout=sscanf(strb,"%s.",dummy) != 0){
1.136 brouard 5011: month=99;
5012: year=9999;
5013: }else{
1.141 brouard 5014: 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);
5015: 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 5016: return 1;
5017: }
5018: anint[j][i]= (double) year;
5019: mint[j][i]= (double)month;
5020: strcpy(line,stra);
5021: } /* ENd Waves */
5022:
5023: cutv(stra, strb,line,' ');
5024: if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
5025: }
5026: else if(iout=sscanf(strb,"%s.",dummy) != 0){
5027: month=99;
5028: year=9999;
5029: }else{
1.141 brouard 5030: 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);
5031: 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 5032: return 1;
5033: }
5034: andc[i]=(double) year;
5035: moisdc[i]=(double) month;
5036: strcpy(line,stra);
5037:
5038: cutv(stra, strb,line,' ');
5039: if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
5040: }
1.145 brouard 5041: else if(iout=sscanf(strb,"%s.", dummy) != 0){
1.136 brouard 5042: month=99;
5043: year=9999;
5044: }else{
1.141 brouard 5045: printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be a date of birth (mm/yyyy or .). Exiting.\n",strb, linei,i,line);
5046: fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be a date of birth (mm/yyyy or .). Exiting.\n",strb, linei,i,line);fflush(ficlog);
1.136 brouard 5047: return 1;
5048: }
5049: if (year==9999) {
1.141 brouard 5050: 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);
5051: 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 5052: return 1;
1.126 brouard 5053:
1.136 brouard 5054: }
5055: annais[i]=(double)(year);
5056: moisnais[i]=(double)(month);
5057: strcpy(line,stra);
5058:
5059: cutv(stra, strb,line,' ');
5060: errno=0;
5061: dval=strtod(strb,&endptr);
5062: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5063: printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight. Exiting.\n",dval, i,line,linei);
5064: 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 5065: fflush(ficlog);
5066: return 1;
5067: }
5068: weight[i]=dval;
5069: strcpy(line,stra);
5070:
5071: for (j=ncovcol;j>=1;j--){
5072: cutv(stra, strb,line,' ');
5073: if(strb[0]=='.') { /* Missing status */
5074: lval=-1;
5075: }else{
5076: errno=0;
5077: lval=strtol(strb,&endptr,10);
5078: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5079: 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);
5080: 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 5081: return 1;
5082: }
5083: }
5084: if(lval <-1 || lval >1){
1.141 brouard 5085: printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 5086: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5087: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5088: For example, for multinomial values like 1, 2 and 3,\n \
5089: build V1=0 V2=0 for the reference value (1),\n \
5090: V1=1 V2=0 for (2) \n \
5091: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5092: output of IMaCh is often meaningless.\n \
5093: Exiting.\n",lval,linei, i,line,j);
1.141 brouard 5094: fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 5095: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5096: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5097: For example, for multinomial values like 1, 2 and 3,\n \
5098: build V1=0 V2=0 for the reference value (1),\n \
5099: V1=1 V2=0 for (2) \n \
5100: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5101: output of IMaCh is often meaningless.\n \
5102: Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
5103: return 1;
5104: }
5105: covar[j][i]=(double)(lval);
5106: strcpy(line,stra);
5107: }
5108: lstra=strlen(stra);
5109:
5110: if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
5111: stratrunc = &(stra[lstra-9]);
5112: num[i]=atol(stratrunc);
5113: }
5114: else
5115: num[i]=atol(stra);
5116: /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
5117: 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;}*/
5118:
5119: i=i+1;
5120: } /* End loop reading data */
1.126 brouard 5121:
1.136 brouard 5122: *imax=i-1; /* Number of individuals */
5123: fclose(fic);
5124:
5125: return (0);
1.164 brouard 5126: /* endread: */
1.136 brouard 5127: printf("Exiting readdata: ");
5128: fclose(fic);
5129: return (1);
1.126 brouard 5130:
5131:
5132:
1.136 brouard 5133: }
1.145 brouard 5134: void removespace(char *str) {
5135: char *p1 = str, *p2 = str;
5136: do
5137: while (*p2 == ' ')
5138: p2++;
5139: while (*p1++ = *p2++);
5140: }
5141:
5142: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
5143: * Model V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age
5144: * - cptcovt total number of covariates of the model nbocc(+)+1 = 8
5145: * - cptcovn or number of covariates k of the models excluding age*products =6
5146: * - cptcovage number of covariates with age*products =2
5147: * - cptcovs number of simple covariates
5148: * - 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
5149: * which is a new column after the 9 (ncovcol) variables.
5150: * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
5151: * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
5152: * Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
5153: * - Tvard[k] p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
5154: */
1.136 brouard 5155: {
1.145 brouard 5156: int i, j, k, ks;
1.164 brouard 5157: int j1, k1, k2;
1.136 brouard 5158: char modelsav[80];
1.145 brouard 5159: char stra[80], strb[80], strc[80], strd[80],stre[80];
1.136 brouard 5160:
1.145 brouard 5161: /*removespace(model);*/
1.136 brouard 5162: if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145 brouard 5163: j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
5164: j=nbocc(model,'+'); /**< j=Number of '+' */
5165: j1=nbocc(model,'*'); /**< j1=Number of '*' */
5166: cptcovs=j+1-j1; /**< Number of simple covariates V1+V2*age+V3 +V3*V4=> V1 + V3 =2 */
5167: cptcovt= j+1; /* Number of total covariates in the model V1 + V2*age+ V3 + V3*V4=> 4*/
5168: /* including age products which are counted in cptcovage.
5169: /* but the covariates which are products must be treated separately: ncovn=4- 2=2 (V1+V3). */
5170: cptcovprod=j1; /**< Number of products V1*V2 +v3*age = 2 */
5171: cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1 */
1.136 brouard 5172: strcpy(modelsav,model);
1.137 brouard 5173: if (strstr(model,"AGE") !=0){
5174: printf("Error. AGE must be in lower case 'age' model=%s ",model);
5175: fprintf(ficlog,"Error. AGE must be in lower case model=%s ",model);fflush(ficlog);
1.136 brouard 5176: return 1;
5177: }
1.141 brouard 5178: if (strstr(model,"v") !=0){
5179: printf("Error. 'v' must be in upper case 'V' model=%s ",model);
5180: fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
5181: return 1;
5182: }
1.136 brouard 5183:
1.145 brouard 5184: /* Design
5185: * V1 V2 V3 V4 V5 V6 V7 V8 V9 Weight
5186: * < ncovcol=8 >
5187: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
5188: * k= 1 2 3 4 5 6 7 8
5189: * cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
5190: * covar[k,i], value of kth covariate if not including age for individual i:
5191: * covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
5192: * Tvar[k] # of the kth covariate: Tvar[1]=2 Tvar[4]=3 Tvar[8]=8
5193: * if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and
5194: * Tage[++cptcovage]=k
5195: * if products, new covar are created after ncovcol with k1
5196: * Tvar[k]=ncovcol+k1; # of the kth covariate product: Tvar[5]=ncovcol+1=10 Tvar[6]=ncovcol+1=11
5197: * Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
5198: * 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
5199: * Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
5200: * Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
5201: * V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
5202: * < ncovcol=8 >
5203: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 d1 d1 d2 d2
5204: * k= 1 2 3 4 5 6 7 8 9 10 11 12
5205: * Tvar[k]= 2 1 3 3 10 11 8 8 5 6 7 8
5206: * p Tvar[1]@12={2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5207: * p Tprod[1]@2={ 6, 5}
5208: *p Tvard[1][1]@4= {7, 8, 5, 6}
5209: * covar[k][i]= V2 V1 ? V3 V5*V6? V7*V8? ? V8
5210: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
5211: *How to reorganize?
5212: * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
5213: * Tvars {2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5214: * {2, 1, 4, 8, 5, 6, 3, 7}
5215: * Struct []
5216: */
5217:
1.136 brouard 5218: /* This loop fills the array Tvar from the string 'model'.*/
5219: /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
1.137 brouard 5220: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 */
5221: /* k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
5222: /* k=3 V4 Tvar[k=3]= 4 (from V4) */
5223: /* k=2 V1 Tvar[k=2]= 1 (from V1) */
5224: /* k=1 Tvar[1]=2 (from V2) */
5225: /* k=5 Tvar[5] */
5226: /* for (k=1; k<=cptcovn;k++) { */
5227: /* cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
5228: /* } */
5229: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.145 brouard 5230: /*
5231: * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
5232: for(k=cptcovt; k>=1;k--) /**< Number of covariates */
5233: Tvar[k]=0;
5234: cptcovage=0;
5235: for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
5236: cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+'
5237: modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */
1.137 brouard 5238: if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
1.136 brouard 5239: /* printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
5240: /*scanf("%d",i);*/
1.145 brouard 5241: if (strchr(strb,'*')) { /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
5242: cutl(strc,strd,strb,'*'); /**< strd*strc Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
5243: if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
5244: /* covar is not filled and then is empty */
1.136 brouard 5245: cptcovprod--;
1.145 brouard 5246: cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
5247: Tvar[k]=atoi(stre); /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2 */
1.136 brouard 5248: cptcovage++; /* Sums the number of covariates which include age as a product */
1.137 brouard 5249: Tage[cptcovage]=k; /* Tage[1] = 4 */
1.136 brouard 5250: /*printf("stre=%s ", stre);*/
1.137 brouard 5251: } else if (strcmp(strd,"age")==0) { /* or age*Vn */
1.136 brouard 5252: cptcovprod--;
1.145 brouard 5253: cutl(stre,strb,strc,'V');
1.136 brouard 5254: Tvar[k]=atoi(stre);
5255: cptcovage++;
5256: Tage[cptcovage]=k;
1.137 brouard 5257: } else { /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2 strb=V3*V2*/
5258: /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
1.145 brouard 5259: cptcovn++;
5260: cptcovprodnoage++;k1++;
5261: cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
5262: Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
1.137 brouard 5263: because this model-covariate is a construction we invent a new column
5264: ncovcol + k1
5265: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
5266: Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
1.145 brouard 5267: cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
1.137 brouard 5268: Tprod[k1]=k; /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 */
1.145 brouard 5269: Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
5270: Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
5271: k2=k2+2;
5272: Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
5273: Tvar[cptcovt+k2+1]=Tvard[k1][2]; /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
1.137 brouard 5274: for (i=1; i<=lastobs;i++){
5275: /* Computes the new covariate which is a product of
1.145 brouard 5276: covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
1.136 brouard 5277: covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
1.137 brouard 5278: }
5279: } /* End age is not in the model */
5280: } /* End if model includes a product */
1.136 brouard 5281: else { /* no more sum */
5282: /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
5283: /* scanf("%d",i);*/
1.145 brouard 5284: cutl(strd,strc,strb,'V');
5285: ks++; /**< Number of simple covariates */
5286: cptcovn++;
5287: Tvar[k]=atoi(strd);
1.136 brouard 5288: }
1.137 brouard 5289: strcpy(modelsav,stra); /* modelsav=V2+V1+V4 stra=V2+V1+V4 */
1.136 brouard 5290: /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
5291: scanf("%d",i);*/
5292: } /* end of loop + */
5293: } /* end model */
5294:
5295: /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
5296: If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
5297:
5298: /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
5299: printf("cptcovprod=%d ", cptcovprod);
5300: fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
5301:
5302: scanf("%d ",i);*/
5303:
5304:
1.137 brouard 5305: return (0); /* with covar[new additional covariate if product] and Tage if age */
1.164 brouard 5306: /*endread:*/
1.136 brouard 5307: printf("Exiting decodemodel: ");
5308: return (1);
5309: }
5310:
5311: calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
5312: {
5313: int i, m;
5314:
5315: for (i=1; i<=imx; i++) {
5316: for(m=2; (m<= maxwav); m++) {
5317: if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
5318: anint[m][i]=9999;
5319: s[m][i]=-1;
5320: }
5321: if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
5322: *nberr++;
5323: printf("Error! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown, you must set an arbitrary year of death or he/she is skipped and results are biased\n",(int)moisdc[i],(int)andc[i],num[i],i);
5324: fprintf(ficlog,"Error! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown, you must set an arbitrary year of death or he/she is skipped and results are biased\n",(int)moisdc[i],(int)andc[i],num[i],i);
5325: s[m][i]=-1;
5326: }
5327: if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
5328: *nberr++;
5329: 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]);
5330: 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]);
5331: s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
5332: }
5333: }
5334: }
5335:
5336: for (i=1; i<=imx; i++) {
5337: agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
5338: for(m=firstpass; (m<= lastpass); m++){
5339: if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
5340: if (s[m][i] >= nlstate+1) {
5341: if(agedc[i]>0)
5342: if((int)moisdc[i]!=99 && (int)andc[i]!=9999)
5343: agev[m][i]=agedc[i];
5344: /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
5345: else {
5346: if ((int)andc[i]!=9999){
5347: nbwarn++;
5348: printf("Warning negative age at death: %ld line:%d\n",num[i],i);
5349: fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
5350: agev[m][i]=-1;
5351: }
5352: }
5353: }
5354: else if(s[m][i] !=9){ /* Standard case, age in fractional
5355: years but with the precision of a month */
5356: agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
5357: if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
5358: agev[m][i]=1;
5359: else if(agev[m][i] < *agemin){
5360: *agemin=agev[m][i];
5361: printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
5362: }
5363: else if(agev[m][i] >*agemax){
5364: *agemax=agev[m][i];
1.156 brouard 5365: /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136 brouard 5366: }
5367: /*agev[m][i]=anint[m][i]-annais[i];*/
5368: /* agev[m][i] = age[i]+2*m;*/
5369: }
5370: else { /* =9 */
5371: agev[m][i]=1;
5372: s[m][i]=-1;
5373: }
5374: }
5375: else /*= 0 Unknown */
5376: agev[m][i]=1;
5377: }
5378:
5379: }
5380: for (i=1; i<=imx; i++) {
5381: for(m=firstpass; (m<=lastpass); m++){
5382: if (s[m][i] > (nlstate+ndeath)) {
5383: *nberr++;
5384: 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);
5385: 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);
5386: return 1;
5387: }
5388: }
5389: }
5390:
5391: /*for (i=1; i<=imx; i++){
5392: for (m=firstpass; (m<lastpass); m++){
5393: printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
5394: }
5395:
5396: }*/
5397:
5398:
1.139 brouard 5399: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
5400: fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
1.136 brouard 5401:
5402: return (0);
1.164 brouard 5403: /* endread:*/
1.136 brouard 5404: printf("Exiting calandcheckages: ");
5405: return (1);
5406: }
5407:
5408:
5409: /***********************************************/
5410: /**************** Main Program *****************/
5411: /***********************************************/
5412:
5413: int main(int argc, char *argv[])
5414: {
5415: #ifdef GSL
5416: const gsl_multimin_fminimizer_type *T;
5417: size_t iteri = 0, it;
5418: int rval = GSL_CONTINUE;
5419: int status = GSL_SUCCESS;
5420: double ssval;
5421: #endif
5422: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164 brouard 5423: int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
5424:
5425: int jj, ll, li, lj, lk;
1.136 brouard 5426: int numlinepar=0; /* Current linenumber of parameter file */
5427: int itimes;
5428: int NDIM=2;
5429: int vpopbased=0;
5430:
1.164 brouard 5431: char ca[32], cb[32];
1.136 brouard 5432: /* FILE *fichtm; *//* Html File */
5433: /* FILE *ficgp;*/ /*Gnuplot File */
5434: struct stat info;
1.164 brouard 5435: double agedeb;
1.136 brouard 5436: double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
5437:
1.165 ! brouard 5438: double fret;
1.136 brouard 5439: double dum; /* Dummy variable */
5440: double ***p3mat;
5441: double ***mobaverage;
1.164 brouard 5442:
5443: char line[MAXLINE];
1.136 brouard 5444: char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
5445: char pathr[MAXLINE], pathimach[MAXLINE];
1.164 brouard 5446: char *tok, *val; /* pathtot */
1.136 brouard 5447: int firstobs=1, lastobs=10;
1.164 brouard 5448: int c, h , cpt;
5449: int jl;
5450: int i1, j1, jk, stepsize;
5451: int *tab;
1.136 brouard 5452: int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
5453: int mobilav=0,popforecast=0;
5454: int hstepm, nhstepm;
5455: int agemortsup;
5456: float sumlpop=0.;
5457: double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
5458: double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
5459:
1.164 brouard 5460: double bage=0, fage=110, age, agelim, agebase;
1.136 brouard 5461: double ftolpl=FTOL;
5462: double **prlim;
5463: double ***param; /* Matrix of parameters */
5464: double *p;
5465: double **matcov; /* Matrix of covariance */
5466: double ***delti3; /* Scale */
5467: double *delti; /* Scale */
5468: double ***eij, ***vareij;
5469: double **varpl; /* Variances of prevalence limits by age */
5470: double *epj, vepp;
1.164 brouard 5471:
1.136 brouard 5472: double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
5473: double **ximort;
1.145 brouard 5474: char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136 brouard 5475: int *dcwave;
5476:
1.164 brouard 5477: char z[1]="c";
1.136 brouard 5478:
5479: /*char *strt;*/
5480: char strtend[80];
1.126 brouard 5481:
1.164 brouard 5482:
1.126 brouard 5483: /* setlocale (LC_ALL, ""); */
5484: /* bindtextdomain (PACKAGE, LOCALEDIR); */
5485: /* textdomain (PACKAGE); */
5486: /* setlocale (LC_CTYPE, ""); */
5487: /* setlocale (LC_MESSAGES, ""); */
5488:
5489: /* gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157 brouard 5490: rstart_time = time(NULL);
5491: /* (void) gettimeofday(&start_time,&tzp);*/
5492: start_time = *localtime(&rstart_time);
1.126 brouard 5493: curr_time=start_time;
1.157 brouard 5494: /*tml = *localtime(&start_time.tm_sec);*/
5495: /* strcpy(strstart,asctime(&tml)); */
5496: strcpy(strstart,asctime(&start_time));
1.126 brouard 5497:
5498: /* printf("Localtime (at start)=%s",strstart); */
1.157 brouard 5499: /* tp.tm_sec = tp.tm_sec +86400; */
5500: /* tm = *localtime(&start_time.tm_sec); */
1.126 brouard 5501: /* tmg.tm_year=tmg.tm_year +dsign*dyear; */
5502: /* tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
5503: /* tmg.tm_hour=tmg.tm_hour + 1; */
1.157 brouard 5504: /* tp.tm_sec = mktime(&tmg); */
1.126 brouard 5505: /* strt=asctime(&tmg); */
5506: /* printf("Time(after) =%s",strstart); */
5507: /* (void) time (&time_value);
5508: * printf("time=%d,t-=%d\n",time_value,time_value-86400);
5509: * tm = *localtime(&time_value);
5510: * strstart=asctime(&tm);
5511: * printf("tim_value=%d,asctime=%s\n",time_value,strstart);
5512: */
5513:
5514: nberr=0; /* Number of errors and warnings */
5515: nbwarn=0;
5516: getcwd(pathcd, size);
5517:
5518: printf("\n%s\n%s",version,fullversion);
5519: if(argc <=1){
5520: printf("\nEnter the parameter file name: ");
5521: fgets(pathr,FILENAMELENGTH,stdin);
5522: i=strlen(pathr);
5523: if(pathr[i-1]=='\n')
5524: pathr[i-1]='\0';
1.156 brouard 5525: i=strlen(pathr);
5526: if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
5527: pathr[i-1]='\0';
1.126 brouard 5528: for (tok = pathr; tok != NULL; ){
5529: printf("Pathr |%s|\n",pathr);
5530: while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
5531: printf("val= |%s| pathr=%s\n",val,pathr);
5532: strcpy (pathtot, val);
5533: if(pathr[0] == '\0') break; /* Dirty */
5534: }
5535: }
5536: else{
5537: strcpy(pathtot,argv[1]);
5538: }
5539: /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
5540: /*cygwin_split_path(pathtot,path,optionfile);
5541: printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
5542: /* cutv(path,optionfile,pathtot,'\\');*/
5543:
5544: /* Split argv[0], imach program to get pathimach */
5545: printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
5546: split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
5547: printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
5548: /* strcpy(pathimach,argv[0]); */
5549: /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
5550: split(pathtot,path,optionfile,optionfilext,optionfilefiname);
5551: printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
5552: chdir(path); /* Can be a relative path */
5553: if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
5554: printf("Current directory %s!\n",pathcd);
5555: strcpy(command,"mkdir ");
5556: strcat(command,optionfilefiname);
5557: if((outcmd=system(command)) != 0){
5558: printf("Problem creating directory or it already exists %s%s, err=%d\n",path,optionfilefiname,outcmd);
5559: /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
5560: /* fclose(ficlog); */
5561: /* exit(1); */
5562: }
5563: /* if((imk=mkdir(optionfilefiname))<0){ */
5564: /* perror("mkdir"); */
5565: /* } */
5566:
5567: /*-------- arguments in the command line --------*/
5568:
5569: /* Log file */
5570: strcat(filelog, optionfilefiname);
5571: strcat(filelog,".log"); /* */
5572: if((ficlog=fopen(filelog,"w"))==NULL) {
5573: printf("Problem with logfile %s\n",filelog);
5574: goto end;
5575: }
5576: fprintf(ficlog,"Log filename:%s\n",filelog);
5577: fprintf(ficlog,"\n%s\n%s",version,fullversion);
5578: fprintf(ficlog,"\nEnter the parameter file name: \n");
5579: fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
5580: path=%s \n\
5581: optionfile=%s\n\
5582: optionfilext=%s\n\
1.156 brouard 5583: optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126 brouard 5584:
5585: printf("Local time (at start):%s",strstart);
5586: fprintf(ficlog,"Local time (at start): %s",strstart);
5587: fflush(ficlog);
5588: /* (void) gettimeofday(&curr_time,&tzp); */
1.157 brouard 5589: /* printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126 brouard 5590:
5591: /* */
5592: strcpy(fileres,"r");
5593: strcat(fileres, optionfilefiname);
5594: strcat(fileres,".txt"); /* Other files have txt extension */
5595:
5596: /*---------arguments file --------*/
5597:
5598: if((ficpar=fopen(optionfile,"r"))==NULL) {
1.155 brouard 5599: printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
5600: fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126 brouard 5601: fflush(ficlog);
1.149 brouard 5602: /* goto end; */
5603: exit(70);
1.126 brouard 5604: }
5605:
5606:
5607:
5608: strcpy(filereso,"o");
5609: strcat(filereso,fileres);
5610: if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
5611: printf("Problem with Output resultfile: %s\n", filereso);
5612: fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
5613: fflush(ficlog);
5614: goto end;
5615: }
5616:
5617: /* Reads comments: lines beginning with '#' */
5618: numlinepar=0;
5619: while((c=getc(ficpar))=='#' && c!= EOF){
5620: ungetc(c,ficpar);
5621: fgets(line, MAXLINE, ficpar);
5622: numlinepar++;
1.141 brouard 5623: fputs(line,stdout);
1.126 brouard 5624: fputs(line,ficparo);
5625: fputs(line,ficlog);
5626: }
5627: ungetc(c,ficpar);
5628:
5629: 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);
5630: numlinepar++;
5631: 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);
5632: 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);
5633: 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);
5634: fflush(ficlog);
5635: while((c=getc(ficpar))=='#' && c!= EOF){
5636: ungetc(c,ficpar);
5637: fgets(line, MAXLINE, ficpar);
5638: numlinepar++;
1.141 brouard 5639: fputs(line, stdout);
5640: //puts(line);
1.126 brouard 5641: fputs(line,ficparo);
5642: fputs(line,ficlog);
5643: }
5644: ungetc(c,ficpar);
5645:
5646:
1.145 brouard 5647: covar=matrix(0,NCOVMAX,1,n); /**< used in readdata */
1.136 brouard 5648: cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
5649: /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
5650: v1+v2*age+v2*v3 makes cptcovn = 3
5651: */
5652: if (strlen(model)>1)
1.145 brouard 5653: 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*/
5654: else
5655: ncovmodel=2;
1.126 brouard 5656: nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
1.133 brouard 5657: nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
5658: npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131 brouard 5659: if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
5660: 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);
5661: 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);
5662: fflush(stdout);
5663: fclose (ficlog);
5664: goto end;
5665: }
1.126 brouard 5666: delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5667: delti=delti3[1][1];
5668: /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
5669: if(mle==-1){ /* Print a wizard for help writing covariance matrix */
5670: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
5671: printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
5672: fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
5673: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
5674: fclose (ficparo);
5675: fclose (ficlog);
5676: goto end;
5677: exit(0);
5678: }
5679: else if(mle==-3) {
5680: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
5681: printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
5682: fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
5683: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5684: matcov=matrix(1,npar,1,npar);
5685: }
5686: else{
1.145 brouard 5687: /* Read guessed parameters */
1.126 brouard 5688: /* Reads comments: lines beginning with '#' */
5689: while((c=getc(ficpar))=='#' && c!= EOF){
5690: ungetc(c,ficpar);
5691: fgets(line, MAXLINE, ficpar);
5692: numlinepar++;
1.141 brouard 5693: fputs(line,stdout);
1.126 brouard 5694: fputs(line,ficparo);
5695: fputs(line,ficlog);
5696: }
5697: ungetc(c,ficpar);
5698:
5699: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5700: for(i=1; i <=nlstate; i++){
5701: j=0;
5702: for(jj=1; jj <=nlstate+ndeath; jj++){
5703: if(jj==i) continue;
5704: j++;
5705: fscanf(ficpar,"%1d%1d",&i1,&j1);
5706: if ((i1 != i) && (j1 != j)){
5707: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
5708: It might be a problem of design; if ncovcol and the model are correct\n \
5709: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
5710: exit(1);
5711: }
5712: fprintf(ficparo,"%1d%1d",i1,j1);
5713: if(mle==1)
5714: printf("%1d%1d",i,j);
5715: fprintf(ficlog,"%1d%1d",i,j);
5716: for(k=1; k<=ncovmodel;k++){
5717: fscanf(ficpar," %lf",¶m[i][j][k]);
5718: if(mle==1){
5719: printf(" %lf",param[i][j][k]);
5720: fprintf(ficlog," %lf",param[i][j][k]);
5721: }
5722: else
5723: fprintf(ficlog," %lf",param[i][j][k]);
5724: fprintf(ficparo," %lf",param[i][j][k]);
5725: }
5726: fscanf(ficpar,"\n");
5727: numlinepar++;
5728: if(mle==1)
5729: printf("\n");
5730: fprintf(ficlog,"\n");
5731: fprintf(ficparo,"\n");
5732: }
5733: }
5734: fflush(ficlog);
5735:
1.145 brouard 5736: /* Reads scales values */
1.126 brouard 5737: p=param[1][1];
5738:
5739: /* Reads comments: lines beginning with '#' */
5740: while((c=getc(ficpar))=='#' && c!= EOF){
5741: ungetc(c,ficpar);
5742: fgets(line, MAXLINE, ficpar);
5743: numlinepar++;
1.141 brouard 5744: fputs(line,stdout);
1.126 brouard 5745: fputs(line,ficparo);
5746: fputs(line,ficlog);
5747: }
5748: ungetc(c,ficpar);
5749:
5750: for(i=1; i <=nlstate; i++){
5751: for(j=1; j <=nlstate+ndeath-1; j++){
5752: fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164 brouard 5753: if ( (i1-i) * (j1-j) != 0){
1.126 brouard 5754: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
5755: exit(1);
5756: }
5757: printf("%1d%1d",i,j);
5758: fprintf(ficparo,"%1d%1d",i1,j1);
5759: fprintf(ficlog,"%1d%1d",i1,j1);
5760: for(k=1; k<=ncovmodel;k++){
5761: fscanf(ficpar,"%le",&delti3[i][j][k]);
5762: printf(" %le",delti3[i][j][k]);
5763: fprintf(ficparo," %le",delti3[i][j][k]);
5764: fprintf(ficlog," %le",delti3[i][j][k]);
5765: }
5766: fscanf(ficpar,"\n");
5767: numlinepar++;
5768: printf("\n");
5769: fprintf(ficparo,"\n");
5770: fprintf(ficlog,"\n");
5771: }
5772: }
5773: fflush(ficlog);
5774:
1.145 brouard 5775: /* Reads covariance matrix */
1.126 brouard 5776: delti=delti3[1][1];
5777:
5778:
5779: /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
5780:
5781: /* Reads comments: lines beginning with '#' */
5782: while((c=getc(ficpar))=='#' && c!= EOF){
5783: ungetc(c,ficpar);
5784: fgets(line, MAXLINE, ficpar);
5785: numlinepar++;
1.141 brouard 5786: fputs(line,stdout);
1.126 brouard 5787: fputs(line,ficparo);
5788: fputs(line,ficlog);
5789: }
5790: ungetc(c,ficpar);
5791:
5792: matcov=matrix(1,npar,1,npar);
1.131 brouard 5793: for(i=1; i <=npar; i++)
5794: for(j=1; j <=npar; j++) matcov[i][j]=0.;
5795:
1.126 brouard 5796: for(i=1; i <=npar; i++){
1.145 brouard 5797: fscanf(ficpar,"%s",str);
1.126 brouard 5798: if(mle==1)
5799: printf("%s",str);
5800: fprintf(ficlog,"%s",str);
5801: fprintf(ficparo,"%s",str);
5802: for(j=1; j <=i; j++){
5803: fscanf(ficpar," %le",&matcov[i][j]);
5804: if(mle==1){
5805: printf(" %.5le",matcov[i][j]);
5806: }
5807: fprintf(ficlog," %.5le",matcov[i][j]);
5808: fprintf(ficparo," %.5le",matcov[i][j]);
5809: }
5810: fscanf(ficpar,"\n");
5811: numlinepar++;
5812: if(mle==1)
5813: printf("\n");
5814: fprintf(ficlog,"\n");
5815: fprintf(ficparo,"\n");
5816: }
5817: for(i=1; i <=npar; i++)
5818: for(j=i+1;j<=npar;j++)
5819: matcov[i][j]=matcov[j][i];
5820:
5821: if(mle==1)
5822: printf("\n");
5823: fprintf(ficlog,"\n");
5824:
5825: fflush(ficlog);
5826:
5827: /*-------- Rewriting parameter file ----------*/
5828: strcpy(rfileres,"r"); /* "Rparameterfile */
5829: strcat(rfileres,optionfilefiname); /* Parameter file first name*/
5830: strcat(rfileres,"."); /* */
5831: strcat(rfileres,optionfilext); /* Other files have txt extension */
5832: if((ficres =fopen(rfileres,"w"))==NULL) {
5833: printf("Problem writing new parameter file: %s\n", fileres);goto end;
5834: fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
5835: }
5836: fprintf(ficres,"#%s\n",version);
5837: } /* End of mle != -3 */
5838:
5839:
5840: n= lastobs;
5841: num=lvector(1,n);
5842: moisnais=vector(1,n);
5843: annais=vector(1,n);
5844: moisdc=vector(1,n);
5845: andc=vector(1,n);
5846: agedc=vector(1,n);
5847: cod=ivector(1,n);
5848: weight=vector(1,n);
5849: for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
5850: mint=matrix(1,maxwav,1,n);
5851: anint=matrix(1,maxwav,1,n);
1.131 brouard 5852: s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */
1.126 brouard 5853: tab=ivector(1,NCOVMAX);
1.144 brouard 5854: ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.126 brouard 5855:
1.136 brouard 5856: /* Reads data from file datafile */
5857: if (readdata(datafile, firstobs, lastobs, &imx)==1)
5858: goto end;
5859:
5860: /* Calculation of the number of parameters from char model */
1.137 brouard 5861: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4
5862: k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
5863: k=3 V4 Tvar[k=3]= 4 (from V4)
5864: k=2 V1 Tvar[k=2]= 1 (from V1)
5865: k=1 Tvar[1]=2 (from V2)
5866: */
5867: Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
5868: /* V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs).
5869: For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4,
5870: Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
5871: */
5872: /* For model-covariate k tells which data-covariate to use but
5873: because this model-covariate is a construction we invent a new column
5874: ncovcol + k1
5875: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
5876: Tvar[3=V1*V4]=4+1 etc */
1.145 brouard 5877: Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137 brouard 5878: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
5879: if V2+V1+V1*V4+age*V3+V3*V2 TProd[k1=2]=5 (V3*V2)
5880: */
1.145 brouard 5881: Tvaraff=ivector(1,NCOVMAX); /* Unclear */
5882: 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 5883: * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd.
5884: * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145 brouard 5885: Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137 brouard 5886: 4 covariates (3 plus signs)
5887: Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
5888: */
1.136 brouard 5889:
5890: if(decodemodel(model, lastobs) == 1)
5891: goto end;
5892:
1.137 brouard 5893: if((double)(lastobs-imx)/(double)imx > 1.10){
5894: nbwarn++;
5895: 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);
5896: 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);
5897: }
1.136 brouard 5898: /* if(mle==1){*/
1.137 brouard 5899: if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
5900: for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136 brouard 5901: }
5902:
5903: /*-calculation of age at interview from date of interview and age at death -*/
5904: agev=matrix(1,maxwav,1,imx);
5905:
5906: if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
5907: goto end;
5908:
1.126 brouard 5909:
1.136 brouard 5910: agegomp=(int)agemin;
5911: free_vector(moisnais,1,n);
5912: free_vector(annais,1,n);
1.126 brouard 5913: /* free_matrix(mint,1,maxwav,1,n);
5914: free_matrix(anint,1,maxwav,1,n);*/
5915: free_vector(moisdc,1,n);
5916: free_vector(andc,1,n);
1.145 brouard 5917: /* */
5918:
1.126 brouard 5919: wav=ivector(1,imx);
5920: dh=imatrix(1,lastpass-firstpass+1,1,imx);
5921: bh=imatrix(1,lastpass-firstpass+1,1,imx);
5922: mw=imatrix(1,lastpass-firstpass+1,1,imx);
5923:
5924: /* Concatenates waves */
5925: concatwav(wav, dh, bh, mw, s, agedc, agev, firstpass, lastpass, imx, nlstate, stepm);
1.145 brouard 5926: /* */
5927:
1.126 brouard 5928: /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
5929:
5930: nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
5931: ncodemax[1]=1;
1.145 brouard 5932: Ndum =ivector(-1,NCOVMAX);
5933: if (ncovmodel > 2)
5934: tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
5935:
5936: codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
5937: /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
5938: h=0;
5939:
5940:
5941: /*if (cptcovn > 0) */
1.126 brouard 5942:
1.145 brouard 5943:
1.126 brouard 5944: m=pow(2,cptcoveff);
5945:
1.131 brouard 5946: for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
1.143 brouard 5947: 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 */
5948: for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
5949: 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 5950: h++;
1.141 brouard 5951: if (h>m)
1.136 brouard 5952: h=1;
1.144 brouard 5953: /**< codtab(h,k) k = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.143 brouard 5954: * h 1 2 3 4
5955: *______________________________
5956: * 1 i=1 1 i=1 1 i=1 1 i=1 1
5957: * 2 2 1 1 1
5958: * 3 i=2 1 2 1 1
5959: * 4 2 2 1 1
5960: * 5 i=3 1 i=2 1 2 1
5961: * 6 2 1 2 1
5962: * 7 i=4 1 2 2 1
5963: * 8 2 2 2 1
5964: * 9 i=5 1 i=3 1 i=2 1 1
5965: * 10 2 1 1 1
5966: * 11 i=6 1 2 1 1
5967: * 12 2 2 1 1
5968: * 13 i=7 1 i=4 1 2 1
5969: * 14 2 1 2 1
5970: * 15 i=8 1 2 2 1
5971: * 16 2 2 2 1
5972: */
1.141 brouard 5973: codtab[h][k]=j;
1.145 brouard 5974: /*codtab[h][Tvar[k]]=j;*/
1.130 brouard 5975: 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 5976: }
5977: }
5978: }
5979: }
5980: /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
5981: codtab[1][2]=1;codtab[2][2]=2; */
5982: /* for(i=1; i <=m ;i++){
5983: for(k=1; k <=cptcovn; k++){
1.131 brouard 5984: printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
1.126 brouard 5985: }
5986: printf("\n");
5987: }
5988: scanf("%d",i);*/
1.145 brouard 5989:
5990: free_ivector(Ndum,-1,NCOVMAX);
5991:
5992:
1.126 brouard 5993:
5994: /*------------ gnuplot -------------*/
5995: strcpy(optionfilegnuplot,optionfilefiname);
5996: if(mle==-3)
5997: strcat(optionfilegnuplot,"-mort");
5998: strcat(optionfilegnuplot,".gp");
5999:
6000: if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
6001: printf("Problem with file %s",optionfilegnuplot);
6002: }
6003: else{
6004: fprintf(ficgp,"\n# %s\n", version);
6005: fprintf(ficgp,"# %s\n", optionfilegnuplot);
1.141 brouard 6006: //fprintf(ficgp,"set missing 'NaNq'\n");
6007: fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126 brouard 6008: }
6009: /* fclose(ficgp);*/
6010: /*--------- index.htm --------*/
6011:
6012: strcpy(optionfilehtm,optionfilefiname); /* Main html file */
6013: if(mle==-3)
6014: strcat(optionfilehtm,"-mort");
6015: strcat(optionfilehtm,".htm");
6016: if((fichtm=fopen(optionfilehtm,"w"))==NULL) {
1.131 brouard 6017: printf("Problem with %s \n",optionfilehtm);
6018: exit(0);
1.126 brouard 6019: }
6020:
6021: strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
6022: strcat(optionfilehtmcov,"-cov.htm");
6023: if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL) {
6024: printf("Problem with %s \n",optionfilehtmcov), exit(0);
6025: }
6026: else{
6027: fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6028: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6029: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
6030: optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
6031: }
6032:
6033: fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6034: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6035: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
6036: \n\
6037: <hr size=\"2\" color=\"#EC5E5E\">\
6038: <ul><li><h4>Parameter files</h4>\n\
6039: - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
6040: - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
6041: - Log file of the run: <a href=\"%s\">%s</a><br>\n\
6042: - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
6043: - Date and time at start: %s</ul>\n",\
6044: optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
6045: optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
6046: fileres,fileres,\
6047: filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
6048: fflush(fichtm);
6049:
6050: strcpy(pathr,path);
6051: strcat(pathr,optionfilefiname);
6052: chdir(optionfilefiname); /* Move to directory named optionfile */
6053:
6054: /* Calculates basic frequencies. Computes observed prevalence at single age
6055: and prints on file fileres'p'. */
6056: freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
6057:
6058: fprintf(fichtm,"\n");
6059: fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
6060: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
6061: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
6062: imx,agemin,agemax,jmin,jmax,jmean);
6063: pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6064: oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6065: newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6066: savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6067: oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
6068:
6069:
6070: /* For Powell, parameters are in a vector p[] starting at p[1]
6071: so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
6072: p=param[1][1]; /* *(*(*(param +1)+1)+0) */
6073:
6074: globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
6075:
6076: if (mle==-3){
1.136 brouard 6077: ximort=matrix(1,NDIM,1,NDIM);
6078: /* ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126 brouard 6079: cens=ivector(1,n);
6080: ageexmed=vector(1,n);
6081: agecens=vector(1,n);
6082: dcwave=ivector(1,n);
6083:
6084: for (i=1; i<=imx; i++){
6085: dcwave[i]=-1;
6086: for (m=firstpass; m<=lastpass; m++)
6087: if (s[m][i]>nlstate) {
6088: dcwave[i]=m;
6089: /* printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
6090: break;
6091: }
6092: }
6093:
6094: for (i=1; i<=imx; i++) {
6095: if (wav[i]>0){
6096: ageexmed[i]=agev[mw[1][i]][i];
6097: j=wav[i];
6098: agecens[i]=1.;
6099:
6100: if (ageexmed[i]> 1 && wav[i] > 0){
6101: agecens[i]=agev[mw[j][i]][i];
6102: cens[i]= 1;
6103: }else if (ageexmed[i]< 1)
6104: cens[i]= -1;
6105: if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
6106: cens[i]=0 ;
6107: }
6108: else cens[i]=-1;
6109: }
6110:
6111: for (i=1;i<=NDIM;i++) {
6112: for (j=1;j<=NDIM;j++)
6113: ximort[i][j]=(i == j ? 1.0 : 0.0);
6114: }
6115:
1.145 brouard 6116: /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126 brouard 6117: /*printf("%lf %lf", p[1], p[2]);*/
6118:
6119:
1.136 brouard 6120: #ifdef GSL
6121: printf("GSL optimization\n"); fprintf(ficlog,"Powell\n");
1.162 brouard 6122: #else
1.126 brouard 6123: printf("Powell\n"); fprintf(ficlog,"Powell\n");
1.136 brouard 6124: #endif
1.126 brouard 6125: strcpy(filerespow,"pow-mort");
6126: strcat(filerespow,fileres);
6127: if((ficrespow=fopen(filerespow,"w"))==NULL) {
6128: printf("Problem with resultfile: %s\n", filerespow);
6129: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
6130: }
1.136 brouard 6131: #ifdef GSL
6132: fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162 brouard 6133: #else
1.126 brouard 6134: fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136 brouard 6135: #endif
1.126 brouard 6136: /* for (i=1;i<=nlstate;i++)
6137: for(j=1;j<=nlstate+ndeath;j++)
6138: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
6139: */
6140: fprintf(ficrespow,"\n");
1.136 brouard 6141: #ifdef GSL
6142: /* gsl starts here */
6143: T = gsl_multimin_fminimizer_nmsimplex;
6144: gsl_multimin_fminimizer *sfm = NULL;
6145: gsl_vector *ss, *x;
6146: gsl_multimin_function minex_func;
6147:
6148: /* Initial vertex size vector */
6149: ss = gsl_vector_alloc (NDIM);
6150:
6151: if (ss == NULL){
6152: GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
6153: }
6154: /* Set all step sizes to 1 */
6155: gsl_vector_set_all (ss, 0.001);
6156:
6157: /* Starting point */
1.126 brouard 6158:
1.136 brouard 6159: x = gsl_vector_alloc (NDIM);
6160:
6161: if (x == NULL){
6162: gsl_vector_free(ss);
6163: GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
6164: }
6165:
6166: /* Initialize method and iterate */
6167: /* p[1]=0.0268; p[NDIM]=0.083; */
6168: /* gsl_vector_set(x, 0, 0.0268); */
6169: /* gsl_vector_set(x, 1, 0.083); */
6170: gsl_vector_set(x, 0, p[1]);
6171: gsl_vector_set(x, 1, p[2]);
6172:
6173: minex_func.f = &gompertz_f;
6174: minex_func.n = NDIM;
6175: minex_func.params = (void *)&p; /* ??? */
6176:
6177: sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
6178: gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
6179:
6180: printf("Iterations beginning .....\n\n");
6181: printf("Iter. # Intercept Slope -Log Likelihood Simplex size\n");
6182:
6183: iteri=0;
6184: while (rval == GSL_CONTINUE){
6185: iteri++;
6186: status = gsl_multimin_fminimizer_iterate(sfm);
6187:
6188: if (status) printf("error: %s\n", gsl_strerror (status));
6189: fflush(0);
6190:
6191: if (status)
6192: break;
6193:
6194: rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
6195: ssval = gsl_multimin_fminimizer_size (sfm);
6196:
6197: if (rval == GSL_SUCCESS)
6198: printf ("converged to a local maximum at\n");
6199:
6200: printf("%5d ", iteri);
6201: for (it = 0; it < NDIM; it++){
6202: printf ("%10.5f ", gsl_vector_get (sfm->x, it));
6203: }
6204: printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
6205: }
6206:
6207: printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
6208:
6209: gsl_vector_free(x); /* initial values */
6210: gsl_vector_free(ss); /* inital step size */
6211: for (it=0; it<NDIM; it++){
6212: p[it+1]=gsl_vector_get(sfm->x,it);
6213: fprintf(ficrespow," %.12lf", p[it]);
6214: }
6215: gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1) */
6216: #endif
6217: #ifdef POWELL
6218: powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
6219: #endif
1.126 brouard 6220: fclose(ficrespow);
6221:
6222: hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);
6223:
6224: for(i=1; i <=NDIM; i++)
6225: for(j=i+1;j<=NDIM;j++)
6226: matcov[i][j]=matcov[j][i];
6227:
6228: printf("\nCovariance matrix\n ");
6229: for(i=1; i <=NDIM; i++) {
6230: for(j=1;j<=NDIM;j++){
6231: printf("%f ",matcov[i][j]);
6232: }
6233: printf("\n ");
6234: }
6235:
6236: printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
6237: for (i=1;i<=NDIM;i++)
6238: printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
6239:
6240: lsurv=vector(1,AGESUP);
6241: lpop=vector(1,AGESUP);
6242: tpop=vector(1,AGESUP);
6243: lsurv[agegomp]=100000;
6244:
6245: for (k=agegomp;k<=AGESUP;k++) {
6246: agemortsup=k;
6247: if (p[1]*exp(p[2]*(k-agegomp))>1) break;
6248: }
6249:
6250: for (k=agegomp;k<agemortsup;k++)
6251: lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
6252:
6253: for (k=agegomp;k<agemortsup;k++){
6254: lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
6255: sumlpop=sumlpop+lpop[k];
6256: }
6257:
6258: tpop[agegomp]=sumlpop;
6259: for (k=agegomp;k<(agemortsup-3);k++){
6260: /* tpop[k+1]=2;*/
6261: tpop[k+1]=tpop[k]-lpop[k];
6262: }
6263:
6264:
6265: printf("\nAge lx qx dx Lx Tx e(x)\n");
6266: for (k=agegomp;k<(agemortsup-2);k++)
6267: 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]);
6268:
6269:
6270: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6271: printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6272:
6273: printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
6274: stepm, weightopt,\
6275: model,imx,p,matcov,agemortsup);
6276:
6277: free_vector(lsurv,1,AGESUP);
6278: free_vector(lpop,1,AGESUP);
6279: free_vector(tpop,1,AGESUP);
1.136 brouard 6280: #ifdef GSL
6281: free_ivector(cens,1,n);
6282: free_vector(agecens,1,n);
6283: free_ivector(dcwave,1,n);
6284: free_matrix(ximort,1,NDIM,1,NDIM);
6285: #endif
1.126 brouard 6286: } /* Endof if mle==-3 */
6287:
6288: else{ /* For mle >=1 */
1.132 brouard 6289: globpr=0;/* debug */
6290: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126 brouard 6291: printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6292: for (k=1; k<=npar;k++)
6293: printf(" %d %8.5f",k,p[k]);
6294: printf("\n");
6295: globpr=1; /* to print the contributions */
6296: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
6297: printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6298: for (k=1; k<=npar;k++)
6299: printf(" %d %8.5f",k,p[k]);
6300: printf("\n");
6301: if(mle>=1){ /* Could be 1 or 2 */
6302: mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
6303: }
6304:
6305: /*--------- results files --------------*/
6306: 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);
6307:
6308:
6309: fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6310: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6311: fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6312: for(i=1,jk=1; i <=nlstate; i++){
6313: for(k=1; k <=(nlstate+ndeath); k++){
6314: if (k != i) {
6315: printf("%d%d ",i,k);
6316: fprintf(ficlog,"%d%d ",i,k);
6317: fprintf(ficres,"%1d%1d ",i,k);
6318: for(j=1; j <=ncovmodel; j++){
6319: printf("%lf ",p[jk]);
6320: fprintf(ficlog,"%lf ",p[jk]);
6321: fprintf(ficres,"%lf ",p[jk]);
6322: jk++;
6323: }
6324: printf("\n");
6325: fprintf(ficlog,"\n");
6326: fprintf(ficres,"\n");
6327: }
6328: }
6329: }
6330: if(mle!=0){
6331: /* Computing hessian and covariance matrix */
6332: ftolhess=ftol; /* Usually correct */
6333: hesscov(matcov, p, npar, delti, ftolhess, func);
6334: }
6335: fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
6336: printf("# Scales (for hessian or gradient estimation)\n");
6337: fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
6338: for(i=1,jk=1; i <=nlstate; i++){
6339: for(j=1; j <=nlstate+ndeath; j++){
6340: if (j!=i) {
6341: fprintf(ficres,"%1d%1d",i,j);
6342: printf("%1d%1d",i,j);
6343: fprintf(ficlog,"%1d%1d",i,j);
6344: for(k=1; k<=ncovmodel;k++){
6345: printf(" %.5e",delti[jk]);
6346: fprintf(ficlog," %.5e",delti[jk]);
6347: fprintf(ficres," %.5e",delti[jk]);
6348: jk++;
6349: }
6350: printf("\n");
6351: fprintf(ficlog,"\n");
6352: fprintf(ficres,"\n");
6353: }
6354: }
6355: }
6356:
6357: 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");
6358: if(mle>=1)
6359: 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");
6360: 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");
6361: /* # 121 Var(a12)\n\ */
6362: /* # 122 Cov(b12,a12) Var(b12)\n\ */
6363: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
6364: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
6365: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
6366: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
6367: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
6368: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
6369:
6370:
6371: /* Just to have a covariance matrix which will be more understandable
6372: even is we still don't want to manage dictionary of variables
6373: */
6374: for(itimes=1;itimes<=2;itimes++){
6375: jj=0;
6376: for(i=1; i <=nlstate; i++){
6377: for(j=1; j <=nlstate+ndeath; j++){
6378: if(j==i) continue;
6379: for(k=1; k<=ncovmodel;k++){
6380: jj++;
6381: ca[0]= k+'a'-1;ca[1]='\0';
6382: if(itimes==1){
6383: if(mle>=1)
6384: printf("#%1d%1d%d",i,j,k);
6385: fprintf(ficlog,"#%1d%1d%d",i,j,k);
6386: fprintf(ficres,"#%1d%1d%d",i,j,k);
6387: }else{
6388: if(mle>=1)
6389: printf("%1d%1d%d",i,j,k);
6390: fprintf(ficlog,"%1d%1d%d",i,j,k);
6391: fprintf(ficres,"%1d%1d%d",i,j,k);
6392: }
6393: ll=0;
6394: for(li=1;li <=nlstate; li++){
6395: for(lj=1;lj <=nlstate+ndeath; lj++){
6396: if(lj==li) continue;
6397: for(lk=1;lk<=ncovmodel;lk++){
6398: ll++;
6399: if(ll<=jj){
6400: cb[0]= lk +'a'-1;cb[1]='\0';
6401: if(ll<jj){
6402: if(itimes==1){
6403: if(mle>=1)
6404: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6405: fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6406: fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6407: }else{
6408: if(mle>=1)
6409: printf(" %.5e",matcov[jj][ll]);
6410: fprintf(ficlog," %.5e",matcov[jj][ll]);
6411: fprintf(ficres," %.5e",matcov[jj][ll]);
6412: }
6413: }else{
6414: if(itimes==1){
6415: if(mle>=1)
6416: printf(" Var(%s%1d%1d)",ca,i,j);
6417: fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
6418: fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
6419: }else{
6420: if(mle>=1)
6421: printf(" %.5e",matcov[jj][ll]);
6422: fprintf(ficlog," %.5e",matcov[jj][ll]);
6423: fprintf(ficres," %.5e",matcov[jj][ll]);
6424: }
6425: }
6426: }
6427: } /* end lk */
6428: } /* end lj */
6429: } /* end li */
6430: if(mle>=1)
6431: printf("\n");
6432: fprintf(ficlog,"\n");
6433: fprintf(ficres,"\n");
6434: numlinepar++;
6435: } /* end k*/
6436: } /*end j */
6437: } /* end i */
6438: } /* end itimes */
6439:
6440: fflush(ficlog);
6441: fflush(ficres);
6442:
6443: while((c=getc(ficpar))=='#' && c!= EOF){
6444: ungetc(c,ficpar);
6445: fgets(line, MAXLINE, ficpar);
1.141 brouard 6446: fputs(line,stdout);
1.126 brouard 6447: fputs(line,ficparo);
6448: }
6449: ungetc(c,ficpar);
6450:
6451: estepm=0;
6452: fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
6453: if (estepm==0 || estepm < stepm) estepm=stepm;
6454: if (fage <= 2) {
6455: bage = ageminpar;
6456: fage = agemaxpar;
6457: }
6458:
6459: fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
6460: fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6461: fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6462:
6463: while((c=getc(ficpar))=='#' && c!= EOF){
6464: ungetc(c,ficpar);
6465: fgets(line, MAXLINE, ficpar);
1.141 brouard 6466: fputs(line,stdout);
1.126 brouard 6467: fputs(line,ficparo);
6468: }
6469: ungetc(c,ficpar);
6470:
6471: 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);
6472: 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);
6473: 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);
6474: printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
6475: 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);
6476:
6477: while((c=getc(ficpar))=='#' && c!= EOF){
6478: ungetc(c,ficpar);
6479: fgets(line, MAXLINE, ficpar);
1.141 brouard 6480: fputs(line,stdout);
1.126 brouard 6481: fputs(line,ficparo);
6482: }
6483: ungetc(c,ficpar);
6484:
6485:
6486: dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
6487: dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
6488:
6489: fscanf(ficpar,"pop_based=%d\n",&popbased);
6490: fprintf(ficparo,"pop_based=%d\n",popbased);
6491: fprintf(ficres,"pop_based=%d\n",popbased);
6492:
6493: while((c=getc(ficpar))=='#' && c!= EOF){
6494: ungetc(c,ficpar);
6495: fgets(line, MAXLINE, ficpar);
1.141 brouard 6496: fputs(line,stdout);
1.126 brouard 6497: fputs(line,ficparo);
6498: }
6499: ungetc(c,ficpar);
6500:
6501: 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);
6502: 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);
6503: 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);
6504: 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);
6505: 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);
6506: /* day and month of proj2 are not used but only year anproj2.*/
6507:
6508:
6509:
1.145 brouard 6510: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
6511: /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126 brouard 6512:
6513: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6514: printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6515:
6516: printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
6517: model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
6518: jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
6519:
6520: /*------------ free_vector -------------*/
6521: /* chdir(path); */
6522:
6523: free_ivector(wav,1,imx);
6524: free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
6525: free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
6526: free_imatrix(mw,1,lastpass-firstpass+1,1,imx);
6527: free_lvector(num,1,n);
6528: free_vector(agedc,1,n);
6529: /*free_matrix(covar,0,NCOVMAX,1,n);*/
6530: /*free_matrix(covar,1,NCOVMAX,1,n);*/
6531: fclose(ficparo);
6532: fclose(ficres);
6533:
6534:
6535: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
1.145 brouard 6536: #include "prevlim.h" /* Use ficrespl, ficlog */
1.126 brouard 6537: fclose(ficrespl);
6538:
1.145 brouard 6539: #ifdef FREEEXIT2
6540: #include "freeexit2.h"
6541: #endif
6542:
1.126 brouard 6543: /*------------- h Pij x at various ages ------------*/
1.145 brouard 6544: #include "hpijx.h"
6545: fclose(ficrespij);
1.126 brouard 6546:
1.145 brouard 6547: /*-------------- Variance of one-step probabilities---*/
6548: k=1;
1.126 brouard 6549: varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
6550:
6551:
6552: probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
6553: for(i=1;i<=AGESUP;i++)
6554: for(j=1;j<=NCOVMAX;j++)
6555: for(k=1;k<=NCOVMAX;k++)
6556: probs[i][j][k]=0.;
6557:
6558: /*---------- Forecasting ------------------*/
6559: /*if((stepm == 1) && (strcmp(model,".")==0)){*/
6560: if(prevfcast==1){
6561: /* if(stepm ==1){*/
6562: prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
6563: /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
6564: /* } */
6565: /* else{ */
6566: /* erreur=108; */
6567: /* 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); */
6568: /* 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); */
6569: /* } */
6570: }
6571:
6572:
1.127 brouard 6573: /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
6574:
6575: prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
6576: /* 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",\
6577: ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
6578: */
1.126 brouard 6579:
1.127 brouard 6580: if (mobilav!=0) {
6581: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
6582: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
6583: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
6584: printf(" Error in movingaverage mobilav=%d\n",mobilav);
6585: }
1.126 brouard 6586: }
6587:
6588:
1.127 brouard 6589: /*---------- Health expectancies, no variances ------------*/
6590:
1.126 brouard 6591: strcpy(filerese,"e");
6592: strcat(filerese,fileres);
6593: if((ficreseij=fopen(filerese,"w"))==NULL) {
6594: printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
6595: fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
6596: }
6597: printf("Computing Health Expectancies: result on file '%s' \n", filerese);
6598: fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
1.145 brouard 6599: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6600: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6601:
6602: for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127 brouard 6603: fprintf(ficreseij,"\n#****** ");
6604: for(j=1;j<=cptcoveff;j++) {
6605: fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6606: }
6607: fprintf(ficreseij,"******\n");
6608:
6609: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6610: oldm=oldms;savm=savms;
6611: evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);
6612:
6613: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145 brouard 6614: /*}*/
1.127 brouard 6615: }
6616: fclose(ficreseij);
6617:
6618:
6619: /*---------- Health expectancies and variances ------------*/
6620:
6621:
6622: strcpy(filerest,"t");
6623: strcat(filerest,fileres);
6624: if((ficrest=fopen(filerest,"w"))==NULL) {
6625: printf("Problem with total LE resultfile: %s\n", filerest);goto end;
6626: fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
6627: }
6628: printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
6629: fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
6630:
1.126 brouard 6631:
6632: strcpy(fileresstde,"stde");
6633: strcat(fileresstde,fileres);
6634: if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
6635: printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
6636: fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
6637: }
6638: printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
6639: fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
6640:
6641: strcpy(filerescve,"cve");
6642: strcat(filerescve,fileres);
6643: if((ficrescveij=fopen(filerescve,"w"))==NULL) {
6644: printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
6645: fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
6646: }
6647: printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
6648: fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
6649:
6650: strcpy(fileresv,"v");
6651: strcat(fileresv,fileres);
6652: if((ficresvij=fopen(fileresv,"w"))==NULL) {
6653: printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
6654: fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
6655: }
6656: printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
6657: fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
6658:
1.145 brouard 6659: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6660: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6661:
6662: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6663: fprintf(ficrest,"\n#****** ");
1.126 brouard 6664: for(j=1;j<=cptcoveff;j++)
6665: fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6666: fprintf(ficrest,"******\n");
6667:
6668: fprintf(ficresstdeij,"\n#****** ");
6669: fprintf(ficrescveij,"\n#****** ");
6670: for(j=1;j<=cptcoveff;j++) {
6671: fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6672: fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6673: }
6674: fprintf(ficresstdeij,"******\n");
6675: fprintf(ficrescveij,"******\n");
6676:
6677: fprintf(ficresvij,"\n#****** ");
6678: for(j=1;j<=cptcoveff;j++)
6679: fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6680: fprintf(ficresvij,"******\n");
6681:
6682: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6683: oldm=oldms;savm=savms;
1.127 brouard 6684: cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
1.145 brouard 6685: /*
6686: */
6687: /* goto endfree; */
1.126 brouard 6688:
6689: vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6690: pstamp(ficrest);
1.145 brouard 6691:
6692:
1.128 brouard 6693: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.145 brouard 6694: oldm=oldms;savm=savms; /* Segmentation fault */
1.161 brouard 6695: cptcod= 0; /* To be deleted */
6696: 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 6697: 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 6698: if(vpopbased==1)
6699: 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);
6700: else
6701: fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
6702: fprintf(ficrest,"# Age e.. (std) ");
6703: for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
6704: fprintf(ficrest,"\n");
1.126 brouard 6705:
1.128 brouard 6706: epj=vector(1,nlstate+1);
6707: for(age=bage; age <=fage ;age++){
6708: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
6709: if (vpopbased==1) {
6710: if(mobilav ==0){
6711: for(i=1; i<=nlstate;i++)
6712: prlim[i][i]=probs[(int)age][i][k];
6713: }else{ /* mobilav */
6714: for(i=1; i<=nlstate;i++)
6715: prlim[i][i]=mobaverage[(int)age][i][k];
6716: }
1.126 brouard 6717: }
6718:
1.128 brouard 6719: fprintf(ficrest," %4.0f",age);
6720: for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
6721: for(i=1, epj[j]=0.;i <=nlstate;i++) {
6722: epj[j] += prlim[i][i]*eij[i][j][(int)age];
6723: /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
6724: }
6725: epj[nlstate+1] +=epj[j];
1.126 brouard 6726: }
6727:
1.128 brouard 6728: for(i=1, vepp=0.;i <=nlstate;i++)
6729: for(j=1;j <=nlstate;j++)
6730: vepp += vareij[i][j][(int)age];
6731: fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
6732: for(j=1;j <=nlstate;j++){
6733: fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
6734: }
6735: fprintf(ficrest,"\n");
1.126 brouard 6736: }
6737: }
6738: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
6739: free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
6740: free_vector(epj,1,nlstate+1);
1.145 brouard 6741: /*}*/
1.126 brouard 6742: }
6743: free_vector(weight,1,n);
1.145 brouard 6744: free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126 brouard 6745: free_imatrix(s,1,maxwav+1,1,n);
6746: free_matrix(anint,1,maxwav,1,n);
6747: free_matrix(mint,1,maxwav,1,n);
6748: free_ivector(cod,1,n);
6749: free_ivector(tab,1,NCOVMAX);
6750: fclose(ficresstdeij);
6751: fclose(ficrescveij);
6752: fclose(ficresvij);
6753: fclose(ficrest);
6754: fclose(ficpar);
6755:
6756: /*------- Variance of period (stable) prevalence------*/
6757:
6758: strcpy(fileresvpl,"vpl");
6759: strcat(fileresvpl,fileres);
6760: if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
6761: printf("Problem with variance of period (stable) prevalence resultfile: %s\n", fileresvpl);
6762: exit(0);
6763: }
6764: printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
6765:
1.145 brouard 6766: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6767: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6768:
6769: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6770: fprintf(ficresvpl,"\n#****** ");
1.126 brouard 6771: for(j=1;j<=cptcoveff;j++)
6772: fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6773: fprintf(ficresvpl,"******\n");
6774:
6775: varpl=matrix(1,nlstate,(int) bage, (int) fage);
6776: oldm=oldms;savm=savms;
6777: varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
6778: free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145 brouard 6779: /*}*/
1.126 brouard 6780: }
6781:
6782: fclose(ficresvpl);
6783:
6784: /*---------- End : free ----------------*/
6785: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
6786: free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
6787: } /* mle==-3 arrives here for freeing */
1.164 brouard 6788: /* endfree:*/
1.141 brouard 6789: free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126 brouard 6790: free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
6791: free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
6792: free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
6793: free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
6794: free_matrix(covar,0,NCOVMAX,1,n);
6795: free_matrix(matcov,1,npar,1,npar);
6796: /*free_vector(delti,1,npar);*/
6797: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
6798: free_matrix(agev,1,maxwav,1,imx);
6799: free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
6800:
1.145 brouard 6801: free_ivector(ncodemax,1,NCOVMAX);
6802: free_ivector(Tvar,1,NCOVMAX);
6803: free_ivector(Tprod,1,NCOVMAX);
6804: free_ivector(Tvaraff,1,NCOVMAX);
6805: free_ivector(Tage,1,NCOVMAX);
1.126 brouard 6806:
6807: free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
6808: free_imatrix(codtab,1,100,1,10);
6809: fflush(fichtm);
6810: fflush(ficgp);
6811:
6812:
6813: if((nberr >0) || (nbwarn>0)){
6814: printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
6815: fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
6816: }else{
6817: printf("End of Imach\n");
6818: fprintf(ficlog,"End of Imach\n");
6819: }
6820: printf("See log file on %s\n",filelog);
6821: /* gettimeofday(&end_time, (struct timezone*)0);*/ /* after time */
1.157 brouard 6822: /*(void) gettimeofday(&end_time,&tzp);*/
6823: rend_time = time(NULL);
6824: end_time = *localtime(&rend_time);
6825: /* tml = *localtime(&end_time.tm_sec); */
6826: strcpy(strtend,asctime(&end_time));
1.126 brouard 6827: printf("Local time at start %s\nLocal time at end %s",strstart, strtend);
6828: fprintf(ficlog,"Local time at start %s\nLocal time at end %s\n",strstart, strtend);
1.157 brouard 6829: printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126 brouard 6830:
1.157 brouard 6831: printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
6832: fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
6833: fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126 brouard 6834: /* printf("Total time was %d uSec.\n", total_usecs);*/
6835: /* if(fileappend(fichtm,optionfilehtm)){ */
6836: fprintf(fichtm,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
6837: fclose(fichtm);
6838: fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
6839: fclose(fichtmcov);
6840: fclose(ficgp);
6841: fclose(ficlog);
6842: /*------ End -----------*/
6843:
6844:
6845: printf("Before Current directory %s!\n",pathcd);
6846: if(chdir(pathcd) != 0)
6847: printf("Can't move to directory %s!\n",path);
6848: if(getcwd(pathcd,MAXLINE) > 0)
6849: printf("Current directory %s!\n",pathcd);
6850: /*strcat(plotcmd,CHARSEPARATOR);*/
6851: sprintf(plotcmd,"gnuplot");
1.157 brouard 6852: #ifdef _WIN32
1.126 brouard 6853: sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
6854: #endif
6855: if(!stat(plotcmd,&info)){
1.158 brouard 6856: printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 6857: if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158 brouard 6858: printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126 brouard 6859: }else
6860: strcpy(pplotcmd,plotcmd);
1.157 brouard 6861: #ifdef __unix
1.126 brouard 6862: strcpy(plotcmd,GNUPLOTPROGRAM);
6863: if(!stat(plotcmd,&info)){
1.158 brouard 6864: printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 6865: }else
6866: strcpy(pplotcmd,plotcmd);
6867: #endif
6868: }else
6869: strcpy(pplotcmd,plotcmd);
6870:
6871: sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158 brouard 6872: printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 6873:
6874: if((outcmd=system(plotcmd)) != 0){
1.158 brouard 6875: printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154 brouard 6876: printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152 brouard 6877: sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150 brouard 6878: if((outcmd=system(plotcmd)) != 0)
1.153 brouard 6879: printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126 brouard 6880: }
1.158 brouard 6881: printf(" Successful, please wait...");
1.126 brouard 6882: while (z[0] != 'q') {
6883: /* chdir(path); */
1.154 brouard 6884: printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126 brouard 6885: scanf("%s",z);
6886: /* if (z[0] == 'c') system("./imach"); */
6887: if (z[0] == 'e') {
1.158 brouard 6888: #ifdef __APPLE__
1.152 brouard 6889: sprintf(pplotcmd, "open %s", optionfilehtm);
1.157 brouard 6890: #elif __linux
6891: sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153 brouard 6892: #else
1.152 brouard 6893: sprintf(pplotcmd, "%s", optionfilehtm);
1.153 brouard 6894: #endif
6895: printf("Starting browser with: %s",pplotcmd);fflush(stdout);
6896: system(pplotcmd);
1.126 brouard 6897: }
6898: else if (z[0] == 'g') system(plotcmd);
6899: else if (z[0] == 'q') exit(0);
6900: }
6901: end:
6902: while (z[0] != 'q') {
6903: printf("\nType q for exiting: ");
6904: scanf("%s",z);
6905: }
6906: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>