Annotation of imach/src/imach.c, revision 1.162
1.162 ! brouard 1: /* $Id: imach-nlopt.c,v 1.1 2014/09/16 11:06:58 brouard Exp $
1.126 brouard 2: $State: Exp $
1.162 ! brouard 3: $Log: imach-nlopt.c,v $
! 4: Revision 1.1 2014/09/16 11:06:58 brouard
! 5: Summary: With some code (wrong) for nlopt
! 6:
! 7: Author:
! 8:
! 9: Revision 1.161 2014/09/15 20:41:41 brouard
! 10: Summary: Problem with macro SQR on Intel compiler
! 11:
1.161 brouard 12: Revision 1.160 2014/09/02 09:24:05 brouard
13: *** empty log message ***
14:
1.160 brouard 15: Revision 1.159 2014/09/01 10:34:10 brouard
16: Summary: WIN32
17: Author: Brouard
18:
1.159 brouard 19: Revision 1.158 2014/08/27 17:11:51 brouard
20: *** empty log message ***
21:
1.158 brouard 22: Revision 1.157 2014/08/27 16:26:55 brouard
23: Summary: Preparing windows Visual studio version
24: Author: Brouard
25:
26: In order to compile on Visual studio, time.h is now correct and time_t
27: and tm struct should be used. difftime should be used but sometimes I
28: just make the differences in raw time format (time(&now).
29: Trying to suppress #ifdef LINUX
30: Add xdg-open for __linux in order to open default browser.
31:
1.157 brouard 32: Revision 1.156 2014/08/25 20:10:10 brouard
33: *** empty log message ***
34:
1.156 brouard 35: Revision 1.155 2014/08/25 18:32:34 brouard
36: Summary: New compile, minor changes
37: Author: Brouard
38:
1.155 brouard 39: Revision 1.154 2014/06/20 17:32:08 brouard
40: Summary: Outputs now all graphs of convergence to period prevalence
41:
1.154 brouard 42: Revision 1.153 2014/06/20 16:45:46 brouard
43: Summary: If 3 live state, convergence to period prevalence on same graph
44: Author: Brouard
45:
1.153 brouard 46: Revision 1.152 2014/06/18 17:54:09 brouard
47: Summary: open browser, use gnuplot on same dir than imach if not found in the path
48:
1.152 brouard 49: Revision 1.151 2014/06/18 16:43:30 brouard
50: *** empty log message ***
51:
1.151 brouard 52: Revision 1.150 2014/06/18 16:42:35 brouard
53: Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
54: Author: brouard
55:
1.150 brouard 56: Revision 1.149 2014/06/18 15:51:14 brouard
57: Summary: Some fixes in parameter files errors
58: Author: Nicolas Brouard
59:
1.149 brouard 60: Revision 1.148 2014/06/17 17:38:48 brouard
61: Summary: Nothing new
62: Author: Brouard
63:
64: Just a new packaging for OS/X version 0.98nS
65:
1.148 brouard 66: Revision 1.147 2014/06/16 10:33:11 brouard
67: *** empty log message ***
68:
1.147 brouard 69: Revision 1.146 2014/06/16 10:20:28 brouard
70: Summary: Merge
71: Author: Brouard
72:
73: Merge, before building revised version.
74:
1.146 brouard 75: Revision 1.145 2014/06/10 21:23:15 brouard
76: Summary: Debugging with valgrind
77: Author: Nicolas Brouard
78:
79: Lot of changes in order to output the results with some covariates
80: After the Edimburgh REVES conference 2014, it seems mandatory to
81: improve the code.
82: No more memory valgrind error but a lot has to be done in order to
83: continue the work of splitting the code into subroutines.
84: Also, decodemodel has been improved. Tricode is still not
85: optimal. nbcode should be improved. Documentation has been added in
86: the source code.
87:
1.144 brouard 88: Revision 1.143 2014/01/26 09:45:38 brouard
89: Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
90:
91: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
92: (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
93:
1.143 brouard 94: Revision 1.142 2014/01/26 03:57:36 brouard
95: Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
96:
97: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
98:
1.142 brouard 99: Revision 1.141 2014/01/26 02:42:01 brouard
100: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
101:
1.141 brouard 102: Revision 1.140 2011/09/02 10:37:54 brouard
103: Summary: times.h is ok with mingw32 now.
104:
1.140 brouard 105: Revision 1.139 2010/06/14 07:50:17 brouard
106: After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
107: I remember having already fixed agemin agemax which are pointers now but not cvs saved.
108:
1.139 brouard 109: Revision 1.138 2010/04/30 18:19:40 brouard
110: *** empty log message ***
111:
1.138 brouard 112: Revision 1.137 2010/04/29 18:11:38 brouard
113: (Module): Checking covariates for more complex models
114: than V1+V2. A lot of change to be done. Unstable.
115:
1.137 brouard 116: Revision 1.136 2010/04/26 20:30:53 brouard
117: (Module): merging some libgsl code. Fixing computation
118: of likelione (using inter/intrapolation if mle = 0) in order to
119: get same likelihood as if mle=1.
120: Some cleaning of code and comments added.
121:
1.136 brouard 122: Revision 1.135 2009/10/29 15:33:14 brouard
123: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
124:
1.135 brouard 125: Revision 1.134 2009/10/29 13:18:53 brouard
126: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
127:
1.134 brouard 128: Revision 1.133 2009/07/06 10:21:25 brouard
129: just nforces
130:
1.133 brouard 131: Revision 1.132 2009/07/06 08:22:05 brouard
132: Many tings
133:
1.132 brouard 134: Revision 1.131 2009/06/20 16:22:47 brouard
135: Some dimensions resccaled
136:
1.131 brouard 137: Revision 1.130 2009/05/26 06:44:34 brouard
138: (Module): Max Covariate is now set to 20 instead of 8. A
139: lot of cleaning with variables initialized to 0. Trying to make
140: V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
141:
1.130 brouard 142: Revision 1.129 2007/08/31 13:49:27 lievre
143: Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
144:
1.129 lievre 145: Revision 1.128 2006/06/30 13:02:05 brouard
146: (Module): Clarifications on computing e.j
147:
1.128 brouard 148: Revision 1.127 2006/04/28 18:11:50 brouard
149: (Module): Yes the sum of survivors was wrong since
150: imach-114 because nhstepm was no more computed in the age
151: loop. Now we define nhstepma in the age loop.
152: (Module): In order to speed up (in case of numerous covariates) we
153: compute health expectancies (without variances) in a first step
154: and then all the health expectancies with variances or standard
155: deviation (needs data from the Hessian matrices) which slows the
156: computation.
157: In the future we should be able to stop the program is only health
158: expectancies and graph are needed without standard deviations.
159:
1.127 brouard 160: Revision 1.126 2006/04/28 17:23:28 brouard
161: (Module): Yes the sum of survivors was wrong since
162: imach-114 because nhstepm was no more computed in the age
163: loop. Now we define nhstepma in the age loop.
164: Version 0.98h
165:
1.126 brouard 166: Revision 1.125 2006/04/04 15:20:31 lievre
167: Errors in calculation of health expectancies. Age was not initialized.
168: Forecasting file added.
169:
170: Revision 1.124 2006/03/22 17:13:53 lievre
171: Parameters are printed with %lf instead of %f (more numbers after the comma).
172: The log-likelihood is printed in the log file
173:
174: Revision 1.123 2006/03/20 10:52:43 brouard
175: * imach.c (Module): <title> changed, corresponds to .htm file
176: name. <head> headers where missing.
177:
178: * imach.c (Module): Weights can have a decimal point as for
179: English (a comma might work with a correct LC_NUMERIC environment,
180: otherwise the weight is truncated).
181: Modification of warning when the covariates values are not 0 or
182: 1.
183: Version 0.98g
184:
185: Revision 1.122 2006/03/20 09:45:41 brouard
186: (Module): Weights can have a decimal point as for
187: English (a comma might work with a correct LC_NUMERIC environment,
188: otherwise the weight is truncated).
189: Modification of warning when the covariates values are not 0 or
190: 1.
191: Version 0.98g
192:
193: Revision 1.121 2006/03/16 17:45:01 lievre
194: * imach.c (Module): Comments concerning covariates added
195:
196: * imach.c (Module): refinements in the computation of lli if
197: status=-2 in order to have more reliable computation if stepm is
198: not 1 month. Version 0.98f
199:
200: Revision 1.120 2006/03/16 15:10:38 lievre
201: (Module): refinements in the computation of lli if
202: status=-2 in order to have more reliable computation if stepm is
203: not 1 month. Version 0.98f
204:
205: Revision 1.119 2006/03/15 17:42:26 brouard
206: (Module): Bug if status = -2, the loglikelihood was
207: computed as likelihood omitting the logarithm. Version O.98e
208:
209: Revision 1.118 2006/03/14 18:20:07 brouard
210: (Module): varevsij Comments added explaining the second
211: table of variances if popbased=1 .
212: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
213: (Module): Function pstamp added
214: (Module): Version 0.98d
215:
216: Revision 1.117 2006/03/14 17:16:22 brouard
217: (Module): varevsij Comments added explaining the second
218: table of variances if popbased=1 .
219: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
220: (Module): Function pstamp added
221: (Module): Version 0.98d
222:
223: Revision 1.116 2006/03/06 10:29:27 brouard
224: (Module): Variance-covariance wrong links and
225: varian-covariance of ej. is needed (Saito).
226:
227: Revision 1.115 2006/02/27 12:17:45 brouard
228: (Module): One freematrix added in mlikeli! 0.98c
229:
230: Revision 1.114 2006/02/26 12:57:58 brouard
231: (Module): Some improvements in processing parameter
232: filename with strsep.
233:
234: Revision 1.113 2006/02/24 14:20:24 brouard
235: (Module): Memory leaks checks with valgrind and:
236: datafile was not closed, some imatrix were not freed and on matrix
237: allocation too.
238:
239: Revision 1.112 2006/01/30 09:55:26 brouard
240: (Module): Back to gnuplot.exe instead of wgnuplot.exe
241:
242: Revision 1.111 2006/01/25 20:38:18 brouard
243: (Module): Lots of cleaning and bugs added (Gompertz)
244: (Module): Comments can be added in data file. Missing date values
245: can be a simple dot '.'.
246:
247: Revision 1.110 2006/01/25 00:51:50 brouard
248: (Module): Lots of cleaning and bugs added (Gompertz)
249:
250: Revision 1.109 2006/01/24 19:37:15 brouard
251: (Module): Comments (lines starting with a #) are allowed in data.
252:
253: Revision 1.108 2006/01/19 18:05:42 lievre
254: Gnuplot problem appeared...
255: To be fixed
256:
257: Revision 1.107 2006/01/19 16:20:37 brouard
258: Test existence of gnuplot in imach path
259:
260: Revision 1.106 2006/01/19 13:24:36 brouard
261: Some cleaning and links added in html output
262:
263: Revision 1.105 2006/01/05 20:23:19 lievre
264: *** empty log message ***
265:
266: Revision 1.104 2005/09/30 16:11:43 lievre
267: (Module): sump fixed, loop imx fixed, and simplifications.
268: (Module): If the status is missing at the last wave but we know
269: that the person is alive, then we can code his/her status as -2
270: (instead of missing=-1 in earlier versions) and his/her
271: contributions to the likelihood is 1 - Prob of dying from last
272: health status (= 1-p13= p11+p12 in the easiest case of somebody in
273: the healthy state at last known wave). Version is 0.98
274:
275: Revision 1.103 2005/09/30 15:54:49 lievre
276: (Module): sump fixed, loop imx fixed, and simplifications.
277:
278: Revision 1.102 2004/09/15 17:31:30 brouard
279: Add the possibility to read data file including tab characters.
280:
281: Revision 1.101 2004/09/15 10:38:38 brouard
282: Fix on curr_time
283:
284: Revision 1.100 2004/07/12 18:29:06 brouard
285: Add version for Mac OS X. Just define UNIX in Makefile
286:
287: Revision 1.99 2004/06/05 08:57:40 brouard
288: *** empty log message ***
289:
290: Revision 1.98 2004/05/16 15:05:56 brouard
291: New version 0.97 . First attempt to estimate force of mortality
292: directly from the data i.e. without the need of knowing the health
293: state at each age, but using a Gompertz model: log u =a + b*age .
294: This is the basic analysis of mortality and should be done before any
295: other analysis, in order to test if the mortality estimated from the
296: cross-longitudinal survey is different from the mortality estimated
297: from other sources like vital statistic data.
298:
299: The same imach parameter file can be used but the option for mle should be -3.
300:
1.133 brouard 301: Agnès, who wrote this part of the code, tried to keep most of the
1.126 brouard 302: former routines in order to include the new code within the former code.
303:
304: The output is very simple: only an estimate of the intercept and of
305: the slope with 95% confident intervals.
306:
307: Current limitations:
308: A) Even if you enter covariates, i.e. with the
309: model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
310: B) There is no computation of Life Expectancy nor Life Table.
311:
312: Revision 1.97 2004/02/20 13:25:42 lievre
313: Version 0.96d. Population forecasting command line is (temporarily)
314: suppressed.
315:
316: Revision 1.96 2003/07/15 15:38:55 brouard
317: * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
318: rewritten within the same printf. Workaround: many printfs.
319:
320: Revision 1.95 2003/07/08 07:54:34 brouard
321: * imach.c (Repository):
322: (Repository): Using imachwizard code to output a more meaningful covariance
323: matrix (cov(a12,c31) instead of numbers.
324:
325: Revision 1.94 2003/06/27 13:00:02 brouard
326: Just cleaning
327:
328: Revision 1.93 2003/06/25 16:33:55 brouard
329: (Module): On windows (cygwin) function asctime_r doesn't
330: exist so I changed back to asctime which exists.
331: (Module): Version 0.96b
332:
333: Revision 1.92 2003/06/25 16:30:45 brouard
334: (Module): On windows (cygwin) function asctime_r doesn't
335: exist so I changed back to asctime which exists.
336:
337: Revision 1.91 2003/06/25 15:30:29 brouard
338: * imach.c (Repository): Duplicated warning errors corrected.
339: (Repository): Elapsed time after each iteration is now output. It
340: helps to forecast when convergence will be reached. Elapsed time
341: is stamped in powell. We created a new html file for the graphs
342: concerning matrix of covariance. It has extension -cov.htm.
343:
344: Revision 1.90 2003/06/24 12:34:15 brouard
345: (Module): Some bugs corrected for windows. Also, when
346: mle=-1 a template is output in file "or"mypar.txt with the design
347: of the covariance matrix to be input.
348:
349: Revision 1.89 2003/06/24 12:30:52 brouard
350: (Module): Some bugs corrected for windows. Also, when
351: mle=-1 a template is output in file "or"mypar.txt with the design
352: of the covariance matrix to be input.
353:
354: Revision 1.88 2003/06/23 17:54:56 brouard
355: * 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.
356:
357: Revision 1.87 2003/06/18 12:26:01 brouard
358: Version 0.96
359:
360: Revision 1.86 2003/06/17 20:04:08 brouard
361: (Module): Change position of html and gnuplot routines and added
362: routine fileappend.
363:
364: Revision 1.85 2003/06/17 13:12:43 brouard
365: * imach.c (Repository): Check when date of death was earlier that
366: current date of interview. It may happen when the death was just
367: prior to the death. In this case, dh was negative and likelihood
368: was wrong (infinity). We still send an "Error" but patch by
369: assuming that the date of death was just one stepm after the
370: interview.
371: (Repository): Because some people have very long ID (first column)
372: we changed int to long in num[] and we added a new lvector for
373: memory allocation. But we also truncated to 8 characters (left
374: truncation)
375: (Repository): No more line truncation errors.
376:
377: Revision 1.84 2003/06/13 21:44:43 brouard
378: * imach.c (Repository): Replace "freqsummary" at a correct
379: place. It differs from routine "prevalence" which may be called
380: many times. Probs is memory consuming and must be used with
381: parcimony.
382: Version 0.95a3 (should output exactly the same maximization than 0.8a2)
383:
384: Revision 1.83 2003/06/10 13:39:11 lievre
385: *** empty log message ***
386:
387: Revision 1.82 2003/06/05 15:57:20 brouard
388: Add log in imach.c and fullversion number is now printed.
389:
390: */
391: /*
392: Interpolated Markov Chain
393:
394: Short summary of the programme:
395:
396: This program computes Healthy Life Expectancies from
397: cross-longitudinal data. Cross-longitudinal data consist in: -1- a
398: first survey ("cross") where individuals from different ages are
399: interviewed on their health status or degree of disability (in the
400: case of a health survey which is our main interest) -2- at least a
401: second wave of interviews ("longitudinal") which measure each change
402: (if any) in individual health status. Health expectancies are
403: computed from the time spent in each health state according to a
404: model. More health states you consider, more time is necessary to reach the
405: Maximum Likelihood of the parameters involved in the model. The
406: simplest model is the multinomial logistic model where pij is the
407: probability to be observed in state j at the second wave
408: conditional to be observed in state i at the first wave. Therefore
409: the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
410: 'age' is age and 'sex' is a covariate. If you want to have a more
411: complex model than "constant and age", you should modify the program
412: where the markup *Covariates have to be included here again* invites
413: you to do it. More covariates you add, slower the
414: convergence.
415:
416: The advantage of this computer programme, compared to a simple
417: multinomial logistic model, is clear when the delay between waves is not
418: identical for each individual. Also, if a individual missed an
419: intermediate interview, the information is lost, but taken into
420: account using an interpolation or extrapolation.
421:
422: hPijx is the probability to be observed in state i at age x+h
423: conditional to the observed state i at age x. The delay 'h' can be
424: split into an exact number (nh*stepm) of unobserved intermediate
425: states. This elementary transition (by month, quarter,
426: semester or year) is modelled as a multinomial logistic. The hPx
427: matrix is simply the matrix product of nh*stepm elementary matrices
428: and the contribution of each individual to the likelihood is simply
429: hPijx.
430:
431: Also this programme outputs the covariance matrix of the parameters but also
432: of the life expectancies. It also computes the period (stable) prevalence.
433:
1.133 brouard 434: Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
435: Institut national d'études démographiques, Paris.
1.126 brouard 436: This software have been partly granted by Euro-REVES, a concerted action
437: from the European Union.
438: It is copyrighted identically to a GNU software product, ie programme and
439: software can be distributed freely for non commercial use. Latest version
440: can be accessed at http://euroreves.ined.fr/imach .
441:
442: Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
443: or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
444:
445: **********************************************************************/
446: /*
447: main
448: read parameterfile
449: read datafile
450: concatwav
451: freqsummary
452: if (mle >= 1)
453: mlikeli
454: print results files
455: if mle==1
456: computes hessian
457: read end of parameter file: agemin, agemax, bage, fage, estepm
458: begin-prev-date,...
459: open gnuplot file
460: open html file
1.145 brouard 461: period (stable) prevalence | pl_nom 1-1 2-2 etc by covariate
462: for age prevalim() | #****** V1=0 V2=1 V3=1 V4=0 ******
463: | 65 1 0 2 1 3 1 4 0 0.96326 0.03674
464: freexexit2 possible for memory heap.
465:
466: h Pij x | pij_nom ficrestpij
467: # Cov Agex agex+h hpijx with i,j= 1-1 1-2 1-3 2-1 2-2 2-3
468: 1 85 85 1.00000 0.00000 0.00000 0.00000 1.00000 0.00000
469: 1 85 86 0.68299 0.22291 0.09410 0.71093 0.00000 0.28907
470:
471: 1 65 99 0.00364 0.00322 0.99314 0.00350 0.00310 0.99340
472: 1 65 100 0.00214 0.00204 0.99581 0.00206 0.00196 0.99597
473: variance of p one-step probabilities varprob | prob_nom ficresprob #One-step probabilities and stand. devi in ()
474: Standard deviation of one-step probabilities | probcor_nom ficresprobcor #One-step probabilities and correlation matrix
475: Matrix of variance covariance of one-step probabilities | probcov_nom ficresprobcov #One-step probabilities and covariance matrix
476:
1.126 brouard 477: forecasting if prevfcast==1 prevforecast call prevalence()
478: health expectancies
479: Variance-covariance of DFLE
480: prevalence()
481: movingaverage()
482: varevsij()
483: if popbased==1 varevsij(,popbased)
484: total life expectancies
485: Variance of period (stable) prevalence
486: end
487: */
488:
489:
490:
491:
492: #include <math.h>
493: #include <stdio.h>
494: #include <stdlib.h>
495: #include <string.h>
1.159 brouard 496:
497: #ifdef _WIN32
498: #include <io.h>
499: #else
1.126 brouard 500: #include <unistd.h>
1.159 brouard 501: #endif
1.126 brouard 502:
503: #include <limits.h>
504: #include <sys/types.h>
505: #include <sys/stat.h>
506: #include <errno.h>
1.159 brouard 507: /* extern int errno; */
1.126 brouard 508:
1.157 brouard 509: /* #ifdef LINUX */
510: /* #include <time.h> */
511: /* #include "timeval.h" */
512: /* #else */
513: /* #include <sys/time.h> */
514: /* #endif */
515:
1.126 brouard 516: #include <time.h>
517:
1.136 brouard 518: #ifdef GSL
519: #include <gsl/gsl_errno.h>
520: #include <gsl/gsl_multimin.h>
521: #endif
522:
1.162 ! brouard 523: #ifdef NLOPT
! 524: #include <nlopt.h>
! 525: typedef struct {
! 526: double (* function)(double [] );
! 527: } myfunc_data ;
! 528: #endif
! 529:
1.126 brouard 530: /* #include <libintl.h> */
531: /* #define _(String) gettext (String) */
532:
1.141 brouard 533: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126 brouard 534:
535: #define GNUPLOTPROGRAM "gnuplot"
536: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
537: #define FILENAMELENGTH 132
538:
539: #define GLOCK_ERROR_NOPATH -1 /* empty path */
540: #define GLOCK_ERROR_GETCWD -2 /* cannot get cwd */
541:
1.144 brouard 542: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
543: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126 brouard 544:
545: #define NINTERVMAX 8
1.144 brouard 546: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
547: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
548: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.145 brouard 549: #define codtabm(h,k) 1 & (h-1) >> (k-1) ;
1.126 brouard 550: #define MAXN 20000
1.144 brouard 551: #define YEARM 12. /**< Number of months per year */
1.126 brouard 552: #define AGESUP 130
553: #define AGEBASE 40
1.144 brouard 554: #define AGEGOMP 10. /**< Minimal age for Gompertz adjustment */
1.157 brouard 555: #ifdef _WIN32
556: #define DIRSEPARATOR '\\'
557: #define CHARSEPARATOR "\\"
558: #define ODIRSEPARATOR '/'
559: #else
1.126 brouard 560: #define DIRSEPARATOR '/'
561: #define CHARSEPARATOR "/"
562: #define ODIRSEPARATOR '\\'
563: #endif
564:
1.162 ! brouard 565: /* $Id: imach-nlopt.c,v 1.1 2014/09/16 11:06:58 brouard Exp $ */
1.126 brouard 566: /* $State: Exp $ */
567:
1.162 ! brouard 568: 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)";
! 569: char fullversion[]="$Revision: 1.1 $ $Date: 2014/09/16 11:06:58 $";
1.126 brouard 570: char strstart[80];
571: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130 brouard 572: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings */
1.133 brouard 573: int nvar=0, nforce=0; /* Number of variables, number of forces */
1.145 brouard 574: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
575: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
576: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
577: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
578: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
579: int cptcovprodnoage=0; /**< Number of covariate products without age */
580: int cptcoveff=0; /* Total number of covariates to vary for printing results */
581: int cptcov=0; /* Working variable */
1.126 brouard 582: int npar=NPARMAX;
583: int nlstate=2; /* Number of live states */
584: int ndeath=1; /* Number of dead states */
1.130 brouard 585: int ncovmodel=0, ncovcol=0; /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126 brouard 586: int popbased=0;
587:
588: int *wav; /* Number of waves for this individuual 0 is possible */
1.130 brouard 589: int maxwav=0; /* Maxim number of waves */
590: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
591: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */
592: int gipmx=0, gsw=0; /* Global variables on the number of contributions
1.126 brouard 593: to the likelihood and the sum of weights (done by funcone)*/
1.130 brouard 594: int mle=1, weightopt=0;
1.126 brouard 595: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
596: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
597: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
598: * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162 ! brouard 599: int countcallfunc=0; /* Count the number of calls to func */
1.130 brouard 600: double jmean=1; /* Mean space between 2 waves */
1.145 brouard 601: double **matprod2(); /* test */
1.126 brouard 602: double **oldm, **newm, **savm; /* Working pointers to matrices */
603: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136 brouard 604: /*FILE *fic ; */ /* Used in readdata only */
605: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126 brouard 606: FILE *ficlog, *ficrespow;
1.130 brouard 607: int globpr=0; /* Global variable for printing or not */
1.126 brouard 608: double fretone; /* Only one call to likelihood */
1.130 brouard 609: long ipmx=0; /* Number of contributions */
1.126 brouard 610: double sw; /* Sum of weights */
611: char filerespow[FILENAMELENGTH];
612: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
613: FILE *ficresilk;
614: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
615: FILE *ficresprobmorprev;
616: FILE *fichtm, *fichtmcov; /* Html File */
617: FILE *ficreseij;
618: char filerese[FILENAMELENGTH];
619: FILE *ficresstdeij;
620: char fileresstde[FILENAMELENGTH];
621: FILE *ficrescveij;
622: char filerescve[FILENAMELENGTH];
623: FILE *ficresvij;
624: char fileresv[FILENAMELENGTH];
625: FILE *ficresvpl;
626: char fileresvpl[FILENAMELENGTH];
627: char title[MAXLINE];
628: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH], filerespl[FILENAMELENGTH];
629: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
630: char tmpout[FILENAMELENGTH], tmpout2[FILENAMELENGTH];
631: char command[FILENAMELENGTH];
632: int outcmd=0;
633:
634: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
635:
636: char filelog[FILENAMELENGTH]; /* Log file */
637: char filerest[FILENAMELENGTH];
638: char fileregp[FILENAMELENGTH];
639: char popfile[FILENAMELENGTH];
640:
641: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
642:
1.157 brouard 643: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
644: /* struct timezone tzp; */
645: /* extern int gettimeofday(); */
646: struct tm tml, *gmtime(), *localtime();
647:
648: extern time_t time();
649:
650: struct tm start_time, end_time, curr_time, last_time, forecast_time;
651: time_t rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
652: struct tm tm;
653:
1.126 brouard 654: char strcurr[80], strfor[80];
655:
656: char *endptr;
657: long lval;
658: double dval;
659:
660: #define NR_END 1
661: #define FREE_ARG char*
662: #define FTOL 1.0e-10
663:
664: #define NRANSI
665: #define ITMAX 200
666:
667: #define TOL 2.0e-4
668:
669: #define CGOLD 0.3819660
670: #define ZEPS 1.0e-10
671: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
672:
673: #define GOLD 1.618034
674: #define GLIMIT 100.0
675: #define TINY 1.0e-20
676:
677: static double maxarg1,maxarg2;
678: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
679: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
680:
681: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
682: #define rint(a) floor(a+0.5)
683:
684: static double sqrarg;
685: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
686: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
687: int agegomp= AGEGOMP;
688:
689: int imx;
690: int stepm=1;
691: /* Stepm, step in month: minimum step interpolation*/
692:
693: int estepm;
694: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
695:
696: int m,nb;
697: long *num;
698: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
699: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
700: double **pmmij, ***probs;
701: double *ageexmed,*agecens;
702: double dateintmean=0;
703:
704: double *weight;
705: int **s; /* Status */
1.141 brouard 706: double *agedc;
1.145 brouard 707: double **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141 brouard 708: * covar=matrix(0,NCOVMAX,1,n);
709: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; */
710: double idx;
711: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.145 brouard 712: int *Ndum; /** Freq of modality (tricode */
1.141 brouard 713: int **codtab; /**< codtab=imatrix(1,100,1,10); */
714: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126 brouard 715: double *lsurv, *lpop, *tpop;
716:
1.143 brouard 717: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
718: double ftolhess; /**< Tolerance for computing hessian */
1.126 brouard 719:
720: /**************** split *************************/
721: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
722: {
723: /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
724: the name of the file (name), its extension only (ext) and its first part of the name (finame)
725: */
726: char *ss; /* pointer */
727: int l1, l2; /* length counters */
728:
729: l1 = strlen(path ); /* length of path */
730: if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
731: ss= strrchr( path, DIRSEPARATOR ); /* find last / */
732: if ( ss == NULL ) { /* no directory, so determine current directory */
733: strcpy( name, path ); /* we got the fullname name because no directory */
734: /*if(strrchr(path, ODIRSEPARATOR )==NULL)
735: printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
736: /* get current working directory */
737: /* extern char* getcwd ( char *buf , int len);*/
738: if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
739: return( GLOCK_ERROR_GETCWD );
740: }
741: /* got dirc from getcwd*/
742: printf(" DIRC = %s \n",dirc);
743: } else { /* strip direcotry from path */
744: ss++; /* after this, the filename */
745: l2 = strlen( ss ); /* length of filename */
746: if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
747: strcpy( name, ss ); /* save file name */
748: strncpy( dirc, path, l1 - l2 ); /* now the directory */
749: dirc[l1-l2] = 0; /* add zero */
750: printf(" DIRC2 = %s \n",dirc);
751: }
752: /* We add a separator at the end of dirc if not exists */
753: l1 = strlen( dirc ); /* length of directory */
754: if( dirc[l1-1] != DIRSEPARATOR ){
755: dirc[l1] = DIRSEPARATOR;
756: dirc[l1+1] = 0;
757: printf(" DIRC3 = %s \n",dirc);
758: }
759: ss = strrchr( name, '.' ); /* find last / */
760: if (ss >0){
761: ss++;
762: strcpy(ext,ss); /* save extension */
763: l1= strlen( name);
764: l2= strlen(ss)+1;
765: strncpy( finame, name, l1-l2);
766: finame[l1-l2]= 0;
767: }
768:
769: return( 0 ); /* we're done */
770: }
771:
772:
773: /******************************************/
774:
775: void replace_back_to_slash(char *s, char*t)
776: {
777: int i;
778: int lg=0;
779: i=0;
780: lg=strlen(t);
781: for(i=0; i<= lg; i++) {
782: (s[i] = t[i]);
783: if (t[i]== '\\') s[i]='/';
784: }
785: }
786:
1.132 brouard 787: char *trimbb(char *out, char *in)
1.137 brouard 788: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132 brouard 789: char *s;
790: s=out;
791: while (*in != '\0'){
1.137 brouard 792: while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132 brouard 793: in++;
794: }
795: *out++ = *in++;
796: }
797: *out='\0';
798: return s;
799: }
800:
1.145 brouard 801: char *cutl(char *blocc, char *alocc, char *in, char occ)
802: {
803: /* cuts string in into blocc and alocc where blocc ends before first occurence of char 'occ'
804: and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
805: gives blocc="abcdef2ghi" and alocc="j".
806: If occ is not found blocc is null and alocc is equal to in. Returns blocc
807: */
1.160 brouard 808: char *s, *t;
1.145 brouard 809: t=in;s=in;
810: while ((*in != occ) && (*in != '\0')){
811: *alocc++ = *in++;
812: }
813: if( *in == occ){
814: *(alocc)='\0';
815: s=++in;
816: }
817:
818: if (s == t) {/* occ not found */
819: *(alocc-(in-s))='\0';
820: in=s;
821: }
822: while ( *in != '\0'){
823: *blocc++ = *in++;
824: }
825:
826: *blocc='\0';
827: return t;
828: }
1.137 brouard 829: char *cutv(char *blocc, char *alocc, char *in, char occ)
830: {
831: /* cuts string in into blocc and alocc where blocc ends before last occurence of char 'occ'
832: and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
833: gives blocc="abcdef2ghi" and alocc="j".
834: If occ is not found blocc is null and alocc is equal to in. Returns alocc
835: */
836: char *s, *t;
837: t=in;s=in;
838: while (*in != '\0'){
839: while( *in == occ){
840: *blocc++ = *in++;
841: s=in;
842: }
843: *blocc++ = *in++;
844: }
845: if (s == t) /* occ not found */
846: *(blocc-(in-s))='\0';
847: else
848: *(blocc-(in-s)-1)='\0';
849: in=s;
850: while ( *in != '\0'){
851: *alocc++ = *in++;
852: }
853:
854: *alocc='\0';
855: return s;
856: }
857:
1.126 brouard 858: int nbocc(char *s, char occ)
859: {
860: int i,j=0;
861: int lg=20;
862: i=0;
863: lg=strlen(s);
864: for(i=0; i<= lg; i++) {
865: if (s[i] == occ ) j++;
866: }
867: return j;
868: }
869:
1.137 brouard 870: /* void cutv(char *u,char *v, char*t, char occ) */
871: /* { */
872: /* /\* cuts string t into u and v where u ends before last occurence of char 'occ' */
873: /* and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
874: /* gives u="abcdef2ghi" and v="j" *\/ */
875: /* int i,lg,j,p=0; */
876: /* i=0; */
877: /* lg=strlen(t); */
878: /* for(j=0; j<=lg-1; j++) { */
879: /* if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
880: /* } */
1.126 brouard 881:
1.137 brouard 882: /* for(j=0; j<p; j++) { */
883: /* (u[j] = t[j]); */
884: /* } */
885: /* u[p]='\0'; */
1.126 brouard 886:
1.137 brouard 887: /* for(j=0; j<= lg; j++) { */
888: /* if (j>=(p+1))(v[j-p-1] = t[j]); */
889: /* } */
890: /* } */
1.126 brouard 891:
1.160 brouard 892: #ifdef _WIN32
893: char * strsep(char **pp, const char *delim)
894: {
895: char *p, *q;
896:
897: if ((p = *pp) == NULL)
898: return 0;
899: if ((q = strpbrk (p, delim)) != NULL)
900: {
901: *pp = q + 1;
902: *q = '\0';
903: }
904: else
905: *pp = 0;
906: return p;
907: }
908: #endif
909:
1.126 brouard 910: /********************** nrerror ********************/
911:
912: void nrerror(char error_text[])
913: {
914: fprintf(stderr,"ERREUR ...\n");
915: fprintf(stderr,"%s\n",error_text);
916: exit(EXIT_FAILURE);
917: }
918: /*********************** vector *******************/
919: double *vector(int nl, int nh)
920: {
921: double *v;
922: v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
923: if (!v) nrerror("allocation failure in vector");
924: return v-nl+NR_END;
925: }
926:
927: /************************ free vector ******************/
928: void free_vector(double*v, int nl, int nh)
929: {
930: free((FREE_ARG)(v+nl-NR_END));
931: }
932:
933: /************************ivector *******************************/
934: int *ivector(long nl,long nh)
935: {
936: int *v;
937: v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
938: if (!v) nrerror("allocation failure in ivector");
939: return v-nl+NR_END;
940: }
941:
942: /******************free ivector **************************/
943: void free_ivector(int *v, long nl, long nh)
944: {
945: free((FREE_ARG)(v+nl-NR_END));
946: }
947:
948: /************************lvector *******************************/
949: long *lvector(long nl,long nh)
950: {
951: long *v;
952: v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
953: if (!v) nrerror("allocation failure in ivector");
954: return v-nl+NR_END;
955: }
956:
957: /******************free lvector **************************/
958: void free_lvector(long *v, long nl, long nh)
959: {
960: free((FREE_ARG)(v+nl-NR_END));
961: }
962:
963: /******************* imatrix *******************************/
964: int **imatrix(long nrl, long nrh, long ncl, long nch)
965: /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
966: {
967: long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
968: int **m;
969:
970: /* allocate pointers to rows */
971: m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
972: if (!m) nrerror("allocation failure 1 in matrix()");
973: m += NR_END;
974: m -= nrl;
975:
976:
977: /* allocate rows and set pointers to them */
978: m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
979: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
980: m[nrl] += NR_END;
981: m[nrl] -= ncl;
982:
983: for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
984:
985: /* return pointer to array of pointers to rows */
986: return m;
987: }
988:
989: /****************** free_imatrix *************************/
990: void free_imatrix(m,nrl,nrh,ncl,nch)
991: int **m;
992: long nch,ncl,nrh,nrl;
993: /* free an int matrix allocated by imatrix() */
994: {
995: free((FREE_ARG) (m[nrl]+ncl-NR_END));
996: free((FREE_ARG) (m+nrl-NR_END));
997: }
998:
999: /******************* matrix *******************************/
1000: double **matrix(long nrl, long nrh, long ncl, long nch)
1001: {
1002: long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
1003: double **m;
1004:
1005: m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1006: if (!m) nrerror("allocation failure 1 in matrix()");
1007: m += NR_END;
1008: m -= nrl;
1009:
1010: m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1011: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1012: m[nrl] += NR_END;
1013: m[nrl] -= ncl;
1014:
1015: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1016: return m;
1.145 brouard 1017: /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
1018: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
1019: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126 brouard 1020: */
1021: }
1022:
1023: /*************************free matrix ************************/
1024: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
1025: {
1026: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1027: free((FREE_ARG)(m+nrl-NR_END));
1028: }
1029:
1030: /******************* ma3x *******************************/
1031: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
1032: {
1033: long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
1034: double ***m;
1035:
1036: m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1037: if (!m) nrerror("allocation failure 1 in matrix()");
1038: m += NR_END;
1039: m -= nrl;
1040:
1041: m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1042: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1043: m[nrl] += NR_END;
1044: m[nrl] -= ncl;
1045:
1046: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1047:
1048: m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
1049: if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
1050: m[nrl][ncl] += NR_END;
1051: m[nrl][ncl] -= nll;
1052: for (j=ncl+1; j<=nch; j++)
1053: m[nrl][j]=m[nrl][j-1]+nlay;
1054:
1055: for (i=nrl+1; i<=nrh; i++) {
1056: m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
1057: for (j=ncl+1; j<=nch; j++)
1058: m[i][j]=m[i][j-1]+nlay;
1059: }
1060: return m;
1061: /* gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
1062: &(m[i][j][k]) <=> *((*(m+i) + j)+k)
1063: */
1064: }
1065:
1066: /*************************free ma3x ************************/
1067: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
1068: {
1069: free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
1070: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1071: free((FREE_ARG)(m+nrl-NR_END));
1072: }
1073:
1074: /*************** function subdirf ***********/
1075: char *subdirf(char fileres[])
1076: {
1077: /* Caution optionfilefiname is hidden */
1078: strcpy(tmpout,optionfilefiname);
1079: strcat(tmpout,"/"); /* Add to the right */
1080: strcat(tmpout,fileres);
1081: return tmpout;
1082: }
1083:
1084: /*************** function subdirf2 ***********/
1085: char *subdirf2(char fileres[], char *preop)
1086: {
1087:
1088: /* Caution optionfilefiname is hidden */
1089: strcpy(tmpout,optionfilefiname);
1090: strcat(tmpout,"/");
1091: strcat(tmpout,preop);
1092: strcat(tmpout,fileres);
1093: return tmpout;
1094: }
1095:
1096: /*************** function subdirf3 ***********/
1097: char *subdirf3(char fileres[], char *preop, char *preop2)
1098: {
1099:
1100: /* Caution optionfilefiname is hidden */
1101: strcpy(tmpout,optionfilefiname);
1102: strcat(tmpout,"/");
1103: strcat(tmpout,preop);
1104: strcat(tmpout,preop2);
1105: strcat(tmpout,fileres);
1106: return tmpout;
1107: }
1108:
1.162 ! brouard 1109: char *asc_diff_time(long time_sec, char ascdiff[])
! 1110: {
! 1111: long sec_left, days, hours, minutes;
! 1112: days = (time_sec) / (60*60*24);
! 1113: sec_left = (time_sec) % (60*60*24);
! 1114: hours = (sec_left) / (60*60) ;
! 1115: sec_left = (sec_left) %(60*60);
! 1116: minutes = (sec_left) /60;
! 1117: sec_left = (sec_left) % (60);
! 1118: sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);
! 1119: return ascdiff;
! 1120: }
! 1121:
1.126 brouard 1122: /***************** f1dim *************************/
1123: extern int ncom;
1124: extern double *pcom,*xicom;
1125: extern double (*nrfunc)(double []);
1126:
1127: double f1dim(double x)
1128: {
1129: int j;
1130: double f;
1131: double *xt;
1132:
1133: xt=vector(1,ncom);
1134: for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
1135: f=(*nrfunc)(xt);
1136: free_vector(xt,1,ncom);
1137: return f;
1138: }
1139:
1140: /*****************brent *************************/
1141: double brent(double ax, double bx, double cx, double (*f)(double), double tol, double *xmin)
1142: {
1143: int iter;
1144: double a,b,d,etemp;
1.159 brouard 1145: double fu=0,fv,fw,fx;
1.126 brouard 1146: double ftemp;
1147: double p,q,r,tol1,tol2,u,v,w,x,xm;
1148: double e=0.0;
1149:
1150: a=(ax < cx ? ax : cx);
1151: b=(ax > cx ? ax : cx);
1152: x=w=v=bx;
1153: fw=fv=fx=(*f)(x);
1154: for (iter=1;iter<=ITMAX;iter++) {
1155: xm=0.5*(a+b);
1156: tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
1157: /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
1158: printf(".");fflush(stdout);
1159: fprintf(ficlog,".");fflush(ficlog);
1.162 ! brouard 1160: #ifdef DEBUGBRENT
1.126 brouard 1161: 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);
1162: 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);
1163: /* if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
1164: #endif
1165: if (fabs(x-xm) <= (tol2-0.5*(b-a))){
1166: *xmin=x;
1167: return fx;
1168: }
1169: ftemp=fu;
1170: if (fabs(e) > tol1) {
1171: r=(x-w)*(fx-fv);
1172: q=(x-v)*(fx-fw);
1173: p=(x-v)*q-(x-w)*r;
1174: q=2.0*(q-r);
1175: if (q > 0.0) p = -p;
1176: q=fabs(q);
1177: etemp=e;
1178: e=d;
1179: if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
1180: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1181: else {
1182: d=p/q;
1183: u=x+d;
1184: if (u-a < tol2 || b-u < tol2)
1185: d=SIGN(tol1,xm-x);
1186: }
1187: } else {
1188: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1189: }
1190: u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
1191: fu=(*f)(u);
1192: if (fu <= fx) {
1193: if (u >= x) a=x; else b=x;
1194: SHFT(v,w,x,u)
1195: SHFT(fv,fw,fx,fu)
1196: } else {
1197: if (u < x) a=u; else b=u;
1198: if (fu <= fw || w == x) {
1199: v=w;
1200: w=u;
1201: fv=fw;
1202: fw=fu;
1203: } else if (fu <= fv || v == x || v == w) {
1204: v=u;
1205: fv=fu;
1206: }
1207: }
1208: }
1209: nrerror("Too many iterations in brent");
1210: *xmin=x;
1211: return fx;
1212: }
1213:
1214: /****************** mnbrak ***********************/
1215:
1216: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
1217: double (*func)(double))
1218: {
1219: double ulim,u,r,q, dum;
1220: double fu;
1221:
1222: *fa=(*func)(*ax);
1223: *fb=(*func)(*bx);
1224: if (*fb > *fa) {
1225: SHFT(dum,*ax,*bx,dum)
1226: SHFT(dum,*fb,*fa,dum)
1227: }
1228: *cx=(*bx)+GOLD*(*bx-*ax);
1229: *fc=(*func)(*cx);
1.162 ! brouard 1230: while (*fb > *fc) { /* Declining fa, fb, fc */
1.126 brouard 1231: r=(*bx-*ax)*(*fb-*fc);
1232: q=(*bx-*cx)*(*fb-*fa);
1233: u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
1.162 ! brouard 1234: (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscisse of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
! 1235: ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscisse where function can be evaluated */
! 1236: if ((*bx-u)*(u-*cx) > 0.0) { /* if u between b and c */
1.126 brouard 1237: fu=(*func)(u);
1.162 ! brouard 1238: } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.126 brouard 1239: fu=(*func)(u);
1240: if (fu < *fc) {
1241: SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
1242: SHFT(*fb,*fc,fu,(*func)(u))
1243: }
1.162 ! brouard 1244: } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.126 brouard 1245: u=ulim;
1246: fu=(*func)(u);
1247: } else {
1248: u=(*cx)+GOLD*(*cx-*bx);
1249: fu=(*func)(u);
1250: }
1251: SHFT(*ax,*bx,*cx,u)
1252: SHFT(*fa,*fb,*fc,fu)
1253: }
1254: }
1255:
1256: /*************** linmin ************************/
1.162 ! brouard 1257: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
! 1258: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
! 1259: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
! 1260: the value of func at the returned location p . This is actually all accomplished by calling the
! 1261: routines mnbrak and brent .*/
1.126 brouard 1262: int ncom;
1263: double *pcom,*xicom;
1264: double (*nrfunc)(double []);
1265:
1266: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
1267: {
1268: double brent(double ax, double bx, double cx,
1269: double (*f)(double), double tol, double *xmin);
1270: double f1dim(double x);
1271: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
1272: double *fc, double (*func)(double));
1273: int j;
1274: double xx,xmin,bx,ax;
1275: double fx,fb,fa;
1276:
1277: ncom=n;
1278: pcom=vector(1,n);
1279: xicom=vector(1,n);
1280: nrfunc=func;
1281: for (j=1;j<=n;j++) {
1282: pcom[j]=p[j];
1283: xicom[j]=xi[j];
1284: }
1285: ax=0.0;
1286: xx=1.0;
1.162 ! brouard 1287: mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Find a bracket a,x,b in direction n=xi ie xicom */
! 1288: *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 1289: #ifdef DEBUG
1290: printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1291: fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1292: #endif
1293: for (j=1;j<=n;j++) {
1294: xi[j] *= xmin;
1295: p[j] += xi[j];
1296: }
1297: free_vector(xicom,1,n);
1298: free_vector(pcom,1,n);
1299: }
1300:
1301:
1302: /*************** powell ************************/
1.162 ! brouard 1303: /*
! 1304: Minimization of a function func of n variables. Input consists of an initial starting point
! 1305: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
! 1306: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
! 1307: such that failure to decrease by more than this amount on one iteration signals doneness. On
! 1308: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
! 1309: function value at p , and iter is the number of iterations taken. The routine linmin is used.
! 1310: */
1.126 brouard 1311: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
1312: double (*func)(double []))
1313: {
1314: void linmin(double p[], double xi[], int n, double *fret,
1315: double (*func)(double []));
1316: int i,ibig,j;
1317: double del,t,*pt,*ptt,*xit;
1318: double fp,fptt;
1319: double *xits;
1320: int niterf, itmp;
1321:
1322: pt=vector(1,n);
1323: ptt=vector(1,n);
1324: xit=vector(1,n);
1325: xits=vector(1,n);
1326: *fret=(*func)(p);
1327: for (j=1;j<=n;j++) pt[j]=p[j];
1.157 brouard 1328: rcurr_time = time(NULL);
1.126 brouard 1329: for (*iter=1;;++(*iter)) {
1330: fp=(*fret);
1331: ibig=0;
1332: del=0.0;
1.157 brouard 1333: rlast_time=rcurr_time;
1334: /* (void) gettimeofday(&curr_time,&tzp); */
1335: rcurr_time = time(NULL);
1336: curr_time = *localtime(&rcurr_time);
1337: printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
1338: fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1339: /* fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.126 brouard 1340: for (i=1;i<=n;i++) {
1341: printf(" %d %.12f",i, p[i]);
1342: fprintf(ficlog," %d %.12lf",i, p[i]);
1343: fprintf(ficrespow," %.12lf", p[i]);
1344: }
1345: printf("\n");
1346: fprintf(ficlog,"\n");
1347: fprintf(ficrespow,"\n");fflush(ficrespow);
1348: if(*iter <=3){
1.157 brouard 1349: tml = *localtime(&rcurr_time);
1350: strcpy(strcurr,asctime(&tml));
1351: rforecast_time=rcurr_time;
1.126 brouard 1352: itmp = strlen(strcurr);
1353: if(strcurr[itmp-1]=='\n') /* Windows outputs with a new line */
1354: strcurr[itmp-1]='\0';
1.162 ! brouard 1355: printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157 brouard 1356: fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126 brouard 1357: for(niterf=10;niterf<=30;niterf+=10){
1.157 brouard 1358: rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
1359: forecast_time = *localtime(&rforecast_time);
1360: strcpy(strfor,asctime(&forecast_time));
1.126 brouard 1361: itmp = strlen(strfor);
1362: if(strfor[itmp-1]=='\n')
1363: strfor[itmp-1]='\0';
1.157 brouard 1364: 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);
1365: 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 1366: }
1367: }
1368: for (i=1;i<=n;i++) {
1369: for (j=1;j<=n;j++) xit[j]=xi[j][i];
1370: fptt=(*fret);
1371: #ifdef DEBUG
1372: printf("fret=%lf \n",*fret);
1373: fprintf(ficlog,"fret=%lf \n",*fret);
1374: #endif
1375: printf("%d",i);fflush(stdout);
1376: fprintf(ficlog,"%d",i);fflush(ficlog);
1377: linmin(p,xit,n,fret,func);
1378: if (fabs(fptt-(*fret)) > del) {
1379: del=fabs(fptt-(*fret));
1380: ibig=i;
1381: }
1382: #ifdef DEBUG
1383: printf("%d %.12e",i,(*fret));
1384: fprintf(ficlog,"%d %.12e",i,(*fret));
1385: for (j=1;j<=n;j++) {
1386: xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
1387: printf(" x(%d)=%.12e",j,xit[j]);
1388: fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1389: }
1390: for(j=1;j<=n;j++) {
1.162 ! brouard 1391: printf(" p(%d)=%.12e",j,p[j]);
! 1392: fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126 brouard 1393: }
1394: printf("\n");
1395: fprintf(ficlog,"\n");
1396: #endif
1.162 ! brouard 1397: } /* end i */
1.126 brouard 1398: if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
1399: #ifdef DEBUG
1400: int k[2],l;
1401: k[0]=1;
1402: k[1]=-1;
1403: printf("Max: %.12e",(*func)(p));
1404: fprintf(ficlog,"Max: %.12e",(*func)(p));
1405: for (j=1;j<=n;j++) {
1406: printf(" %.12e",p[j]);
1407: fprintf(ficlog," %.12e",p[j]);
1408: }
1409: printf("\n");
1410: fprintf(ficlog,"\n");
1411: for(l=0;l<=1;l++) {
1412: for (j=1;j<=n;j++) {
1413: ptt[j]=p[j]+(p[j]-pt[j])*k[l];
1414: printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1415: fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1416: }
1417: printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1418: fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1419: }
1420: #endif
1421:
1422:
1423: free_vector(xit,1,n);
1424: free_vector(xits,1,n);
1425: free_vector(ptt,1,n);
1426: free_vector(pt,1,n);
1427: return;
1428: }
1429: if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
1.161 brouard 1430: for (j=1;j<=n;j++) { /* Computes an extrapolated point */
1.126 brouard 1431: ptt[j]=2.0*p[j]-pt[j];
1432: xit[j]=p[j]-pt[j];
1433: pt[j]=p[j];
1434: }
1435: fptt=(*func)(ptt);
1.161 brouard 1436: if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.162 ! brouard 1437: /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161 brouard 1438: /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162 ! brouard 1439: /* Let f"(x2) be the 2nd derivative equal everywhere. */
! 1440: /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
! 1441: /* will reach at f3 = fm + h^2/2 f"m ; f" = (f1 -2f2 +f3 ) / h**2 */
1.161 brouard 1442: /* f1-f3 = delta(2h) = 2 h**2 f'' = 2(f1- 2f2 +f3) */
1443: /* Thus we compare delta(2h) with observed f1-f3 */
1.162 ! brouard 1444: /* or best gain on one ancient line 'del' with total */
! 1445: /* gain f1-f2 = f1 - f2 - 'del' with del */
1.161 brouard 1446: /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.162 ! brouard 1447:
1.161 brouard 1448: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del);
1449: t= t- del*SQR(fp-fptt);
1450: printf("t1= %.12lf, t2= %.12lf, t=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t);
1451: 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);
1452: #ifdef DEBUG
1453: printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1454: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1455: fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1456: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1457: 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);
1458: 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);
1459: #endif
1460: if (t < 0.0) { /* Then we use it for last direction */
1461: linmin(p,xit,n,fret,func); /* computes mean on the extrapolated direction.*/
1.126 brouard 1462: for (j=1;j<=n;j++) {
1.161 brouard 1463: xi[j][ibig]=xi[j][n]; /* Replace the direction with biggest decrease by n */
1464: xi[j][n]=xit[j]; /* and nth direction by the extrapolated */
1.126 brouard 1465: }
1.161 brouard 1466: printf("Gaining to use average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1467: fprintf(ficlog,"Gaining to use average direction of P0 P%d instead of biggest increase direction :\n",n,ibig);
1468:
1.126 brouard 1469: #ifdef DEBUG
1470: for(j=1;j<=n;j++){
1471: printf(" %.12e",xit[j]);
1472: fprintf(ficlog," %.12e",xit[j]);
1473: }
1474: printf("\n");
1475: fprintf(ficlog,"\n");
1476: #endif
1.162 ! brouard 1477: } /* end of t negative */
! 1478: } /* end if (fptt < fp) */
1.126 brouard 1479: }
1480: }
1481:
1482: /**** Prevalence limit (stable or period prevalence) ****************/
1483:
1484: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
1485: {
1486: /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1487: matrix by transitions matrix until convergence is reached */
1488:
1489: int i, ii,j,k;
1490: double min, max, maxmin, maxmax,sumnew=0.;
1.145 brouard 1491: /* double **matprod2(); */ /* test */
1.131 brouard 1492: double **out, cov[NCOVMAX+1], **pmij();
1.126 brouard 1493: double **newm;
1494: double agefin, delaymax=50 ; /* Max number of years to converge */
1495:
1496: for (ii=1;ii<=nlstate+ndeath;ii++)
1497: for (j=1;j<=nlstate+ndeath;j++){
1498: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1499: }
1500:
1501: cov[1]=1.;
1502:
1503: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1504: for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1505: newm=savm;
1506: /* Covariates have to be included here again */
1.138 brouard 1507: cov[2]=agefin;
1508:
1509: for (k=1; k<=cptcovn;k++) {
1510: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.145 brouard 1511: /*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 1512: }
1.145 brouard 1513: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1514: /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
1515: /* 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 1516:
1517: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
1518: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
1519: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145 brouard 1520: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1521: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142 brouard 1522: out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138 brouard 1523:
1.126 brouard 1524: savm=oldm;
1525: oldm=newm;
1526: maxmax=0.;
1527: for(j=1;j<=nlstate;j++){
1528: min=1.;
1529: max=0.;
1530: for(i=1; i<=nlstate; i++) {
1531: sumnew=0;
1532: for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
1533: prlim[i][j]= newm[i][j]/(1-sumnew);
1.145 brouard 1534: /*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 1535: max=FMAX(max,prlim[i][j]);
1536: min=FMIN(min,prlim[i][j]);
1537: }
1538: maxmin=max-min;
1539: maxmax=FMAX(maxmax,maxmin);
1540: }
1541: if(maxmax < ftolpl){
1542: return prlim;
1543: }
1544: }
1545: }
1546:
1547: /*************** transition probabilities ***************/
1548:
1549: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1550: {
1.138 brouard 1551: /* According to parameters values stored in x and the covariate's values stored in cov,
1552: computes the probability to be observed in state j being in state i by appying the
1553: model to the ncovmodel covariates (including constant and age).
1554: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
1555: and, according on how parameters are entered, the position of the coefficient xij(nc) of the
1556: ncth covariate in the global vector x is given by the formula:
1557: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
1558: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
1559: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
1560: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1561: Outputs ps[i][j] the probability to be observed in j being in j according to
1562: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1563: */
1564: double s1, lnpijopii;
1.126 brouard 1565: /*double t34;*/
1566: int i,j,j1, nc, ii, jj;
1567:
1568: for(i=1; i<= nlstate; i++){
1569: for(j=1; j<i;j++){
1.138 brouard 1570: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1571: /*lnpijopii += param[i][j][nc]*cov[nc];*/
1572: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
1573: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 1574: }
1.138 brouard 1575: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1576: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126 brouard 1577: }
1578: for(j=i+1; j<=nlstate+ndeath;j++){
1.138 brouard 1579: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1580: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
1581: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
1582: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126 brouard 1583: }
1.138 brouard 1584: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126 brouard 1585: }
1586: }
1587:
1588: for(i=1; i<= nlstate; i++){
1589: s1=0;
1.131 brouard 1590: for(j=1; j<i; j++){
1.138 brouard 1591: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 1592: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1593: }
1594: for(j=i+1; j<=nlstate+ndeath; j++){
1.138 brouard 1595: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131 brouard 1596: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1597: }
1.138 brouard 1598: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126 brouard 1599: ps[i][i]=1./(s1+1.);
1.138 brouard 1600: /* Computing other pijs */
1.126 brouard 1601: for(j=1; j<i; j++)
1602: ps[i][j]= exp(ps[i][j])*ps[i][i];
1603: for(j=i+1; j<=nlstate+ndeath; j++)
1604: ps[i][j]= exp(ps[i][j])*ps[i][i];
1605: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
1606: } /* end i */
1607:
1608: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
1609: for(jj=1; jj<= nlstate+ndeath; jj++){
1610: ps[ii][jj]=0;
1611: ps[ii][ii]=1;
1612: }
1613: }
1614:
1.145 brouard 1615:
1616: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
1617: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */
1618: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
1619: /* } */
1620: /* printf("\n "); */
1621: /* } */
1622: /* printf("\n ");printf("%lf ",cov[2]);*/
1623: /*
1.126 brouard 1624: for(i=1; i<= npar; i++) printf("%f ",x[i]);
1625: goto end;*/
1626: return ps;
1627: }
1628:
1629: /**************** Product of 2 matrices ******************/
1630:
1.145 brouard 1631: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126 brouard 1632: {
1633: /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
1634: b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
1635: /* in, b, out are matrice of pointers which should have been initialized
1636: before: only the contents of out is modified. The function returns
1637: a pointer to pointers identical to out */
1.145 brouard 1638: int i, j, k;
1.126 brouard 1639: for(i=nrl; i<= nrh; i++)
1.145 brouard 1640: for(k=ncolol; k<=ncoloh; k++){
1641: out[i][k]=0.;
1642: for(j=ncl; j<=nch; j++)
1643: out[i][k] +=in[i][j]*b[j][k];
1644: }
1.126 brouard 1645: return out;
1646: }
1647:
1648:
1649: /************* Higher Matrix Product ***************/
1650:
1651: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
1652: {
1653: /* Computes the transition matrix starting at age 'age' over
1654: 'nhstepm*hstepm*stepm' months (i.e. until
1655: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
1656: nhstepm*hstepm matrices.
1657: Output is stored in matrix po[i][j][h] for h every 'hstepm' step
1658: (typically every 2 years instead of every month which is too big
1659: for the memory).
1660: Model is determined by parameters x and covariates have to be
1661: included manually here.
1662:
1663: */
1664:
1665: int i, j, d, h, k;
1.131 brouard 1666: double **out, cov[NCOVMAX+1];
1.126 brouard 1667: double **newm;
1668:
1669: /* Hstepm could be zero and should return the unit matrix */
1670: for (i=1;i<=nlstate+ndeath;i++)
1671: for (j=1;j<=nlstate+ndeath;j++){
1672: oldm[i][j]=(i==j ? 1.0 : 0.0);
1673: po[i][j][0]=(i==j ? 1.0 : 0.0);
1674: }
1675: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1676: for(h=1; h <=nhstepm; h++){
1677: for(d=1; d <=hstepm; d++){
1678: newm=savm;
1679: /* Covariates have to be included here again */
1680: cov[1]=1.;
1681: cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
1.131 brouard 1682: for (k=1; k<=cptcovn;k++)
1683: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.126 brouard 1684: for (k=1; k<=cptcovage;k++)
1685: cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
1.145 brouard 1686: for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.126 brouard 1687: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
1688:
1689:
1690: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
1691: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1692: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
1693: pmij(pmmij,cov,ncovmodel,x,nlstate));
1694: savm=oldm;
1695: oldm=newm;
1696: }
1697: for(i=1; i<=nlstate+ndeath; i++)
1698: for(j=1;j<=nlstate+ndeath;j++) {
1699: po[i][j][h]=newm[i][j];
1.128 brouard 1700: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126 brouard 1701: }
1.128 brouard 1702: /*printf("h=%d ",h);*/
1.126 brouard 1703: } /* end h */
1.128 brouard 1704: /* printf("\n H=%d \n",h); */
1.126 brouard 1705: return po;
1706: }
1707:
1.162 ! brouard 1708: #ifdef NLOPT
! 1709: double myfunc(unsigned n, const double *p1, double *grad, void *pd){
! 1710: double fret;
! 1711: double *xt;
! 1712: int j;
! 1713: myfunc_data *d2 = (myfunc_data *) pd;
! 1714: /* xt = (p1-1); */
! 1715: xt=vector(1,n);
! 1716: for (j=1;j<=n;j++) xt[j]=p1[j-1]; /* xt[1]=p1[0] */
! 1717:
! 1718: fret=(d2->function)(xt); /* p xt[1]@8 is fine */
! 1719: /* fret=(*func)(xt); /\* p xt[1]@8 is fine *\/ */
! 1720: printf("Function = %.12lf ",fret);
! 1721: for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]);
! 1722: printf("\n");
! 1723: free_vector(xt,1,n);
! 1724: return fret;
! 1725: }
! 1726: #endif
1.126 brouard 1727:
1728: /*************** log-likelihood *************/
1729: double func( double *x)
1730: {
1731: int i, ii, j, k, mi, d, kk;
1.131 brouard 1732: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 1733: double **out;
1734: double sw; /* Sum of weights */
1735: double lli; /* Individual log likelihood */
1736: int s1, s2;
1737: double bbh, survp;
1738: long ipmx;
1739: /*extern weight */
1740: /* We are differentiating ll according to initial status */
1741: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
1742: /*for(i=1;i<imx;i++)
1743: printf(" %d\n",s[4][i]);
1744: */
1.162 ! brouard 1745:
! 1746: ++countcallfunc;
! 1747:
1.126 brouard 1748: cov[1]=1.;
1749:
1750: for(k=1; k<=nlstate; k++) ll[k]=0.;
1751:
1752: if(mle==1){
1753: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138 brouard 1754: /* Computes the values of the ncovmodel covariates of the model
1755: depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
1756: Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
1757: to be observed in j being in i according to the model.
1758: */
1.145 brouard 1759: for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1760: cov[2+k]=covar[Tvar[k]][i];
1761: }
1.137 brouard 1762: /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4]
1.138 brouard 1763: is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]
1.137 brouard 1764: has been calculated etc */
1.126 brouard 1765: for(mi=1; mi<= wav[i]-1; mi++){
1766: for (ii=1;ii<=nlstate+ndeath;ii++)
1767: for (j=1;j<=nlstate+ndeath;j++){
1768: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1769: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1770: }
1771: for(d=0; d<dh[mi][i]; d++){
1772: newm=savm;
1773: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1774: for (kk=1; kk<=cptcovage;kk++) {
1.137 brouard 1775: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; /* Tage[kk] gives the data-covariate associated with age */
1.126 brouard 1776: }
1777: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1778: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1779: savm=oldm;
1780: oldm=newm;
1781: } /* end mult */
1782:
1783: /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
1784: /* But now since version 0.9 we anticipate for bias at large stepm.
1785: * If stepm is larger than one month (smallest stepm) and if the exact delay
1786: * (in months) between two waves is not a multiple of stepm, we rounded to
1787: * the nearest (and in case of equal distance, to the lowest) interval but now
1788: * we keep into memory the bias bh[mi][i] and also the previous matrix product
1789: * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
1790: * probability in order to take into account the bias as a fraction of the way
1791: * from savm to out if bh is negative or even beyond if bh is positive. bh varies
1792: * -stepm/2 to stepm/2 .
1793: * For stepm=1 the results are the same as for previous versions of Imach.
1794: * For stepm > 1 the results are less biased than in previous versions.
1795: */
1796: s1=s[mw[mi][i]][i];
1797: s2=s[mw[mi+1][i]][i];
1798: bbh=(double)bh[mi][i]/(double)stepm;
1799: /* bias bh is positive if real duration
1800: * is higher than the multiple of stepm and negative otherwise.
1801: */
1802: /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
1803: if( s2 > nlstate){
1804: /* i.e. if s2 is a death state and if the date of death is known
1805: then the contribution to the likelihood is the probability to
1806: die between last step unit time and current step unit time,
1807: which is also equal to probability to die before dh
1808: minus probability to die before dh-stepm .
1809: In version up to 0.92 likelihood was computed
1810: as if date of death was unknown. Death was treated as any other
1811: health state: the date of the interview describes the actual state
1812: and not the date of a change in health state. The former idea was
1813: to consider that at each interview the state was recorded
1814: (healthy, disable or death) and IMaCh was corrected; but when we
1815: introduced the exact date of death then we should have modified
1816: the contribution of an exact death to the likelihood. This new
1817: contribution is smaller and very dependent of the step unit
1818: stepm. It is no more the probability to die between last interview
1819: and month of death but the probability to survive from last
1820: interview up to one month before death multiplied by the
1821: probability to die within a month. Thanks to Chris
1822: Jackson for correcting this bug. Former versions increased
1823: mortality artificially. The bad side is that we add another loop
1824: which slows down the processing. The difference can be up to 10%
1825: lower mortality.
1826: */
1827: lli=log(out[s1][s2] - savm[s1][s2]);
1828:
1829:
1830: } else if (s2==-2) {
1831: for (j=1,survp=0. ; j<=nlstate; j++)
1832: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1833: /*survp += out[s1][j]; */
1834: lli= log(survp);
1835: }
1836:
1837: else if (s2==-4) {
1838: for (j=3,survp=0. ; j<=nlstate; j++)
1839: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1840: lli= log(survp);
1841: }
1842:
1843: else if (s2==-5) {
1844: for (j=1,survp=0. ; j<=2; j++)
1845: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1846: lli= log(survp);
1847: }
1848:
1849: else{
1850: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1851: /* 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 */
1852: }
1853: /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
1854: /*if(lli ==000.0)*/
1855: /*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); */
1856: ipmx +=1;
1857: sw += weight[i];
1858: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1859: } /* end of wave */
1860: } /* end of individual */
1861: } else if(mle==2){
1862: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1863: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1864: for(mi=1; mi<= wav[i]-1; mi++){
1865: for (ii=1;ii<=nlstate+ndeath;ii++)
1866: for (j=1;j<=nlstate+ndeath;j++){
1867: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1868: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1869: }
1870: for(d=0; d<=dh[mi][i]; d++){
1871: newm=savm;
1872: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1873: for (kk=1; kk<=cptcovage;kk++) {
1874: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1875: }
1876: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1877: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1878: savm=oldm;
1879: oldm=newm;
1880: } /* end mult */
1881:
1882: s1=s[mw[mi][i]][i];
1883: s2=s[mw[mi+1][i]][i];
1884: bbh=(double)bh[mi][i]/(double)stepm;
1885: 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 */
1886: ipmx +=1;
1887: sw += weight[i];
1888: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1889: } /* end of wave */
1890: } /* end of individual */
1891: } else if(mle==3){ /* exponential inter-extrapolation */
1892: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1893: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1894: for(mi=1; mi<= wav[i]-1; mi++){
1895: for (ii=1;ii<=nlstate+ndeath;ii++)
1896: for (j=1;j<=nlstate+ndeath;j++){
1897: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1898: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1899: }
1900: for(d=0; d<dh[mi][i]; d++){
1901: newm=savm;
1902: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1903: for (kk=1; kk<=cptcovage;kk++) {
1904: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1905: }
1906: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1907: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1908: savm=oldm;
1909: oldm=newm;
1910: } /* end mult */
1911:
1912: s1=s[mw[mi][i]][i];
1913: s2=s[mw[mi+1][i]][i];
1914: bbh=(double)bh[mi][i]/(double)stepm;
1915: 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 */
1916: ipmx +=1;
1917: sw += weight[i];
1918: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1919: } /* end of wave */
1920: } /* end of individual */
1921: }else if (mle==4){ /* ml=4 no inter-extrapolation */
1922: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1923: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1924: for(mi=1; mi<= wav[i]-1; mi++){
1925: for (ii=1;ii<=nlstate+ndeath;ii++)
1926: for (j=1;j<=nlstate+ndeath;j++){
1927: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1928: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1929: }
1930: for(d=0; d<dh[mi][i]; d++){
1931: newm=savm;
1932: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1933: for (kk=1; kk<=cptcovage;kk++) {
1934: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1935: }
1936:
1937: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1938: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1939: savm=oldm;
1940: oldm=newm;
1941: } /* end mult */
1942:
1943: s1=s[mw[mi][i]][i];
1944: s2=s[mw[mi+1][i]][i];
1945: if( s2 > nlstate){
1946: lli=log(out[s1][s2] - savm[s1][s2]);
1947: }else{
1948: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
1949: }
1950: ipmx +=1;
1951: sw += weight[i];
1952: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1953: /* 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]); */
1954: } /* end of wave */
1955: } /* end of individual */
1956: }else{ /* ml=5 no inter-extrapolation no jackson =0.8a */
1957: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1958: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1959: for(mi=1; mi<= wav[i]-1; mi++){
1960: for (ii=1;ii<=nlstate+ndeath;ii++)
1961: for (j=1;j<=nlstate+ndeath;j++){
1962: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1963: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1964: }
1965: for(d=0; d<dh[mi][i]; d++){
1966: newm=savm;
1967: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1968: for (kk=1; kk<=cptcovage;kk++) {
1969: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1970: }
1971:
1972: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1973: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1974: savm=oldm;
1975: oldm=newm;
1976: } /* end mult */
1977:
1978: s1=s[mw[mi][i]][i];
1979: s2=s[mw[mi+1][i]][i];
1980: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
1981: ipmx +=1;
1982: sw += weight[i];
1983: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1984: /*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]);*/
1985: } /* end of wave */
1986: } /* end of individual */
1987: } /* End of if */
1988: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
1989: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
1990: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
1991: return -l;
1992: }
1993:
1994: /*************** log-likelihood *************/
1995: double funcone( double *x)
1996: {
1997: /* Same as likeli but slower because of a lot of printf and if */
1998: int i, ii, j, k, mi, d, kk;
1.131 brouard 1999: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126 brouard 2000: double **out;
2001: double lli; /* Individual log likelihood */
2002: double llt;
2003: int s1, s2;
2004: double bbh, survp;
2005: /*extern weight */
2006: /* We are differentiating ll according to initial status */
2007: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2008: /*for(i=1;i<imx;i++)
2009: printf(" %d\n",s[4][i]);
2010: */
2011: cov[1]=1.;
2012:
2013: for(k=1; k<=nlstate; k++) ll[k]=0.;
2014:
2015: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2016: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2017: for(mi=1; mi<= wav[i]-1; mi++){
2018: for (ii=1;ii<=nlstate+ndeath;ii++)
2019: for (j=1;j<=nlstate+ndeath;j++){
2020: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2021: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2022: }
2023: for(d=0; d<dh[mi][i]; d++){
2024: newm=savm;
2025: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2026: for (kk=1; kk<=cptcovage;kk++) {
2027: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2028: }
1.145 brouard 2029: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126 brouard 2030: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2031: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145 brouard 2032: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
2033: /* 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126 brouard 2034: savm=oldm;
2035: oldm=newm;
2036: } /* end mult */
2037:
2038: s1=s[mw[mi][i]][i];
2039: s2=s[mw[mi+1][i]][i];
2040: bbh=(double)bh[mi][i]/(double)stepm;
2041: /* bias is positive if real duration
2042: * is higher than the multiple of stepm and negative otherwise.
2043: */
2044: if( s2 > nlstate && (mle <5) ){ /* Jackson */
2045: lli=log(out[s1][s2] - savm[s1][s2]);
2046: } else if (s2==-2) {
2047: for (j=1,survp=0. ; j<=nlstate; j++)
2048: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2049: lli= log(survp);
2050: }else if (mle==1){
2051: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2052: } else if(mle==2){
2053: 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 */
2054: } else if(mle==3){ /* exponential inter-extrapolation */
2055: 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 */
2056: } else if (mle==4){ /* mle=4 no inter-extrapolation */
2057: lli=log(out[s1][s2]); /* Original formula */
1.136 brouard 2058: } else{ /* mle=0 back to 1 */
2059: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2060: /*lli=log(out[s1][s2]); */ /* Original formula */
1.126 brouard 2061: } /* End of if */
2062: ipmx +=1;
2063: sw += weight[i];
2064: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132 brouard 2065: /*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 2066: if(globpr){
1.141 brouard 2067: fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
1.126 brouard 2068: %11.6f %11.6f %11.6f ", \
2069: num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
2070: 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
2071: for(k=1,llt=0.,l=0.; k<=nlstate; k++){
2072: llt +=ll[k]*gipmx/gsw;
2073: fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
2074: }
2075: fprintf(ficresilk," %10.6f\n", -llt);
2076: }
2077: } /* end of wave */
2078: } /* end of individual */
2079: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2080: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2081: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2082: if(globpr==0){ /* First time we count the contributions and weights */
2083: gipmx=ipmx;
2084: gsw=sw;
2085: }
2086: return -l;
2087: }
2088:
2089:
2090: /*************** function likelione ***********/
2091: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
2092: {
2093: /* This routine should help understanding what is done with
2094: the selection of individuals/waves and
2095: to check the exact contribution to the likelihood.
2096: Plotting could be done.
2097: */
2098: int k;
2099:
2100: if(*globpri !=0){ /* Just counts and sums, no printings */
2101: strcpy(fileresilk,"ilk");
2102: strcat(fileresilk,fileres);
2103: if((ficresilk=fopen(fileresilk,"w"))==NULL) {
2104: printf("Problem with resultfile: %s\n", fileresilk);
2105: fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
2106: }
2107: 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");
2108: fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
2109: /* i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
2110: for(k=1; k<=nlstate; k++)
2111: fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
2112: fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
2113: }
2114:
2115: *fretone=(*funcone)(p);
2116: if(*globpri !=0){
2117: fclose(ficresilk);
2118: fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
2119: fflush(fichtm);
2120: }
2121: return;
2122: }
2123:
2124:
2125: /*********** Maximum Likelihood Estimation ***************/
2126:
2127: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
2128: {
2129: int i,j, iter;
2130: double **xi;
2131: double fret;
2132: double fretone; /* Only one call to likelihood */
2133: /* char filerespow[FILENAMELENGTH];*/
1.162 ! brouard 2134:
! 2135: #ifdef NLOPT
! 2136: int creturn;
! 2137: nlopt_opt opt;
! 2138: /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
! 2139: double *lb;
! 2140: double minf; /* the minimum objective value, upon return */
! 2141: double * p1; /* Shifted parameters from 0 instead of 1 */
! 2142: myfunc_data dinst, *d = &dinst;
! 2143: #endif
! 2144:
! 2145:
1.126 brouard 2146: xi=matrix(1,npar,1,npar);
2147: for (i=1;i<=npar;i++)
2148: for (j=1;j<=npar;j++)
2149: xi[i][j]=(i==j ? 1.0 : 0.0);
2150: printf("Powell\n"); fprintf(ficlog,"Powell\n");
2151: strcpy(filerespow,"pow");
2152: strcat(filerespow,fileres);
2153: if((ficrespow=fopen(filerespow,"w"))==NULL) {
2154: printf("Problem with resultfile: %s\n", filerespow);
2155: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
2156: }
2157: fprintf(ficrespow,"# Powell\n# iter -2*LL");
2158: for (i=1;i<=nlstate;i++)
2159: for(j=1;j<=nlstate+ndeath;j++)
2160: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
2161: fprintf(ficrespow,"\n");
1.162 ! brouard 2162: #ifdef POWELL
1.126 brouard 2163: powell(p,xi,npar,ftol,&iter,&fret,func);
1.162 ! brouard 2164: #endif
1.126 brouard 2165:
1.162 ! brouard 2166: #ifdef NLOPT
! 2167: #ifdef NEWUOA
! 2168: opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
! 2169: #else
! 2170: opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
! 2171: #endif
! 2172: lb=vector(0,npar-1);
! 2173: for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
! 2174: nlopt_set_lower_bounds(opt, lb);
! 2175: nlopt_set_initial_step1(opt, 0.1);
! 2176:
! 2177: p1= (p+1); /* p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
! 2178: d->function = func;
! 2179: printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
! 2180: nlopt_set_min_objective(opt, myfunc, d);
! 2181: nlopt_set_xtol_rel(opt, ftol);
! 2182: if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
! 2183: printf("nlopt failed! %d\n",creturn);
! 2184: }
! 2185: else {
! 2186: printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
! 2187: printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
! 2188: iter=1; /* not equal */
! 2189: }
! 2190: nlopt_destroy(opt);
! 2191: #endif
1.126 brouard 2192: free_matrix(xi,1,npar,1,npar);
2193: fclose(ficrespow);
1.162 ! brouard 2194: printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
! 2195: fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
! 2196: fprintf(ficres,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126 brouard 2197:
2198: }
2199:
2200: /**** Computes Hessian and covariance matrix ***/
2201: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
2202: {
2203: double **a,**y,*x,pd;
2204: double **hess;
2205: int i, j,jk;
2206: int *indx;
2207:
2208: double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
2209: double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
2210: void lubksb(double **a, int npar, int *indx, double b[]) ;
2211: void ludcmp(double **a, int npar, int *indx, double *d) ;
2212: double gompertz(double p[]);
2213: hess=matrix(1,npar,1,npar);
2214:
2215: printf("\nCalculation of the hessian matrix. Wait...\n");
2216: fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
2217: for (i=1;i<=npar;i++){
2218: printf("%d",i);fflush(stdout);
2219: fprintf(ficlog,"%d",i);fflush(ficlog);
2220:
2221: hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
2222:
2223: /* printf(" %f ",p[i]);
2224: printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
2225: }
2226:
2227: for (i=1;i<=npar;i++) {
2228: for (j=1;j<=npar;j++) {
2229: if (j>i) {
2230: printf(".%d%d",i,j);fflush(stdout);
2231: fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
2232: hess[i][j]=hessij(p,delti,i,j,func,npar);
2233:
2234: hess[j][i]=hess[i][j];
2235: /*printf(" %lf ",hess[i][j]);*/
2236: }
2237: }
2238: }
2239: printf("\n");
2240: fprintf(ficlog,"\n");
2241:
2242: printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
2243: fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
2244:
2245: a=matrix(1,npar,1,npar);
2246: y=matrix(1,npar,1,npar);
2247: x=vector(1,npar);
2248: indx=ivector(1,npar);
2249: for (i=1;i<=npar;i++)
2250: for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
2251: ludcmp(a,npar,indx,&pd);
2252:
2253: for (j=1;j<=npar;j++) {
2254: for (i=1;i<=npar;i++) x[i]=0;
2255: x[j]=1;
2256: lubksb(a,npar,indx,x);
2257: for (i=1;i<=npar;i++){
2258: matcov[i][j]=x[i];
2259: }
2260: }
2261:
2262: printf("\n#Hessian matrix#\n");
2263: fprintf(ficlog,"\n#Hessian matrix#\n");
2264: for (i=1;i<=npar;i++) {
2265: for (j=1;j<=npar;j++) {
2266: printf("%.3e ",hess[i][j]);
2267: fprintf(ficlog,"%.3e ",hess[i][j]);
2268: }
2269: printf("\n");
2270: fprintf(ficlog,"\n");
2271: }
2272:
2273: /* Recompute Inverse */
2274: for (i=1;i<=npar;i++)
2275: for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
2276: ludcmp(a,npar,indx,&pd);
2277:
2278: /* printf("\n#Hessian matrix recomputed#\n");
2279:
2280: for (j=1;j<=npar;j++) {
2281: for (i=1;i<=npar;i++) x[i]=0;
2282: x[j]=1;
2283: lubksb(a,npar,indx,x);
2284: for (i=1;i<=npar;i++){
2285: y[i][j]=x[i];
2286: printf("%.3e ",y[i][j]);
2287: fprintf(ficlog,"%.3e ",y[i][j]);
2288: }
2289: printf("\n");
2290: fprintf(ficlog,"\n");
2291: }
2292: */
2293:
2294: free_matrix(a,1,npar,1,npar);
2295: free_matrix(y,1,npar,1,npar);
2296: free_vector(x,1,npar);
2297: free_ivector(indx,1,npar);
2298: free_matrix(hess,1,npar,1,npar);
2299:
2300:
2301: }
2302:
2303: /*************** hessian matrix ****************/
2304: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
2305: {
2306: int i;
2307: int l=1, lmax=20;
2308: double k1,k2;
1.132 brouard 2309: double p2[MAXPARM+1]; /* identical to x */
1.126 brouard 2310: double res;
2311: double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
2312: double fx;
2313: int k=0,kmax=10;
2314: double l1;
2315:
2316: fx=func(x);
2317: for (i=1;i<=npar;i++) p2[i]=x[i];
1.145 brouard 2318: for(l=0 ; l <=lmax; l++){ /* Enlarging the zone around the Maximum */
1.126 brouard 2319: l1=pow(10,l);
2320: delts=delt;
2321: for(k=1 ; k <kmax; k=k+1){
2322: delt = delta*(l1*k);
2323: p2[theta]=x[theta] +delt;
1.145 brouard 2324: k1=func(p2)-fx; /* Might be negative if too close to the theoretical maximum */
1.126 brouard 2325: p2[theta]=x[theta]-delt;
2326: k2=func(p2)-fx;
2327: /*res= (k1-2.0*fx+k2)/delt/delt; */
2328: res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
2329:
1.132 brouard 2330: #ifdef DEBUGHESS
1.126 brouard 2331: 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);
2332: 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);
2333: #endif
2334: /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
2335: if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
2336: k=kmax;
2337: }
2338: else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
2339: k=kmax; l=lmax*10.;
2340: }
2341: else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
2342: delts=delt;
2343: }
2344: }
2345: }
2346: delti[theta]=delts;
2347: return res;
2348:
2349: }
2350:
2351: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
2352: {
2353: int i;
2354: int l=1, l1, lmax=20;
2355: double k1,k2,k3,k4,res,fx;
1.132 brouard 2356: double p2[MAXPARM+1];
1.126 brouard 2357: int k;
2358:
2359: fx=func(x);
2360: for (k=1; k<=2; k++) {
2361: for (i=1;i<=npar;i++) p2[i]=x[i];
2362: p2[thetai]=x[thetai]+delti[thetai]/k;
2363: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2364: k1=func(p2)-fx;
2365:
2366: p2[thetai]=x[thetai]+delti[thetai]/k;
2367: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2368: k2=func(p2)-fx;
2369:
2370: p2[thetai]=x[thetai]-delti[thetai]/k;
2371: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2372: k3=func(p2)-fx;
2373:
2374: p2[thetai]=x[thetai]-delti[thetai]/k;
2375: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2376: k4=func(p2)-fx;
2377: res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
2378: #ifdef DEBUG
2379: 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);
2380: 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);
2381: #endif
2382: }
2383: return res;
2384: }
2385:
2386: /************** Inverse of matrix **************/
2387: void ludcmp(double **a, int n, int *indx, double *d)
2388: {
2389: int i,imax,j,k;
2390: double big,dum,sum,temp;
2391: double *vv;
2392:
2393: vv=vector(1,n);
2394: *d=1.0;
2395: for (i=1;i<=n;i++) {
2396: big=0.0;
2397: for (j=1;j<=n;j++)
2398: if ((temp=fabs(a[i][j])) > big) big=temp;
2399: if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
2400: vv[i]=1.0/big;
2401: }
2402: for (j=1;j<=n;j++) {
2403: for (i=1;i<j;i++) {
2404: sum=a[i][j];
2405: for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
2406: a[i][j]=sum;
2407: }
2408: big=0.0;
2409: for (i=j;i<=n;i++) {
2410: sum=a[i][j];
2411: for (k=1;k<j;k++)
2412: sum -= a[i][k]*a[k][j];
2413: a[i][j]=sum;
2414: if ( (dum=vv[i]*fabs(sum)) >= big) {
2415: big=dum;
2416: imax=i;
2417: }
2418: }
2419: if (j != imax) {
2420: for (k=1;k<=n;k++) {
2421: dum=a[imax][k];
2422: a[imax][k]=a[j][k];
2423: a[j][k]=dum;
2424: }
2425: *d = -(*d);
2426: vv[imax]=vv[j];
2427: }
2428: indx[j]=imax;
2429: if (a[j][j] == 0.0) a[j][j]=TINY;
2430: if (j != n) {
2431: dum=1.0/(a[j][j]);
2432: for (i=j+1;i<=n;i++) a[i][j] *= dum;
2433: }
2434: }
2435: free_vector(vv,1,n); /* Doesn't work */
2436: ;
2437: }
2438:
2439: void lubksb(double **a, int n, int *indx, double b[])
2440: {
2441: int i,ii=0,ip,j;
2442: double sum;
2443:
2444: for (i=1;i<=n;i++) {
2445: ip=indx[i];
2446: sum=b[ip];
2447: b[ip]=b[i];
2448: if (ii)
2449: for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
2450: else if (sum) ii=i;
2451: b[i]=sum;
2452: }
2453: for (i=n;i>=1;i--) {
2454: sum=b[i];
2455: for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
2456: b[i]=sum/a[i][i];
2457: }
2458: }
2459:
2460: void pstamp(FILE *fichier)
2461: {
2462: fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
2463: }
2464:
2465: /************ Frequencies ********************/
2466: 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[])
2467: { /* Some frequencies */
2468:
1.130 brouard 2469: int i, m, jk, k1,i1, j1, bool, z1,j;
1.126 brouard 2470: int first;
2471: double ***freq; /* Frequencies */
2472: double *pp, **prop;
2473: double pos,posprop, k2, dateintsum=0,k2cpt=0;
2474: char fileresp[FILENAMELENGTH];
2475:
2476: pp=vector(1,nlstate);
2477: prop=matrix(1,nlstate,iagemin,iagemax+3);
2478: strcpy(fileresp,"p");
2479: strcat(fileresp,fileres);
2480: if((ficresp=fopen(fileresp,"w"))==NULL) {
2481: printf("Problem with prevalence resultfile: %s\n", fileresp);
2482: fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
2483: exit(0);
2484: }
2485: freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
2486: j1=0;
2487:
2488: j=cptcoveff;
2489: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2490:
2491: first=1;
2492:
1.145 brouard 2493: /* for(k1=1; k1<=j ; k1++){ /* Loop on covariates */
2494: /* for(i1=1; i1<=ncodemax[k1];i1++){ /* Now it is 2 */
2495: /* j1++;
2496: */
2497: for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126 brouard 2498: /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
2499: scanf("%d", i);*/
2500: for (i=-5; i<=nlstate+ndeath; i++)
2501: for (jk=-5; jk<=nlstate+ndeath; jk++)
2502: for(m=iagemin; m <= iagemax+3; m++)
2503: freq[i][jk][m]=0;
1.143 brouard 2504:
2505: for (i=1; i<=nlstate; i++)
2506: for(m=iagemin; m <= iagemax+3; m++)
2507: prop[i][m]=0;
1.126 brouard 2508:
2509: dateintsum=0;
2510: k2cpt=0;
2511: for (i=1; i<=imx; i++) {
2512: bool=1;
1.144 brouard 2513: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
2514: for (z1=1; z1<=cptcoveff; z1++)
2515: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
1.145 brouard 2516: /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144 brouard 2517: bool=0;
1.145 brouard 2518: /* 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",
2519: bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
2520: j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
1.144 brouard 2521: /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
2522: }
1.126 brouard 2523: }
1.144 brouard 2524:
1.126 brouard 2525: if (bool==1){
2526: for(m=firstpass; m<=lastpass; m++){
2527: k2=anint[m][i]+(mint[m][i]/12.);
2528: /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
2529: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2530: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2531: if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
2532: if (m<lastpass) {
2533: freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
2534: freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
2535: }
2536:
2537: if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
2538: dateintsum=dateintsum+k2;
2539: k2cpt++;
2540: }
2541: /*}*/
2542: }
2543: }
1.145 brouard 2544: } /* end i */
1.126 brouard 2545:
2546: /* fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
2547: pstamp(ficresp);
2548: if (cptcovn>0) {
2549: fprintf(ficresp, "\n#********** Variable ");
2550: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2551: fprintf(ficresp, "**********\n#");
1.143 brouard 2552: fprintf(ficlog, "\n#********** Variable ");
2553: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2554: fprintf(ficlog, "**********\n#");
1.126 brouard 2555: }
2556: for(i=1; i<=nlstate;i++)
2557: fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
2558: fprintf(ficresp, "\n");
2559:
2560: for(i=iagemin; i <= iagemax+3; i++){
2561: if(i==iagemax+3){
2562: fprintf(ficlog,"Total");
2563: }else{
2564: if(first==1){
2565: first=0;
2566: printf("See log file for details...\n");
2567: }
2568: fprintf(ficlog,"Age %d", i);
2569: }
2570: for(jk=1; jk <=nlstate ; jk++){
2571: for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
2572: pp[jk] += freq[jk][m][i];
2573: }
2574: for(jk=1; jk <=nlstate ; jk++){
2575: for(m=-1, pos=0; m <=0 ; m++)
2576: pos += freq[jk][m][i];
2577: if(pp[jk]>=1.e-10){
2578: if(first==1){
1.132 brouard 2579: printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126 brouard 2580: }
2581: fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
2582: }else{
2583: if(first==1)
2584: printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2585: fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2586: }
2587: }
2588:
2589: for(jk=1; jk <=nlstate ; jk++){
2590: for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
2591: pp[jk] += freq[jk][m][i];
2592: }
2593: for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
2594: pos += pp[jk];
2595: posprop += prop[jk][i];
2596: }
2597: for(jk=1; jk <=nlstate ; jk++){
2598: if(pos>=1.e-5){
2599: if(first==1)
2600: printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2601: fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2602: }else{
2603: if(first==1)
2604: printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2605: fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2606: }
2607: if( i <= iagemax){
2608: if(pos>=1.e-5){
2609: fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
2610: /*probs[i][jk][j1]= pp[jk]/pos;*/
2611: /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
2612: }
2613: else
2614: fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
2615: }
2616: }
2617:
2618: for(jk=-1; jk <=nlstate+ndeath; jk++)
2619: for(m=-1; m <=nlstate+ndeath; m++)
2620: if(freq[jk][m][i] !=0 ) {
2621: if(first==1)
2622: printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
2623: fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
2624: }
2625: if(i <= iagemax)
2626: fprintf(ficresp,"\n");
2627: if(first==1)
2628: printf("Others in log...\n");
2629: fprintf(ficlog,"\n");
2630: }
1.145 brouard 2631: /*}*/
1.126 brouard 2632: }
2633: dateintmean=dateintsum/k2cpt;
2634:
2635: fclose(ficresp);
2636: free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
2637: free_vector(pp,1,nlstate);
2638: free_matrix(prop,1,nlstate,iagemin, iagemax+3);
2639: /* End of Freq */
2640: }
2641:
2642: /************ Prevalence ********************/
2643: 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)
2644: {
2645: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
2646: in each health status at the date of interview (if between dateprev1 and dateprev2).
2647: We still use firstpass and lastpass as another selection.
2648: */
2649:
1.130 brouard 2650: int i, m, jk, k1, i1, j1, bool, z1,j;
1.126 brouard 2651: double ***freq; /* Frequencies */
2652: double *pp, **prop;
2653: double pos,posprop;
2654: double y2; /* in fractional years */
2655: int iagemin, iagemax;
1.145 brouard 2656: int first; /** to stop verbosity which is redirected to log file */
1.126 brouard 2657:
2658: iagemin= (int) agemin;
2659: iagemax= (int) agemax;
2660: /*pp=vector(1,nlstate);*/
2661: prop=matrix(1,nlstate,iagemin,iagemax+3);
2662: /* freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
2663: j1=0;
2664:
1.145 brouard 2665: /*j=cptcoveff;*/
1.126 brouard 2666: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2667:
1.145 brouard 2668: first=1;
2669: for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
2670: /*for(i1=1; i1<=ncodemax[k1];i1++){
2671: j1++;*/
1.126 brouard 2672:
2673: for (i=1; i<=nlstate; i++)
2674: for(m=iagemin; m <= iagemax+3; m++)
2675: prop[i][m]=0.0;
2676:
2677: for (i=1; i<=imx; i++) { /* Each individual */
2678: bool=1;
2679: if (cptcovn>0) {
2680: for (z1=1; z1<=cptcoveff; z1++)
2681: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
2682: bool=0;
2683: }
2684: if (bool==1) {
2685: for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
2686: y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
2687: if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
2688: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2689: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2690: 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);
2691: if (s[m][i]>0 && s[m][i]<=nlstate) {
2692: /*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]]);*/
2693: prop[s[m][i]][(int)agev[m][i]] += weight[i];
2694: prop[s[m][i]][iagemax+3] += weight[i];
2695: }
2696: }
2697: } /* end selection of waves */
2698: }
2699: }
2700: for(i=iagemin; i <= iagemax+3; i++){
2701: for(jk=1,posprop=0; jk <=nlstate ; jk++) {
2702: posprop += prop[jk][i];
2703: }
1.145 brouard 2704:
1.126 brouard 2705: for(jk=1; jk <=nlstate ; jk++){
2706: if( i <= iagemax){
2707: if(posprop>=1.e-5){
2708: probs[i][jk][j1]= prop[jk][i]/posprop;
1.145 brouard 2709: } else{
2710: if(first==1){
2711: first=0;
2712: 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]);
2713: }
2714: }
1.126 brouard 2715: }
2716: }/* end jk */
2717: }/* end i */
1.145 brouard 2718: /*} *//* end i1 */
2719: } /* end j1 */
1.126 brouard 2720:
2721: /* free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
2722: /*free_vector(pp,1,nlstate);*/
2723: free_matrix(prop,1,nlstate, iagemin,iagemax+3);
2724: } /* End of prevalence */
2725:
2726: /************* Waves Concatenation ***************/
2727:
2728: 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)
2729: {
2730: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
2731: Death is a valid wave (if date is known).
2732: mw[mi][i] is the mi (mi=1 to wav[i]) effective wave of individual i
2733: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
2734: and mw[mi+1][i]. dh depends on stepm.
2735: */
2736:
2737: int i, mi, m;
2738: /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
2739: double sum=0., jmean=0.;*/
2740: int first;
2741: int j, k=0,jk, ju, jl;
2742: double sum=0.;
2743: first=0;
2744: jmin=1e+5;
2745: jmax=-1;
2746: jmean=0.;
2747: for(i=1; i<=imx; i++){
2748: mi=0;
2749: m=firstpass;
2750: while(s[m][i] <= nlstate){
2751: if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
2752: mw[++mi][i]=m;
2753: if(m >=lastpass)
2754: break;
2755: else
2756: m++;
2757: }/* end while */
2758: if (s[m][i] > nlstate){
2759: mi++; /* Death is another wave */
2760: /* if(mi==0) never been interviewed correctly before death */
2761: /* Only death is a correct wave */
2762: mw[mi][i]=m;
2763: }
2764:
2765: wav[i]=mi;
2766: if(mi==0){
2767: nbwarn++;
2768: if(first==0){
2769: printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
2770: first=1;
2771: }
2772: if(first==1){
2773: fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
2774: }
2775: } /* end mi==0 */
2776: } /* End individuals */
2777:
2778: for(i=1; i<=imx; i++){
2779: for(mi=1; mi<wav[i];mi++){
2780: if (stepm <=0)
2781: dh[mi][i]=1;
2782: else{
2783: if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
2784: if (agedc[i] < 2*AGESUP) {
2785: j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
2786: if(j==0) j=1; /* Survives at least one month after exam */
2787: else if(j<0){
2788: nberr++;
2789: 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]);
2790: j=1; /* Temporary Dangerous patch */
2791: 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);
2792: 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]);
2793: 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);
2794: }
2795: k=k+1;
2796: if (j >= jmax){
2797: jmax=j;
2798: ijmax=i;
2799: }
2800: if (j <= jmin){
2801: jmin=j;
2802: ijmin=i;
2803: }
2804: sum=sum+j;
2805: /*if (j<0) printf("j=%d num=%d \n",j,i);*/
2806: /* printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
2807: }
2808: }
2809: else{
2810: j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
2811: /* 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]); */
2812:
2813: k=k+1;
2814: if (j >= jmax) {
2815: jmax=j;
2816: ijmax=i;
2817: }
2818: else if (j <= jmin){
2819: jmin=j;
2820: ijmin=i;
2821: }
2822: /* if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
2823: /*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]);*/
2824: if(j<0){
2825: nberr++;
2826: 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]);
2827: 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]);
2828: }
2829: sum=sum+j;
2830: }
2831: jk= j/stepm;
2832: jl= j -jk*stepm;
2833: ju= j -(jk+1)*stepm;
2834: if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
2835: if(jl==0){
2836: dh[mi][i]=jk;
2837: bh[mi][i]=0;
2838: }else{ /* We want a negative bias in order to only have interpolation ie
1.136 brouard 2839: * to avoid the price of an extra matrix product in likelihood */
1.126 brouard 2840: dh[mi][i]=jk+1;
2841: bh[mi][i]=ju;
2842: }
2843: }else{
2844: if(jl <= -ju){
2845: dh[mi][i]=jk;
2846: bh[mi][i]=jl; /* bias is positive if real duration
2847: * is higher than the multiple of stepm and negative otherwise.
2848: */
2849: }
2850: else{
2851: dh[mi][i]=jk+1;
2852: bh[mi][i]=ju;
2853: }
2854: if(dh[mi][i]==0){
2855: dh[mi][i]=1; /* At least one step */
2856: bh[mi][i]=ju; /* At least one step */
2857: /* 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);*/
2858: }
2859: } /* end if mle */
2860: }
2861: } /* end wave */
2862: }
2863: jmean=sum/k;
2864: 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 2865: 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 2866: }
2867:
2868: /*********** Tricode ****************************/
1.145 brouard 2869: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126 brouard 2870: {
1.144 brouard 2871: /**< Uses cptcovn+2*cptcovprod as the number of covariates */
2872: /* Tvar[i]=atoi(stre); find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1
2873: /* Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145 brouard 2874: * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
2875: /* nbcode[Tvar[j]][1]=
1.144 brouard 2876: */
1.130 brouard 2877:
1.145 brouard 2878: int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136 brouard 2879: int modmaxcovj=0; /* Modality max of covariates j */
1.145 brouard 2880: int cptcode=0; /* Modality max of covariates j */
2881: int modmincovj=0; /* Modality min of covariates j */
2882:
2883:
1.126 brouard 2884: cptcoveff=0;
2885:
1.145 brouard 2886: for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.144 brouard 2887: for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126 brouard 2888:
1.145 brouard 2889: /* Loop on covariates without age and products */
2890: for (j=1; j<=(cptcovs); j++) { /* model V1 + V2*age+ V3 + V3*V4 : V1 + V3 = 2 only */
2891: for (i=1; i<=imx; i++) { /* Lopp on individuals: reads the data file to get the maximum value of the
1.136 brouard 2892: modality of this covariate Vj*/
1.145 brouard 2893: ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
2894: * If product of Vn*Vm, still boolean *:
2895: * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
2896: * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0 */
2897: /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136 brouard 2898: modality of the nth covariate of individual i. */
1.145 brouard 2899: if (ij > modmaxcovj)
2900: modmaxcovj=ij;
2901: else if (ij < modmincovj)
2902: modmincovj=ij;
2903: if ((ij < -1) && (ij > NCOVMAX)){
2904: printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
2905: exit(1);
2906: }else
1.136 brouard 2907: Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145 brouard 2908: /* If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126 brouard 2909: /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136 brouard 2910: /* getting the maximum value of the modality of the covariate
2911: (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
2912: female is 1, then modmaxcovj=1.*/
1.126 brouard 2913: }
1.145 brouard 2914: printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
2915: cptcode=modmaxcovj;
1.137 brouard 2916: /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145 brouard 2917: /*for (i=0; i<=cptcode; i++) {*/
2918: for (i=modmincovj; i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
2919: printf("Frequencies of covariates %d V%d %d\n", j, Tvar[j], Ndum[i]);
2920: if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
2921: ncodemax[j]++; /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
2922: }
2923: /* In fact ncodemax[j]=2 (dichotom. variables only) but it could be more for
2924: historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131 brouard 2925: } /* Ndum[-1] number of undefined modalities */
1.126 brouard 2926:
1.136 brouard 2927: /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.145 brouard 2928: /* For covariate j, modalities could be 1, 2, 3, 4. If Ndum[2]=0 ncodemax[j] is not 4 but 3 */
2929: /* If Ndum[3}= 635; Ndum[4]=0; Ndum[5]=0; Ndum[6]=27; Ndum[7]=125;
2930: modmincovj=3; modmaxcovj = 7;
2931: There are only 3 modalities non empty (or 2 if 27 is too few) : ncodemax[j]=3;
2932: which will be coded 0, 1, 2 which in binary on 3-1 digits are 0=00 1=01, 2=10; defining two dummy
2933: variables V1_1 and V1_2.
2934: nbcode[Tvar[j]][ij]=k;
2935: nbcode[Tvar[j]][1]=0;
2936: nbcode[Tvar[j]][2]=1;
2937: nbcode[Tvar[j]][3]=2;
2938: */
2939: ij=1; /* ij is similar to i but can jumps over null modalities */
2940: for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
2941: for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
2942: /*recode from 0 */
1.131 brouard 2943: if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
2944: nbcode[Tvar[j]][ij]=k; /* stores the modality in an array nbcode.
2945: k is a modality. If we have model=V1+V1*sex
2946: then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
1.126 brouard 2947: ij++;
2948: }
2949: if (ij > ncodemax[j]) break;
1.137 brouard 2950: } /* end of loop on */
2951: } /* end of loop on modality */
2952: } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/
2953:
1.145 brouard 2954: for (k=-1; k< maxncov; k++) Ndum[k]=0;
1.137 brouard 2955:
1.145 brouard 2956: for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */
2957: /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
2958: ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
2959: Ndum[ij]++;
2960: }
1.126 brouard 2961:
2962: ij=1;
1.145 brouard 2963: for (i=0; i<= maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
2964: /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126 brouard 2965: if((Ndum[i]!=0) && (i<=ncovcol)){
1.145 brouard 2966: /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
2967: Tvaraff[ij]=i; /*For printing (unclear) */
1.126 brouard 2968: ij++;
1.145 brouard 2969: }else
2970: Tvaraff[ij]=0;
1.126 brouard 2971: }
1.131 brouard 2972: ij--;
1.144 brouard 2973: cptcoveff=ij; /*Number of total covariates*/
1.145 brouard 2974:
1.126 brouard 2975: }
2976:
1.145 brouard 2977:
1.126 brouard 2978: /*********** Health Expectancies ****************/
2979:
1.127 brouard 2980: 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 2981:
2982: {
2983: /* Health expectancies, no variances */
2984: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2;
2985: int nhstepma, nstepma; /* Decreasing with age */
2986: double age, agelim, hf;
2987: double ***p3mat;
2988: double eip;
2989:
2990: pstamp(ficreseij);
2991: fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
2992: fprintf(ficreseij,"# Age");
2993: for(i=1; i<=nlstate;i++){
2994: for(j=1; j<=nlstate;j++){
2995: fprintf(ficreseij," e%1d%1d ",i,j);
2996: }
2997: fprintf(ficreseij," e%1d. ",i);
2998: }
2999: fprintf(ficreseij,"\n");
3000:
3001:
3002: if(estepm < stepm){
3003: printf ("Problem %d lower than %d\n",estepm, stepm);
3004: }
3005: else hstepm=estepm;
3006: /* We compute the life expectancy from trapezoids spaced every estepm months
3007: * This is mainly to measure the difference between two models: for example
3008: * if stepm=24 months pijx are given only every 2 years and by summing them
3009: * we are calculating an estimate of the Life Expectancy assuming a linear
3010: * progression in between and thus overestimating or underestimating according
3011: * to the curvature of the survival function. If, for the same date, we
3012: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3013: * to compare the new estimate of Life expectancy with the same linear
3014: * hypothesis. A more precise result, taking into account a more precise
3015: * curvature will be obtained if estepm is as small as stepm. */
3016:
3017: /* For example we decided to compute the life expectancy with the smallest unit */
3018: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3019: nhstepm is the number of hstepm from age to agelim
3020: nstepm is the number of stepm from age to agelin.
3021: Look at hpijx to understand the reason of that which relies in memory size
3022: and note for a fixed period like estepm months */
3023: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3024: survival function given by stepm (the optimization length). Unfortunately it
3025: means that if the survival funtion is printed only each two years of age and if
3026: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3027: results. So we changed our mind and took the option of the best precision.
3028: */
3029: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3030:
3031: agelim=AGESUP;
3032: /* If stepm=6 months */
3033: /* Computed by stepm unit matrices, product of hstepm matrices, stored
3034: in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
3035:
3036: /* nhstepm age range expressed in number of stepm */
3037: nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3038: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3039: /* if (stepm >= YEARM) hstepm=1;*/
3040: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3041: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3042:
3043: for (age=bage; age<=fage; age ++){
3044: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3045: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3046: /* if (stepm >= YEARM) hstepm=1;*/
3047: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3048:
3049: /* If stepm=6 months */
3050: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3051: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3052:
3053: hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3054:
3055: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3056:
3057: printf("%d|",(int)age);fflush(stdout);
3058: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3059:
3060: /* Computing expectancies */
3061: for(i=1; i<=nlstate;i++)
3062: for(j=1; j<=nlstate;j++)
3063: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3064: eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
3065:
3066: /* 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]);*/
3067:
3068: }
3069:
3070: fprintf(ficreseij,"%3.0f",age );
3071: for(i=1; i<=nlstate;i++){
3072: eip=0;
3073: for(j=1; j<=nlstate;j++){
3074: eip +=eij[i][j][(int)age];
3075: fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
3076: }
3077: fprintf(ficreseij,"%9.4f", eip );
3078: }
3079: fprintf(ficreseij,"\n");
3080:
3081: }
3082: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3083: printf("\n");
3084: fprintf(ficlog,"\n");
3085:
3086: }
3087:
1.127 brouard 3088: 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 3089:
3090: {
3091: /* Covariances of health expectancies eij and of total life expectancies according
3092: to initial status i, ei. .
3093: */
3094: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
3095: int nhstepma, nstepma; /* Decreasing with age */
3096: double age, agelim, hf;
3097: double ***p3matp, ***p3matm, ***varhe;
3098: double **dnewm,**doldm;
3099: double *xp, *xm;
3100: double **gp, **gm;
3101: double ***gradg, ***trgradg;
3102: int theta;
3103:
3104: double eip, vip;
3105:
3106: varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
3107: xp=vector(1,npar);
3108: xm=vector(1,npar);
3109: dnewm=matrix(1,nlstate*nlstate,1,npar);
3110: doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
3111:
3112: pstamp(ficresstdeij);
3113: fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
3114: fprintf(ficresstdeij,"# Age");
3115: for(i=1; i<=nlstate;i++){
3116: for(j=1; j<=nlstate;j++)
3117: fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
3118: fprintf(ficresstdeij," e%1d. ",i);
3119: }
3120: fprintf(ficresstdeij,"\n");
3121:
3122: pstamp(ficrescveij);
3123: fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
3124: fprintf(ficrescveij,"# Age");
3125: for(i=1; i<=nlstate;i++)
3126: for(j=1; j<=nlstate;j++){
3127: cptj= (j-1)*nlstate+i;
3128: for(i2=1; i2<=nlstate;i2++)
3129: for(j2=1; j2<=nlstate;j2++){
3130: cptj2= (j2-1)*nlstate+i2;
3131: if(cptj2 <= cptj)
3132: fprintf(ficrescveij," %1d%1d,%1d%1d",i,j,i2,j2);
3133: }
3134: }
3135: fprintf(ficrescveij,"\n");
3136:
3137: if(estepm < stepm){
3138: printf ("Problem %d lower than %d\n",estepm, stepm);
3139: }
3140: else hstepm=estepm;
3141: /* We compute the life expectancy from trapezoids spaced every estepm months
3142: * This is mainly to measure the difference between two models: for example
3143: * if stepm=24 months pijx are given only every 2 years and by summing them
3144: * we are calculating an estimate of the Life Expectancy assuming a linear
3145: * progression in between and thus overestimating or underestimating according
3146: * to the curvature of the survival function. If, for the same date, we
3147: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3148: * to compare the new estimate of Life expectancy with the same linear
3149: * hypothesis. A more precise result, taking into account a more precise
3150: * curvature will be obtained if estepm is as small as stepm. */
3151:
3152: /* For example we decided to compute the life expectancy with the smallest unit */
3153: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3154: nhstepm is the number of hstepm from age to agelim
3155: nstepm is the number of stepm from age to agelin.
3156: Look at hpijx to understand the reason of that which relies in memory size
3157: and note for a fixed period like estepm months */
3158: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3159: survival function given by stepm (the optimization length). Unfortunately it
3160: means that if the survival funtion is printed only each two years of age and if
3161: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3162: results. So we changed our mind and took the option of the best precision.
3163: */
3164: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3165:
3166: /* If stepm=6 months */
3167: /* nhstepm age range expressed in number of stepm */
3168: agelim=AGESUP;
3169: nstepm=(int) rint((agelim-bage)*YEARM/stepm);
3170: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3171: /* if (stepm >= YEARM) hstepm=1;*/
3172: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3173:
3174: p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3175: p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3176: gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
3177: trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
3178: gp=matrix(0,nhstepm,1,nlstate*nlstate);
3179: gm=matrix(0,nhstepm,1,nlstate*nlstate);
3180:
3181: for (age=bage; age<=fage; age ++){
3182: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3183: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3184: /* if (stepm >= YEARM) hstepm=1;*/
3185: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3186:
3187: /* If stepm=6 months */
3188: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3189: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3190:
3191: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3192:
3193: /* Computing Variances of health expectancies */
3194: /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
3195: decrease memory allocation */
3196: for(theta=1; theta <=npar; theta++){
3197: for(i=1; i<=npar; i++){
3198: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3199: xm[i] = x[i] - (i==theta ?delti[theta]:0);
3200: }
3201: hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);
3202: hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);
3203:
3204: for(j=1; j<= nlstate; j++){
3205: for(i=1; i<=nlstate; i++){
3206: for(h=0; h<=nhstepm-1; h++){
3207: gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
3208: gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
3209: }
3210: }
3211: }
3212:
3213: for(ij=1; ij<= nlstate*nlstate; ij++)
3214: for(h=0; h<=nhstepm-1; h++){
3215: gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
3216: }
3217: }/* End theta */
3218:
3219:
3220: for(h=0; h<=nhstepm-1; h++)
3221: for(j=1; j<=nlstate*nlstate;j++)
3222: for(theta=1; theta <=npar; theta++)
3223: trgradg[h][j][theta]=gradg[h][theta][j];
3224:
3225:
3226: for(ij=1;ij<=nlstate*nlstate;ij++)
3227: for(ji=1;ji<=nlstate*nlstate;ji++)
3228: varhe[ij][ji][(int)age] =0.;
3229:
3230: printf("%d|",(int)age);fflush(stdout);
3231: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3232: for(h=0;h<=nhstepm-1;h++){
3233: for(k=0;k<=nhstepm-1;k++){
3234: matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
3235: matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
3236: for(ij=1;ij<=nlstate*nlstate;ij++)
3237: for(ji=1;ji<=nlstate*nlstate;ji++)
3238: varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
3239: }
3240: }
3241:
3242: /* Computing expectancies */
3243: hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3244: for(i=1; i<=nlstate;i++)
3245: for(j=1; j<=nlstate;j++)
3246: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3247: eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
3248:
3249: /* 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]);*/
3250:
3251: }
3252:
3253: fprintf(ficresstdeij,"%3.0f",age );
3254: for(i=1; i<=nlstate;i++){
3255: eip=0.;
3256: vip=0.;
3257: for(j=1; j<=nlstate;j++){
3258: eip += eij[i][j][(int)age];
3259: for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
3260: vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
3261: fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
3262: }
3263: fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
3264: }
3265: fprintf(ficresstdeij,"\n");
3266:
3267: fprintf(ficrescveij,"%3.0f",age );
3268: for(i=1; i<=nlstate;i++)
3269: for(j=1; j<=nlstate;j++){
3270: cptj= (j-1)*nlstate+i;
3271: for(i2=1; i2<=nlstate;i2++)
3272: for(j2=1; j2<=nlstate;j2++){
3273: cptj2= (j2-1)*nlstate+i2;
3274: if(cptj2 <= cptj)
3275: fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
3276: }
3277: }
3278: fprintf(ficrescveij,"\n");
3279:
3280: }
3281: free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
3282: free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
3283: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
3284: free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
3285: free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3286: free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3287: printf("\n");
3288: fprintf(ficlog,"\n");
3289:
3290: free_vector(xm,1,npar);
3291: free_vector(xp,1,npar);
3292: free_matrix(dnewm,1,nlstate*nlstate,1,npar);
3293: free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
3294: free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
3295: }
3296:
3297: /************ Variance ******************/
3298: 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[])
3299: {
3300: /* Variance of health expectancies */
3301: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
3302: /* double **newm;*/
3303: double **dnewm,**doldm;
3304: double **dnewmp,**doldmp;
3305: int i, j, nhstepm, hstepm, h, nstepm ;
3306: int k, cptcode;
3307: double *xp;
3308: double **gp, **gm; /* for var eij */
3309: double ***gradg, ***trgradg; /*for var eij */
3310: double **gradgp, **trgradgp; /* for var p point j */
3311: double *gpp, *gmp; /* for var p point j */
3312: double **varppt; /* for var p point j nlstate to nlstate+ndeath */
3313: double ***p3mat;
3314: double age,agelim, hf;
3315: double ***mobaverage;
3316: int theta;
3317: char digit[4];
3318: char digitp[25];
3319:
3320: char fileresprobmorprev[FILENAMELENGTH];
3321:
3322: if(popbased==1){
3323: if(mobilav!=0)
3324: strcpy(digitp,"-populbased-mobilav-");
3325: else strcpy(digitp,"-populbased-nomobil-");
3326: }
3327: else
3328: strcpy(digitp,"-stablbased-");
3329:
3330: if (mobilav!=0) {
3331: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3332: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
3333: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
3334: printf(" Error in movingaverage mobilav=%d\n",mobilav);
3335: }
3336: }
3337:
3338: strcpy(fileresprobmorprev,"prmorprev");
3339: sprintf(digit,"%-d",ij);
3340: /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
3341: strcat(fileresprobmorprev,digit); /* Tvar to be done */
3342: strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
3343: strcat(fileresprobmorprev,fileres);
3344: if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
3345: printf("Problem with resultfile: %s\n", fileresprobmorprev);
3346: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
3347: }
3348: printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3349:
3350: fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3351: pstamp(ficresprobmorprev);
3352: 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);
3353: fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
3354: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3355: fprintf(ficresprobmorprev," p.%-d SE",j);
3356: for(i=1; i<=nlstate;i++)
3357: fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
3358: }
3359: fprintf(ficresprobmorprev,"\n");
3360: fprintf(ficgp,"\n# Routine varevsij");
3361: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
3362: 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");
3363: fprintf(fichtm,"\n<br>%s <br>\n",digitp);
3364: /* } */
3365: varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3366: pstamp(ficresvij);
3367: fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n# (weighted average of eij where weights are ");
3368: if(popbased==1)
1.128 brouard 3369: 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 3370: else
3371: fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
3372: fprintf(ficresvij,"# Age");
3373: for(i=1; i<=nlstate;i++)
3374: for(j=1; j<=nlstate;j++)
3375: fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
3376: fprintf(ficresvij,"\n");
3377:
3378: xp=vector(1,npar);
3379: dnewm=matrix(1,nlstate,1,npar);
3380: doldm=matrix(1,nlstate,1,nlstate);
3381: dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
3382: doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3383:
3384: gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
3385: gpp=vector(nlstate+1,nlstate+ndeath);
3386: gmp=vector(nlstate+1,nlstate+ndeath);
3387: trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
3388:
3389: if(estepm < stepm){
3390: printf ("Problem %d lower than %d\n",estepm, stepm);
3391: }
3392: else hstepm=estepm;
3393: /* For example we decided to compute the life expectancy with the smallest unit */
3394: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3395: nhstepm is the number of hstepm from age to agelim
3396: nstepm is the number of stepm from age to agelin.
1.128 brouard 3397: Look at function hpijx to understand why (it is linked to memory size questions) */
1.126 brouard 3398: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3399: survival function given by stepm (the optimization length). Unfortunately it
3400: means that if the survival funtion is printed every two years of age and if
3401: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3402: results. So we changed our mind and took the option of the best precision.
3403: */
3404: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3405: agelim = AGESUP;
3406: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3407: nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3408: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3409: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3410: gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
3411: gp=matrix(0,nhstepm,1,nlstate);
3412: gm=matrix(0,nhstepm,1,nlstate);
3413:
3414:
3415: for(theta=1; theta <=npar; theta++){
3416: for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
3417: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3418: }
3419: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3420: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3421:
3422: if (popbased==1) {
3423: if(mobilav ==0){
3424: for(i=1; i<=nlstate;i++)
3425: prlim[i][i]=probs[(int)age][i][ij];
3426: }else{ /* mobilav */
3427: for(i=1; i<=nlstate;i++)
3428: prlim[i][i]=mobaverage[(int)age][i][ij];
3429: }
3430: }
3431:
3432: for(j=1; j<= nlstate; j++){
3433: for(h=0; h<=nhstepm; h++){
3434: for(i=1, gp[h][j]=0.;i<=nlstate;i++)
3435: gp[h][j] += prlim[i][i]*p3mat[i][j][h];
3436: }
3437: }
3438: /* This for computing probability of death (h=1 means
3439: computed over hstepm matrices product = hstepm*stepm months)
3440: as a weighted average of prlim.
3441: */
3442: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3443: for(i=1,gpp[j]=0.; i<= nlstate; i++)
3444: gpp[j] += prlim[i][i]*p3mat[i][j][1];
3445: }
3446: /* end probability of death */
3447:
3448: for(i=1; i<=npar; i++) /* Computes gradient x - delta */
3449: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3450: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3451: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3452:
3453: if (popbased==1) {
3454: if(mobilav ==0){
3455: for(i=1; i<=nlstate;i++)
3456: prlim[i][i]=probs[(int)age][i][ij];
3457: }else{ /* mobilav */
3458: for(i=1; i<=nlstate;i++)
3459: prlim[i][i]=mobaverage[(int)age][i][ij];
3460: }
3461: }
3462:
1.128 brouard 3463: for(j=1; j<= nlstate; j++){ /* Sum of wi * eij = e.j */
1.126 brouard 3464: for(h=0; h<=nhstepm; h++){
3465: for(i=1, gm[h][j]=0.;i<=nlstate;i++)
3466: gm[h][j] += prlim[i][i]*p3mat[i][j][h];
3467: }
3468: }
3469: /* This for computing probability of death (h=1 means
3470: computed over hstepm matrices product = hstepm*stepm months)
3471: as a weighted average of prlim.
3472: */
3473: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3474: for(i=1,gmp[j]=0.; i<= nlstate; i++)
3475: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3476: }
3477: /* end probability of death */
3478:
3479: for(j=1; j<= nlstate; j++) /* vareij */
3480: for(h=0; h<=nhstepm; h++){
3481: gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
3482: }
3483:
3484: for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
3485: gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
3486: }
3487:
3488: } /* End theta */
3489:
3490: trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
3491:
3492: for(h=0; h<=nhstepm; h++) /* veij */
3493: for(j=1; j<=nlstate;j++)
3494: for(theta=1; theta <=npar; theta++)
3495: trgradg[h][j][theta]=gradg[h][theta][j];
3496:
3497: for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
3498: for(theta=1; theta <=npar; theta++)
3499: trgradgp[j][theta]=gradgp[theta][j];
3500:
3501:
3502: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3503: for(i=1;i<=nlstate;i++)
3504: for(j=1;j<=nlstate;j++)
3505: vareij[i][j][(int)age] =0.;
3506:
3507: for(h=0;h<=nhstepm;h++){
3508: for(k=0;k<=nhstepm;k++){
3509: matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
3510: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
3511: for(i=1;i<=nlstate;i++)
3512: for(j=1;j<=nlstate;j++)
3513: vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
3514: }
3515: }
3516:
3517: /* pptj */
3518: matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
3519: matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
3520: for(j=nlstate+1;j<=nlstate+ndeath;j++)
3521: for(i=nlstate+1;i<=nlstate+ndeath;i++)
3522: varppt[j][i]=doldmp[j][i];
3523: /* end ppptj */
3524: /* x centered again */
3525: hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);
3526: prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
3527:
3528: if (popbased==1) {
3529: if(mobilav ==0){
3530: for(i=1; i<=nlstate;i++)
3531: prlim[i][i]=probs[(int)age][i][ij];
3532: }else{ /* mobilav */
3533: for(i=1; i<=nlstate;i++)
3534: prlim[i][i]=mobaverage[(int)age][i][ij];
3535: }
3536: }
3537:
3538: /* This for computing probability of death (h=1 means
3539: computed over hstepm (estepm) matrices product = hstepm*stepm months)
3540: as a weighted average of prlim.
3541: */
3542: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3543: for(i=1,gmp[j]=0.;i<= nlstate; i++)
3544: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3545: }
3546: /* end probability of death */
3547:
3548: fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
3549: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3550: fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
3551: for(i=1; i<=nlstate;i++){
3552: fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
3553: }
3554: }
3555: fprintf(ficresprobmorprev,"\n");
3556:
3557: fprintf(ficresvij,"%.0f ",age );
3558: for(i=1; i<=nlstate;i++)
3559: for(j=1; j<=nlstate;j++){
3560: fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
3561: }
3562: fprintf(ficresvij,"\n");
3563: free_matrix(gp,0,nhstepm,1,nlstate);
3564: free_matrix(gm,0,nhstepm,1,nlstate);
3565: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
3566: free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
3567: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3568: } /* End age */
3569: free_vector(gpp,nlstate+1,nlstate+ndeath);
3570: free_vector(gmp,nlstate+1,nlstate+ndeath);
3571: free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
3572: free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.145 brouard 3573: fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
1.126 brouard 3574: /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131 brouard 3575: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.126 brouard 3576: /* fprintf(ficgp,"\n plot \"%s\" u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
3577: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
3578: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145 brouard 3579: fprintf(ficgp,"\n plot \"%s\" u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
3580: fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)) t \"95\%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
3581: fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126 brouard 3582: fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
3583: 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);
3584: /* 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);
3585: */
3586: /* fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
3587: fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
3588:
3589: free_vector(xp,1,npar);
3590: free_matrix(doldm,1,nlstate,1,nlstate);
3591: free_matrix(dnewm,1,nlstate,1,npar);
3592: free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3593: free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
3594: free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3595: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3596: fclose(ficresprobmorprev);
3597: fflush(ficgp);
3598: fflush(fichtm);
3599: } /* end varevsij */
3600:
3601: /************ Variance of prevlim ******************/
3602: 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[])
3603: {
3604: /* Variance of prevalence limit */
3605: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
3606: double **newm;
3607: double **dnewm,**doldm;
3608: int i, j, nhstepm, hstepm;
3609: int k, cptcode;
3610: double *xp;
3611: double *gp, *gm;
3612: double **gradg, **trgradg;
3613: double age,agelim;
3614: int theta;
3615:
3616: pstamp(ficresvpl);
3617: fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
3618: fprintf(ficresvpl,"# Age");
3619: for(i=1; i<=nlstate;i++)
3620: fprintf(ficresvpl," %1d-%1d",i,i);
3621: fprintf(ficresvpl,"\n");
3622:
3623: xp=vector(1,npar);
3624: dnewm=matrix(1,nlstate,1,npar);
3625: doldm=matrix(1,nlstate,1,nlstate);
3626:
3627: hstepm=1*YEARM; /* Every year of age */
3628: hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
3629: agelim = AGESUP;
3630: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3631: nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3632: if (stepm >= YEARM) hstepm=1;
3633: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
3634: gradg=matrix(1,npar,1,nlstate);
3635: gp=vector(1,nlstate);
3636: gm=vector(1,nlstate);
3637:
3638: for(theta=1; theta <=npar; theta++){
3639: for(i=1; i<=npar; i++){ /* Computes gradient */
3640: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3641: }
3642: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3643: for(i=1;i<=nlstate;i++)
3644: gp[i] = prlim[i][i];
3645:
3646: for(i=1; i<=npar; i++) /* Computes gradient */
3647: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3648: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3649: for(i=1;i<=nlstate;i++)
3650: gm[i] = prlim[i][i];
3651:
3652: for(i=1;i<=nlstate;i++)
3653: gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
3654: } /* End theta */
3655:
3656: trgradg =matrix(1,nlstate,1,npar);
3657:
3658: for(j=1; j<=nlstate;j++)
3659: for(theta=1; theta <=npar; theta++)
3660: trgradg[j][theta]=gradg[theta][j];
3661:
3662: for(i=1;i<=nlstate;i++)
3663: varpl[i][(int)age] =0.;
3664: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
3665: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
3666: for(i=1;i<=nlstate;i++)
3667: varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
3668:
3669: fprintf(ficresvpl,"%.0f ",age );
3670: for(i=1; i<=nlstate;i++)
3671: fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
3672: fprintf(ficresvpl,"\n");
3673: free_vector(gp,1,nlstate);
3674: free_vector(gm,1,nlstate);
3675: free_matrix(gradg,1,npar,1,nlstate);
3676: free_matrix(trgradg,1,nlstate,1,npar);
3677: } /* End age */
3678:
3679: free_vector(xp,1,npar);
3680: free_matrix(doldm,1,nlstate,1,npar);
3681: free_matrix(dnewm,1,nlstate,1,nlstate);
3682:
3683: }
3684:
3685: /************ Variance of one-step probabilities ******************/
3686: 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[])
3687: {
3688: int i, j=0, i1, k1, l1, t, tj;
3689: int k2, l2, j1, z1;
3690: int k=0,l, cptcode;
1.145 brouard 3691: int first=1, first1, first2;
1.126 brouard 3692: double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
3693: double **dnewm,**doldm;
3694: double *xp;
3695: double *gp, *gm;
3696: double **gradg, **trgradg;
3697: double **mu;
1.145 brouard 3698: double age,agelim, cov[NCOVMAX+1];
1.126 brouard 3699: double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
3700: int theta;
3701: char fileresprob[FILENAMELENGTH];
3702: char fileresprobcov[FILENAMELENGTH];
3703: char fileresprobcor[FILENAMELENGTH];
3704: double ***varpij;
3705:
3706: strcpy(fileresprob,"prob");
3707: strcat(fileresprob,fileres);
3708: if((ficresprob=fopen(fileresprob,"w"))==NULL) {
3709: printf("Problem with resultfile: %s\n", fileresprob);
3710: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
3711: }
3712: strcpy(fileresprobcov,"probcov");
3713: strcat(fileresprobcov,fileres);
3714: if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
3715: printf("Problem with resultfile: %s\n", fileresprobcov);
3716: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
3717: }
3718: strcpy(fileresprobcor,"probcor");
3719: strcat(fileresprobcor,fileres);
3720: if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
3721: printf("Problem with resultfile: %s\n", fileresprobcor);
3722: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
3723: }
3724: printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3725: fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3726: printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3727: fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3728: printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3729: fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3730: pstamp(ficresprob);
3731: fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
3732: fprintf(ficresprob,"# Age");
3733: pstamp(ficresprobcov);
3734: fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
3735: fprintf(ficresprobcov,"# Age");
3736: pstamp(ficresprobcor);
3737: fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
3738: fprintf(ficresprobcor,"# Age");
3739:
3740:
3741: for(i=1; i<=nlstate;i++)
3742: for(j=1; j<=(nlstate+ndeath);j++){
3743: fprintf(ficresprob," p%1d-%1d (SE)",i,j);
3744: fprintf(ficresprobcov," p%1d-%1d ",i,j);
3745: fprintf(ficresprobcor," p%1d-%1d ",i,j);
3746: }
3747: /* fprintf(ficresprob,"\n");
3748: fprintf(ficresprobcov,"\n");
3749: fprintf(ficresprobcor,"\n");
3750: */
1.131 brouard 3751: xp=vector(1,npar);
1.126 brouard 3752: dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3753: doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
3754: mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
3755: varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
3756: first=1;
3757: fprintf(ficgp,"\n# Routine varprob");
3758: fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
3759: fprintf(fichtm,"\n");
3760:
3761: fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
3762: fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
3763: file %s<br>\n",optionfilehtmcov);
3764: fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
3765: and drawn. It helps understanding how is the covariance between two incidences.\
3766: They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
3767: 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. \
3768: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
3769: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
3770: standard deviations wide on each axis. <br>\
3771: Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
3772: and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
3773: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
3774:
3775: cov[1]=1;
1.145 brouard 3776: /* tj=cptcoveff; */
3777: tj = (int) pow(2,cptcoveff);
1.126 brouard 3778: if (cptcovn<1) {tj=1;ncodemax[1]=1;}
3779: j1=0;
1.145 brouard 3780: for(j1=1; j1<=tj;j1++){
3781: /*for(i1=1; i1<=ncodemax[t];i1++){ */
3782: /*j1++;*/
1.126 brouard 3783: if (cptcovn>0) {
3784: fprintf(ficresprob, "\n#********** Variable ");
3785: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3786: fprintf(ficresprob, "**********\n#\n");
3787: fprintf(ficresprobcov, "\n#********** Variable ");
3788: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3789: fprintf(ficresprobcov, "**********\n#\n");
3790:
3791: fprintf(ficgp, "\n#********** Variable ");
3792: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3793: fprintf(ficgp, "**********\n#\n");
3794:
3795:
3796: fprintf(fichtmcov, "\n<hr size=\"2\" color=\"#EC5E5E\">********** Variable ");
3797: for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3798: fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
3799:
3800: fprintf(ficresprobcor, "\n#********** Variable ");
3801: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3802: fprintf(ficresprobcor, "**********\n#");
3803: }
3804:
1.145 brouard 3805: gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
3806: trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3807: gp=vector(1,(nlstate)*(nlstate+ndeath));
3808: gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126 brouard 3809: for (age=bage; age<=fage; age ++){
3810: cov[2]=age;
3811: for (k=1; k<=cptcovn;k++) {
1.145 brouard 3812: cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
3813: * 1 1 1 1 1
3814: * 2 2 1 1 1
3815: * 3 1 2 1 1
3816: */
3817: /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126 brouard 3818: }
3819: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
3820: for (k=1; k<=cptcovprod;k++)
3821: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
3822:
3823:
3824: for(theta=1; theta <=npar; theta++){
3825: for(i=1; i<=npar; i++)
3826: xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
3827:
3828: pmij(pmmij,cov,ncovmodel,xp,nlstate);
3829:
3830: k=0;
3831: for(i=1; i<= (nlstate); i++){
3832: for(j=1; j<=(nlstate+ndeath);j++){
3833: k=k+1;
3834: gp[k]=pmmij[i][j];
3835: }
3836: }
3837:
3838: for(i=1; i<=npar; i++)
3839: xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
3840:
3841: pmij(pmmij,cov,ncovmodel,xp,nlstate);
3842: k=0;
3843: for(i=1; i<=(nlstate); i++){
3844: for(j=1; j<=(nlstate+ndeath);j++){
3845: k=k+1;
3846: gm[k]=pmmij[i][j];
3847: }
3848: }
3849:
3850: for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
3851: gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];
3852: }
3853:
3854: for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
3855: for(theta=1; theta <=npar; theta++)
3856: trgradg[j][theta]=gradg[theta][j];
3857:
3858: matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
3859: matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
3860:
3861: pmij(pmmij,cov,ncovmodel,x,nlstate);
3862:
3863: k=0;
3864: for(i=1; i<=(nlstate); i++){
3865: for(j=1; j<=(nlstate+ndeath);j++){
3866: k=k+1;
3867: mu[k][(int) age]=pmmij[i][j];
3868: }
3869: }
3870: for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
3871: for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
3872: varpij[i][j][(int)age] = doldm[i][j];
3873:
3874: /*printf("\n%d ",(int)age);
3875: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
3876: printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
3877: fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
3878: }*/
3879:
3880: fprintf(ficresprob,"\n%d ",(int)age);
3881: fprintf(ficresprobcov,"\n%d ",(int)age);
3882: fprintf(ficresprobcor,"\n%d ",(int)age);
3883:
3884: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
3885: fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
3886: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
3887: fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
3888: fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
3889: }
3890: i=0;
3891: for (k=1; k<=(nlstate);k++){
3892: for (l=1; l<=(nlstate+ndeath);l++){
1.145 brouard 3893: i++;
1.126 brouard 3894: fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
3895: fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
3896: for (j=1; j<=i;j++){
1.145 brouard 3897: /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126 brouard 3898: fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
3899: fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
3900: }
3901: }
3902: }/* end of loop for state */
3903: } /* end of loop for age */
1.145 brouard 3904: free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
3905: free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
3906: free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
3907: free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
3908:
1.126 brouard 3909: /* Confidence intervalle of pij */
3910: /*
1.131 brouard 3911: fprintf(ficgp,"\nunset parametric;unset label");
1.126 brouard 3912: fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
3913: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
3914: 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);
3915: fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
3916: fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
3917: fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
3918: */
3919:
3920: /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145 brouard 3921: first1=1;first2=2;
1.126 brouard 3922: for (k2=1; k2<=(nlstate);k2++){
3923: for (l2=1; l2<=(nlstate+ndeath);l2++){
3924: if(l2==k2) continue;
3925: j=(k2-1)*(nlstate+ndeath)+l2;
3926: for (k1=1; k1<=(nlstate);k1++){
3927: for (l1=1; l1<=(nlstate+ndeath);l1++){
3928: if(l1==k1) continue;
3929: i=(k1-1)*(nlstate+ndeath)+l1;
3930: if(i<=j) continue;
3931: for (age=bage; age<=fage; age ++){
3932: if ((int)age %5==0){
3933: v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
3934: v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
3935: cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
3936: mu1=mu[i][(int) age]/stepm*YEARM ;
3937: mu2=mu[j][(int) age]/stepm*YEARM;
3938: c12=cv12/sqrt(v1*v2);
3939: /* Computing eigen value of matrix of covariance */
3940: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
3941: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135 brouard 3942: if ((lc2 <0) || (lc1 <0) ){
1.145 brouard 3943: if(first2==1){
3944: first1=0;
3945: 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);
3946: }
3947: 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);
3948: /* lc1=fabs(lc1); */ /* If we want to have them positive */
3949: /* lc2=fabs(lc2); */
1.135 brouard 3950: }
3951:
1.126 brouard 3952: /* Eigen vectors */
3953: v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
3954: /*v21=sqrt(1.-v11*v11); *//* error */
3955: v21=(lc1-v1)/cv12*v11;
3956: v12=-v21;
3957: v22=v11;
3958: tnalp=v21/v11;
3959: if(first1==1){
3960: first1=0;
3961: 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);
3962: }
3963: 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);
3964: /*printf(fignu*/
3965: /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
3966: /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
3967: if(first==1){
3968: first=0;
3969: fprintf(ficgp,"\nset parametric;unset label");
3970: 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 3971: fprintf(ficgp,"\nset ter png small size 320, 240");
1.126 brouard 3972: fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
3973: :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
3974: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
3975: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
3976: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
3977: fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
3978: fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
3979: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
3980: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
3981: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
3982: 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",\
3983: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
3984: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
3985: }else{
3986: first=0;
3987: fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
3988: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
3989: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
3990: 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",\
3991: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
3992: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
3993: }/* if first */
3994: } /* age mod 5 */
3995: } /* end loop age */
3996: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
3997: first=1;
3998: } /*l12 */
3999: } /* k12 */
4000: } /*l1 */
4001: }/* k1 */
1.145 brouard 4002: /* } /* loop covariates */
1.126 brouard 4003: }
4004: free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
4005: free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
4006: free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4007: free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
4008: free_vector(xp,1,npar);
4009: fclose(ficresprob);
4010: fclose(ficresprobcov);
4011: fclose(ficresprobcor);
4012: fflush(ficgp);
4013: fflush(fichtmcov);
4014: }
4015:
4016:
4017: /******************* Printing html file ***********/
4018: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
4019: int lastpass, int stepm, int weightopt, char model[],\
4020: int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
4021: int popforecast, int estepm ,\
4022: double jprev1, double mprev1,double anprev1, \
4023: double jprev2, double mprev2,double anprev2){
4024: int jj1, k1, i1, cpt;
4025:
4026: fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
4027: <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
4028: </ul>");
4029: fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
4030: - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
4031: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
4032: fprintf(fichtm,"\
4033: - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
4034: stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
4035: fprintf(fichtm,"\
4036: - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
4037: subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
4038: fprintf(fichtm,"\
1.128 brouard 4039: - (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 4040: <a href=\"%s\">%s</a> <br>\n",
4041: estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
4042: fprintf(fichtm,"\
4043: - Population projections by age and states: \
4044: <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
4045:
4046: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
4047:
1.145 brouard 4048: m=pow(2,cptcoveff);
1.126 brouard 4049: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4050:
4051: jj1=0;
4052: for(k1=1; k1<=m;k1++){
4053: for(i1=1; i1<=ncodemax[k1];i1++){
4054: jj1++;
4055: if (cptcovn > 0) {
4056: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4057: for (cpt=1; cpt<=cptcoveff;cpt++)
4058: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4059: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4060: }
4061: /* Pij */
1.145 brouard 4062: 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> \
4063: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
1.126 brouard 4064: /* Quasi-incidences */
4065: fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
1.145 brouard 4066: 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> \
4067: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
1.126 brouard 4068: /* Period (stable) prevalence in each health state */
1.154 brouard 4069: for(cpt=1; cpt<=nlstate;cpt++){
4070: fprintf(fichtm,"<br>- Convergence from each state (1 to %d) to period (stable) prevalence in state %d <a href=\"%s%d_%d.png\">%s%d_%d.png</a><br> \
4071: <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 4072: }
4073: for(cpt=1; cpt<=nlstate;cpt++) {
1.154 brouard 4074: 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> \
4075: <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 4076: }
4077: } /* end i1 */
4078: }/* End k1 */
4079: fprintf(fichtm,"</ul>");
4080:
4081:
4082: fprintf(fichtm,"\
4083: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
4084: - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
4085:
4086: fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4087: subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
4088: fprintf(fichtm,"\
4089: - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4090: subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
4091:
4092: fprintf(fichtm,"\
4093: - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4094: subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
4095: fprintf(fichtm,"\
4096: - 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): \
4097: <a href=\"%s\">%s</a> <br>\n</li>",
4098: estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
4099: fprintf(fichtm,"\
4100: - (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): \
4101: <a href=\"%s\">%s</a> <br>\n</li>",
4102: estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
4103: fprintf(fichtm,"\
1.128 brouard 4104: - 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 4105: estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
4106: fprintf(fichtm,"\
1.128 brouard 4107: - 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",
4108: estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
1.126 brouard 4109: fprintf(fichtm,"\
4110: - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
4111: subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
4112:
4113: /* if(popforecast==1) fprintf(fichtm,"\n */
4114: /* - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
4115: /* - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
4116: /* <br>",fileres,fileres,fileres,fileres); */
4117: /* else */
4118: /* 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); */
4119: fflush(fichtm);
4120: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
4121:
1.145 brouard 4122: m=pow(2,cptcoveff);
1.126 brouard 4123: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4124:
4125: jj1=0;
4126: for(k1=1; k1<=m;k1++){
4127: for(i1=1; i1<=ncodemax[k1];i1++){
4128: jj1++;
4129: if (cptcovn > 0) {
4130: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4131: for (cpt=1; cpt<=cptcoveff;cpt++)
4132: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4133: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4134: }
4135: for(cpt=1; cpt<=nlstate;cpt++) {
4136: fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.145 brouard 4137: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
4138: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);
1.126 brouard 4139: }
4140: fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128 brouard 4141: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
4142: true period expectancies (those weighted with period prevalences are also\
4143: drawn in addition to the population based expectancies computed using\
4144: observed and cahotic prevalences: %s%d.png<br>\
1.126 brouard 4145: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
4146: } /* end i1 */
4147: }/* End k1 */
4148: fprintf(fichtm,"</ul>");
4149: fflush(fichtm);
4150: }
4151:
4152: /******************* Gnuplot file **************/
4153: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4154:
4155: char dirfileres[132],optfileres[132];
1.130 brouard 4156: int m0,cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
4157: int ng=0;
1.126 brouard 4158: /* if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
4159: /* printf("Problem with file %s",optionfilegnuplot); */
4160: /* fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
4161: /* } */
4162:
4163: /*#ifdef windows */
4164: fprintf(ficgp,"cd \"%s\" \n",pathc);
4165: /*#endif */
4166: m=pow(2,cptcoveff);
4167:
4168: strcpy(dirfileres,optionfilefiname);
4169: strcpy(optfileres,"vpl");
4170: /* 1eme*/
1.153 brouard 4171: fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
1.126 brouard 4172: for (cpt=1; cpt<= nlstate ; cpt ++) {
1.145 brouard 4173: for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
4174: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
4175: fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
1.126 brouard 4176: fprintf(ficgp,"set xlabel \"Age\" \n\
4177: set ylabel \"Probability\" \n\
1.145 brouard 4178: set ter png small size 320, 240\n\
1.126 brouard 4179: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
4180:
4181: for (i=1; i<= nlstate ; i ++) {
4182: if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
1.131 brouard 4183: else fprintf(ficgp," \%%*lf (\%%*lf)");
1.126 brouard 4184: }
1.145 brouard 4185: 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 4186: for (i=1; i<= nlstate ; i ++) {
4187: if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
4188: else fprintf(ficgp," \%%*lf (\%%*lf)");
4189: }
1.145 brouard 4190: 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 4191: for (i=1; i<= nlstate ; i ++) {
4192: if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
4193: else fprintf(ficgp," \%%*lf (\%%*lf)");
4194: }
1.145 brouard 4195: 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 4196: }
4197: }
4198: /*2 eme*/
1.153 brouard 4199: fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
1.126 brouard 4200: for (k1=1; k1<= m ; k1 ++) {
4201: fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
1.145 brouard 4202: fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
1.126 brouard 4203:
4204: for (i=1; i<= nlstate+1 ; i ++) {
4205: k=2*i;
4206: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4207: for (j=1; j<= nlstate+1 ; j ++) {
4208: if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
4209: else fprintf(ficgp," \%%*lf (\%%*lf)");
4210: }
4211: if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
4212: else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
4213: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4214: for (j=1; j<= nlstate+1 ; j ++) {
4215: if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
4216: else fprintf(ficgp," \%%*lf (\%%*lf)");
4217: }
1.145 brouard 4218: fprintf(ficgp,"\" t\"\" w l lt 0,");
1.126 brouard 4219: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4220: for (j=1; j<= nlstate+1 ; j ++) {
4221: if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
4222: else fprintf(ficgp," \%%*lf (\%%*lf)");
4223: }
1.145 brouard 4224: if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
4225: else fprintf(ficgp,"\" t\"\" w l lt 0,");
1.126 brouard 4226: }
4227: }
4228:
4229: /*3eme*/
4230:
4231: for (k1=1; k1<= m ; k1 ++) {
4232: for (cpt=1; cpt<= nlstate ; cpt ++) {
4233: /* k=2+nlstate*(2*cpt-2); */
4234: k=2+(nlstate+1)*(cpt-1);
4235: fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
1.145 brouard 4236: fprintf(ficgp,"set ter png small size 320, 240\n\
1.126 brouard 4237: 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);
4238: /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4239: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4240: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4241: fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4242: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4243: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4244:
4245: */
4246: for (i=1; i< nlstate ; i ++) {
4247: 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);
4248: /* 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);*/
4249:
4250: }
4251: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
4252: }
4253: }
4254:
4255: /* CV preval stable (period) */
1.153 brouard 4256: for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
4257: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.126 brouard 4258: k=3;
1.153 brouard 4259: fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
1.145 brouard 4260: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
1.126 brouard 4261: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.145 brouard 4262: set ter png small size 320, 240\n\
1.126 brouard 4263: unset log y\n\
1.153 brouard 4264: plot [%.f:%.f] ", ageminpar, agemaxpar);
4265: for (i=1; i<= nlstate ; i ++){
4266: if(i==1)
4267: fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
4268: else
4269: fprintf(ficgp,", '' ");
1.154 brouard 4270: l=(nlstate+ndeath)*(i-1)+1;
4271: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.153 brouard 4272: for (j=1; j<= (nlstate-1) ; j ++)
4273: fprintf(ficgp,"+$%d",k+l+j);
4274: fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
4275: } /* nlstate */
4276: fprintf(ficgp,"\n");
4277: } /* end cpt state*/
4278: } /* end covariate */
1.126 brouard 4279:
4280: /* proba elementaires */
4281: for(i=1,jk=1; i <=nlstate; i++){
4282: for(k=1; k <=(nlstate+ndeath); k++){
4283: if (k != i) {
4284: for(j=1; j <=ncovmodel; j++){
4285: fprintf(ficgp,"p%d=%f ",jk,p[jk]);
4286: jk++;
4287: fprintf(ficgp,"\n");
4288: }
4289: }
4290: }
4291: }
1.145 brouard 4292: /*goto avoid;*/
1.126 brouard 4293: for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
4294: for(jk=1; jk <=m; jk++) {
1.145 brouard 4295: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);
1.126 brouard 4296: if (ng==2)
4297: fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
4298: else
4299: fprintf(ficgp,"\nset title \"Probability\"\n");
1.145 brouard 4300: fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot [%.f:%.f] ",ageminpar,agemaxpar);
1.126 brouard 4301: i=1;
4302: for(k2=1; k2<=nlstate; k2++) {
4303: k3=i;
4304: for(k=1; k<=(nlstate+ndeath); k++) {
4305: if (k != k2){
4306: if(ng==2)
4307: fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
4308: else
4309: fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
1.141 brouard 4310: ij=1;/* To be checked else nbcode[0][0] wrong */
1.126 brouard 4311: for(j=3; j <=ncovmodel; j++) {
1.145 brouard 4312: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /\* Bug valgrind *\/ */
4313: /* /\*fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);*\/ */
4314: /* ij++; */
4315: /* } */
4316: /* else */
1.126 brouard 4317: fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4318: }
4319: fprintf(ficgp,")/(1");
4320:
4321: for(k1=1; k1 <=nlstate; k1++){
4322: fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
4323: ij=1;
4324: for(j=3; j <=ncovmodel; j++){
1.145 brouard 4325: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { */
4326: /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]); */
4327: /* ij++; */
4328: /* } */
4329: /* else */
1.126 brouard 4330: fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4331: }
4332: fprintf(ficgp,")");
4333: }
4334: fprintf(ficgp,") t \"p%d%d\" ", k2,k);
4335: if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
4336: i=i+ncovmodel;
4337: }
4338: } /* end k */
4339: } /* end k2 */
4340: } /* end jk */
4341: } /* end ng */
1.145 brouard 4342: avoid:
1.126 brouard 4343: fflush(ficgp);
4344: } /* end gnuplot */
4345:
4346:
4347: /*************** Moving average **************/
4348: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
4349:
4350: int i, cpt, cptcod;
4351: int modcovmax =1;
4352: int mobilavrange, mob;
4353: double age;
4354:
4355: modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
4356: a covariate has 2 modalities */
4357: if (cptcovn<1) modcovmax=1; /* At least 1 pass */
4358:
4359: if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
4360: if(mobilav==1) mobilavrange=5; /* default */
4361: else mobilavrange=mobilav;
4362: for (age=bage; age<=fage; age++)
4363: for (i=1; i<=nlstate;i++)
4364: for (cptcod=1;cptcod<=modcovmax;cptcod++)
4365: mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
4366: /* We keep the original values on the extreme ages bage, fage and for
4367: fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
4368: we use a 5 terms etc. until the borders are no more concerned.
4369: */
4370: for (mob=3;mob <=mobilavrange;mob=mob+2){
4371: for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
4372: for (i=1; i<=nlstate;i++){
4373: for (cptcod=1;cptcod<=modcovmax;cptcod++){
4374: mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
4375: for (cpt=1;cpt<=(mob-1)/2;cpt++){
4376: mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
4377: mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
4378: }
4379: mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
4380: }
4381: }
4382: }/* end age */
4383: }/* end mob */
4384: }else return -1;
4385: return 0;
4386: }/* End movingaverage */
4387:
4388:
4389: /************** Forecasting ******************/
4390: 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){
4391: /* proj1, year, month, day of starting projection
4392: agemin, agemax range of age
4393: dateprev1 dateprev2 range of dates during which prevalence is computed
4394: anproj2 year of en of projection (same day and month as proj1).
4395: */
4396: int yearp, stepsize, hstepm, nhstepm, j, k, c, cptcod, i, h, i1;
4397: int *popage;
4398: double agec; /* generic age */
4399: double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
4400: double *popeffectif,*popcount;
4401: double ***p3mat;
4402: double ***mobaverage;
4403: char fileresf[FILENAMELENGTH];
4404:
4405: agelim=AGESUP;
4406: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4407:
4408: strcpy(fileresf,"f");
4409: strcat(fileresf,fileres);
4410: if((ficresf=fopen(fileresf,"w"))==NULL) {
4411: printf("Problem with forecast resultfile: %s\n", fileresf);
4412: fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
4413: }
4414: printf("Computing forecasting: result on file '%s' \n", fileresf);
4415: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
4416:
4417: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4418:
4419: if (mobilav!=0) {
4420: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4421: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4422: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4423: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4424: }
4425: }
4426:
4427: stepsize=(int) (stepm+YEARM-1)/YEARM;
4428: if (stepm<=12) stepsize=1;
4429: if(estepm < stepm){
4430: printf ("Problem %d lower than %d\n",estepm, stepm);
4431: }
4432: else hstepm=estepm;
4433:
4434: hstepm=hstepm/stepm;
4435: yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp and
4436: fractional in yp1 */
4437: anprojmean=yp;
4438: yp2=modf((yp1*12),&yp);
4439: mprojmean=yp;
4440: yp1=modf((yp2*30.5),&yp);
4441: jprojmean=yp;
4442: if(jprojmean==0) jprojmean=1;
4443: if(mprojmean==0) jprojmean=1;
4444:
4445: i1=cptcoveff;
4446: if (cptcovn < 1){i1=1;}
4447:
4448: fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
4449:
4450: fprintf(ficresf,"#****** Routine prevforecast **\n");
4451:
4452: /* if (h==(int)(YEARM*yearp)){ */
4453: for(cptcov=1, k=0;cptcov<=i1;cptcov++){
4454: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4455: k=k+1;
4456: fprintf(ficresf,"\n#******");
4457: for(j=1;j<=cptcoveff;j++) {
4458: 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]]);
4459: }
4460: fprintf(ficresf,"******\n");
4461: fprintf(ficresf,"# Covariate valuofcovar yearproj age");
4462: for(j=1; j<=nlstate+ndeath;j++){
4463: for(i=1; i<=nlstate;i++)
4464: fprintf(ficresf," p%d%d",i,j);
4465: fprintf(ficresf," p.%d",j);
4466: }
4467: for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
4468: fprintf(ficresf,"\n");
4469: fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);
4470:
4471: for (agec=fage; agec>=(ageminpar-1); agec--){
4472: nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
4473: nhstepm = nhstepm/hstepm;
4474: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4475: oldm=oldms;savm=savms;
4476: hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
4477:
4478: for (h=0; h<=nhstepm; h++){
4479: if (h*hstepm/YEARM*stepm ==yearp) {
4480: fprintf(ficresf,"\n");
4481: for(j=1;j<=cptcoveff;j++)
4482: fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4483: fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
4484: }
4485: for(j=1; j<=nlstate+ndeath;j++) {
4486: ppij=0.;
4487: for(i=1; i<=nlstate;i++) {
4488: if (mobilav==1)
4489: ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
4490: else {
4491: ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
4492: }
4493: if (h*hstepm/YEARM*stepm== yearp) {
4494: fprintf(ficresf," %.3f", p3mat[i][j][h]);
4495: }
4496: } /* end i */
4497: if (h*hstepm/YEARM*stepm==yearp) {
4498: fprintf(ficresf," %.3f", ppij);
4499: }
4500: }/* end j */
4501: } /* end h */
4502: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4503: } /* end agec */
4504: } /* end yearp */
4505: } /* end cptcod */
4506: } /* end cptcov */
4507:
4508: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4509:
4510: fclose(ficresf);
4511: }
4512:
4513: /************** Forecasting *****not tested NB*************/
4514: 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){
4515:
4516: int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
4517: int *popage;
4518: double calagedatem, agelim, kk1, kk2;
4519: double *popeffectif,*popcount;
4520: double ***p3mat,***tabpop,***tabpopprev;
4521: double ***mobaverage;
4522: char filerespop[FILENAMELENGTH];
4523:
4524: tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4525: tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4526: agelim=AGESUP;
4527: calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
4528:
4529: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4530:
4531:
4532: strcpy(filerespop,"pop");
4533: strcat(filerespop,fileres);
4534: if((ficrespop=fopen(filerespop,"w"))==NULL) {
4535: printf("Problem with forecast resultfile: %s\n", filerespop);
4536: fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
4537: }
4538: printf("Computing forecasting: result on file '%s' \n", filerespop);
4539: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
4540:
4541: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4542:
4543: if (mobilav!=0) {
4544: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4545: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4546: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4547: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4548: }
4549: }
4550:
4551: stepsize=(int) (stepm+YEARM-1)/YEARM;
4552: if (stepm<=12) stepsize=1;
4553:
4554: agelim=AGESUP;
4555:
4556: hstepm=1;
4557: hstepm=hstepm/stepm;
4558:
4559: if (popforecast==1) {
4560: if((ficpop=fopen(popfile,"r"))==NULL) {
4561: printf("Problem with population file : %s\n",popfile);exit(0);
4562: fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
4563: }
4564: popage=ivector(0,AGESUP);
4565: popeffectif=vector(0,AGESUP);
4566: popcount=vector(0,AGESUP);
4567:
4568: i=1;
4569: while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
4570:
4571: imx=i;
4572: for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
4573: }
4574:
4575: for(cptcov=1,k=0;cptcov<=i2;cptcov++){
4576: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4577: k=k+1;
4578: fprintf(ficrespop,"\n#******");
4579: for(j=1;j<=cptcoveff;j++) {
4580: fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4581: }
4582: fprintf(ficrespop,"******\n");
4583: fprintf(ficrespop,"# Age");
4584: for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
4585: if (popforecast==1) fprintf(ficrespop," [Population]");
4586:
4587: for (cpt=0; cpt<=0;cpt++) {
4588: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4589:
4590: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4591: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4592: nhstepm = nhstepm/hstepm;
4593:
4594: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4595: oldm=oldms;savm=savms;
4596: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4597:
4598: for (h=0; h<=nhstepm; h++){
4599: if (h==(int) (calagedatem+YEARM*cpt)) {
4600: fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4601: }
4602: for(j=1; j<=nlstate+ndeath;j++) {
4603: kk1=0.;kk2=0;
4604: for(i=1; i<=nlstate;i++) {
4605: if (mobilav==1)
4606: kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
4607: else {
4608: kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
4609: }
4610: }
4611: if (h==(int)(calagedatem+12*cpt)){
4612: tabpop[(int)(agedeb)][j][cptcod]=kk1;
4613: /*fprintf(ficrespop," %.3f", kk1);
4614: if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
4615: }
4616: }
4617: for(i=1; i<=nlstate;i++){
4618: kk1=0.;
4619: for(j=1; j<=nlstate;j++){
4620: kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
4621: }
4622: tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
4623: }
4624:
4625: if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
4626: fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
4627: }
4628: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4629: }
4630: }
4631:
4632: /******/
4633:
4634: for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
4635: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4636: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4637: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4638: nhstepm = nhstepm/hstepm;
4639:
4640: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4641: oldm=oldms;savm=savms;
4642: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4643: for (h=0; h<=nhstepm; h++){
4644: if (h==(int) (calagedatem+YEARM*cpt)) {
4645: fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4646: }
4647: for(j=1; j<=nlstate+ndeath;j++) {
4648: kk1=0.;kk2=0;
4649: for(i=1; i<=nlstate;i++) {
4650: kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];
4651: }
4652: if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);
4653: }
4654: }
4655: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4656: }
4657: }
4658: }
4659: }
4660:
4661: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4662:
4663: if (popforecast==1) {
4664: free_ivector(popage,0,AGESUP);
4665: free_vector(popeffectif,0,AGESUP);
4666: free_vector(popcount,0,AGESUP);
4667: }
4668: free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4669: free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4670: fclose(ficrespop);
4671: } /* End of popforecast */
4672:
4673: int fileappend(FILE *fichier, char *optionfich)
4674: {
4675: if((fichier=fopen(optionfich,"a"))==NULL) {
4676: printf("Problem with file: %s\n", optionfich);
4677: fprintf(ficlog,"Problem with file: %s\n", optionfich);
4678: return (0);
4679: }
4680: fflush(fichier);
4681: return (1);
4682: }
4683:
4684:
4685: /**************** function prwizard **********************/
4686: void prwizard(int ncovmodel, int nlstate, int ndeath, char model[], FILE *ficparo)
4687: {
4688:
4689: /* Wizard to print covariance matrix template */
4690:
4691: char ca[32], cb[32], cc[32];
4692: int i,j, k, l, li, lj, lk, ll, jj, npar, itimes;
4693: int numlinepar;
4694:
4695: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4696: fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4697: for(i=1; i <=nlstate; i++){
4698: jj=0;
4699: for(j=1; j <=nlstate+ndeath; j++){
4700: if(j==i) continue;
4701: jj++;
4702: /*ca[0]= k+'a'-1;ca[1]='\0';*/
4703: printf("%1d%1d",i,j);
4704: fprintf(ficparo,"%1d%1d",i,j);
4705: for(k=1; k<=ncovmodel;k++){
4706: /* printf(" %lf",param[i][j][k]); */
4707: /* fprintf(ficparo," %lf",param[i][j][k]); */
4708: printf(" 0.");
4709: fprintf(ficparo," 0.");
4710: }
4711: printf("\n");
4712: fprintf(ficparo,"\n");
4713: }
4714: }
4715: printf("# Scales (for hessian or gradient estimation)\n");
4716: fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
4717: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
4718: for(i=1; i <=nlstate; i++){
4719: jj=0;
4720: for(j=1; j <=nlstate+ndeath; j++){
4721: if(j==i) continue;
4722: jj++;
4723: fprintf(ficparo,"%1d%1d",i,j);
4724: printf("%1d%1d",i,j);
4725: fflush(stdout);
4726: for(k=1; k<=ncovmodel;k++){
4727: /* printf(" %le",delti3[i][j][k]); */
4728: /* fprintf(ficparo," %le",delti3[i][j][k]); */
4729: printf(" 0.");
4730: fprintf(ficparo," 0.");
4731: }
4732: numlinepar++;
4733: printf("\n");
4734: fprintf(ficparo,"\n");
4735: }
4736: }
4737: printf("# Covariance matrix\n");
4738: /* # 121 Var(a12)\n\ */
4739: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4740: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
4741: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
4742: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
4743: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
4744: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
4745: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4746: fflush(stdout);
4747: fprintf(ficparo,"# Covariance matrix\n");
4748: /* # 121 Var(a12)\n\ */
4749: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4750: /* # ...\n\ */
4751: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4752:
4753: for(itimes=1;itimes<=2;itimes++){
4754: jj=0;
4755: for(i=1; i <=nlstate; i++){
4756: for(j=1; j <=nlstate+ndeath; j++){
4757: if(j==i) continue;
4758: for(k=1; k<=ncovmodel;k++){
4759: jj++;
4760: ca[0]= k+'a'-1;ca[1]='\0';
4761: if(itimes==1){
4762: printf("#%1d%1d%d",i,j,k);
4763: fprintf(ficparo,"#%1d%1d%d",i,j,k);
4764: }else{
4765: printf("%1d%1d%d",i,j,k);
4766: fprintf(ficparo,"%1d%1d%d",i,j,k);
4767: /* printf(" %.5le",matcov[i][j]); */
4768: }
4769: ll=0;
4770: for(li=1;li <=nlstate; li++){
4771: for(lj=1;lj <=nlstate+ndeath; lj++){
4772: if(lj==li) continue;
4773: for(lk=1;lk<=ncovmodel;lk++){
4774: ll++;
4775: if(ll<=jj){
4776: cb[0]= lk +'a'-1;cb[1]='\0';
4777: if(ll<jj){
4778: if(itimes==1){
4779: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4780: fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4781: }else{
4782: printf(" 0.");
4783: fprintf(ficparo," 0.");
4784: }
4785: }else{
4786: if(itimes==1){
4787: printf(" Var(%s%1d%1d)",ca,i,j);
4788: fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
4789: }else{
4790: printf(" 0.");
4791: fprintf(ficparo," 0.");
4792: }
4793: }
4794: }
4795: } /* end lk */
4796: } /* end lj */
4797: } /* end li */
4798: printf("\n");
4799: fprintf(ficparo,"\n");
4800: numlinepar++;
4801: } /* end k*/
4802: } /*end j */
4803: } /* end i */
4804: } /* end itimes */
4805:
4806: } /* end of prwizard */
4807: /******************* Gompertz Likelihood ******************************/
4808: double gompertz(double x[])
4809: {
4810: double A,B,L=0.0,sump=0.,num=0.;
4811: int i,n=0; /* n is the size of the sample */
4812:
4813: for (i=0;i<=imx-1 ; i++) {
4814: sump=sump+weight[i];
4815: /* sump=sump+1;*/
4816: num=num+1;
4817: }
4818:
4819:
4820: /* for (i=0; i<=imx; i++)
4821: 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]);*/
4822:
4823: for (i=1;i<=imx ; i++)
4824: {
4825: if (cens[i] == 1 && wav[i]>1)
4826: A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
4827:
4828: if (cens[i] == 0 && wav[i]>1)
4829: A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
4830: +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);
4831:
4832: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
4833: if (wav[i] > 1 ) { /* ??? */
4834: L=L+A*weight[i];
4835: /* 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]);*/
4836: }
4837: }
4838:
4839: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
4840:
4841: return -2*L*num/sump;
4842: }
4843:
1.136 brouard 4844: #ifdef GSL
4845: /******************* Gompertz_f Likelihood ******************************/
4846: double gompertz_f(const gsl_vector *v, void *params)
4847: {
4848: double A,B,LL=0.0,sump=0.,num=0.;
4849: double *x= (double *) v->data;
4850: int i,n=0; /* n is the size of the sample */
4851:
4852: for (i=0;i<=imx-1 ; i++) {
4853: sump=sump+weight[i];
4854: /* sump=sump+1;*/
4855: num=num+1;
4856: }
4857:
4858:
4859: /* for (i=0; i<=imx; i++)
4860: 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]);*/
4861: printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
4862: for (i=1;i<=imx ; i++)
4863: {
4864: if (cens[i] == 1 && wav[i]>1)
4865: A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
4866:
4867: if (cens[i] == 0 && wav[i]>1)
4868: A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
4869: +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);
4870:
4871: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
4872: if (wav[i] > 1 ) { /* ??? */
4873: LL=LL+A*weight[i];
4874: /* 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]);*/
4875: }
4876: }
4877:
4878: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
4879: printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
4880:
4881: return -2*LL*num/sump;
4882: }
4883: #endif
4884:
1.126 brouard 4885: /******************* Printing html file ***********/
4886: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
4887: int lastpass, int stepm, int weightopt, char model[],\
4888: int imx, double p[],double **matcov,double agemortsup){
4889: int i,k;
4890:
4891: fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
4892: fprintf(fichtm," mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
4893: for (i=1;i<=2;i++)
4894: 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]));
4895: fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
4896: fprintf(fichtm,"</ul>");
4897:
4898: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
4899:
4900: 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>");
4901:
4902: for (k=agegomp;k<(agemortsup-2);k++)
4903: 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]);
4904:
4905:
4906: fflush(fichtm);
4907: }
4908:
4909: /******************* Gnuplot file **************/
4910: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4911:
4912: char dirfileres[132],optfileres[132];
4913: int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;
4914: int ng;
4915:
4916:
4917: /*#ifdef windows */
4918: fprintf(ficgp,"cd \"%s\" \n",pathc);
4919: /*#endif */
4920:
4921:
4922: strcpy(dirfileres,optionfilefiname);
4923: strcpy(optfileres,"vpl");
4924: fprintf(ficgp,"set out \"graphmort.png\"\n ");
4925: fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
1.145 brouard 4926: fprintf(ficgp, "set ter png small size 320, 240\n set log y\n");
4927: /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126 brouard 4928: fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
4929:
4930: }
4931:
1.136 brouard 4932: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
4933: {
1.126 brouard 4934:
1.136 brouard 4935: /*-------- data file ----------*/
4936: FILE *fic;
4937: char dummy[]=" ";
4938: int i, j, n;
4939: int linei, month, year,iout;
4940: char line[MAXLINE], linetmp[MAXLINE];
4941: char stra[80], strb[80];
4942: char *stratrunc;
4943: int lstra;
1.126 brouard 4944:
4945:
1.136 brouard 4946: if((fic=fopen(datafile,"r"))==NULL) {
4947: printf("Problem while opening datafile: %s\n", datafile);return 1;
4948: fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
4949: }
1.126 brouard 4950:
1.136 brouard 4951: i=1;
4952: linei=0;
4953: while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
4954: linei=linei+1;
4955: for(j=strlen(line); j>=0;j--){ /* Untabifies line */
4956: if(line[j] == '\t')
4957: line[j] = ' ';
4958: }
4959: for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
4960: ;
4961: };
4962: line[j+1]=0; /* Trims blanks at end of line */
4963: if(line[0]=='#'){
4964: fprintf(ficlog,"Comment line\n%s\n",line);
4965: printf("Comment line\n%s\n",line);
4966: continue;
4967: }
4968: trimbb(linetmp,line); /* Trims multiple blanks in line */
4969: for (j=0; line[j]!='\0';j++){
4970: line[j]=linetmp[j];
4971: }
4972:
1.126 brouard 4973:
1.136 brouard 4974: for (j=maxwav;j>=1;j--){
1.137 brouard 4975: cutv(stra, strb, line, ' ');
1.136 brouard 4976: if(strb[0]=='.') { /* Missing status */
4977: lval=-1;
4978: }else{
4979: errno=0;
4980: lval=strtol(strb,&endptr,10);
4981: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
4982: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 4983: 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);
4984: 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 4985: return 1;
4986: }
4987: }
4988: s[j][i]=lval;
4989:
4990: strcpy(line,stra);
4991: cutv(stra, strb,line,' ');
4992: if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
4993: }
1.145 brouard 4994: else if(iout=sscanf(strb,"%s.",dummy) != 0){
1.136 brouard 4995: month=99;
4996: year=9999;
4997: }else{
1.141 brouard 4998: 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);
4999: 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 5000: return 1;
5001: }
5002: anint[j][i]= (double) year;
5003: mint[j][i]= (double)month;
5004: strcpy(line,stra);
5005: } /* ENd Waves */
5006:
5007: cutv(stra, strb,line,' ');
5008: if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
5009: }
5010: else if(iout=sscanf(strb,"%s.",dummy) != 0){
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 death (mm/yyyy or .). Exiting.\n",strb, linei,i,line);
5015: 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 5016: return 1;
5017: }
5018: andc[i]=(double) year;
5019: moisdc[i]=(double) month;
5020: strcpy(line,stra);
5021:
5022: cutv(stra, strb,line,' ');
5023: if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
5024: }
1.145 brouard 5025: else if(iout=sscanf(strb,"%s.", dummy) != 0){
1.136 brouard 5026: month=99;
5027: year=9999;
5028: }else{
1.141 brouard 5029: printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be a date of birth (mm/yyyy or .). Exiting.\n",strb, linei,i,line);
5030: 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 5031: return 1;
5032: }
5033: if (year==9999) {
1.141 brouard 5034: 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);
5035: 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 5036: return 1;
1.126 brouard 5037:
1.136 brouard 5038: }
5039: annais[i]=(double)(year);
5040: moisnais[i]=(double)(month);
5041: strcpy(line,stra);
5042:
5043: cutv(stra, strb,line,' ');
5044: errno=0;
5045: dval=strtod(strb,&endptr);
5046: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5047: printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight. Exiting.\n",dval, i,line,linei);
5048: 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 5049: fflush(ficlog);
5050: return 1;
5051: }
5052: weight[i]=dval;
5053: strcpy(line,stra);
5054:
5055: for (j=ncovcol;j>=1;j--){
5056: cutv(stra, strb,line,' ');
5057: if(strb[0]=='.') { /* Missing status */
5058: lval=-1;
5059: }else{
5060: errno=0;
5061: lval=strtol(strb,&endptr,10);
5062: if( strb[0]=='\0' || (*endptr != '\0')){
1.141 brouard 5063: 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);
5064: 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 5065: return 1;
5066: }
5067: }
5068: if(lval <-1 || lval >1){
1.141 brouard 5069: printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 5070: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5071: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5072: For example, for multinomial values like 1, 2 and 3,\n \
5073: build V1=0 V2=0 for the reference value (1),\n \
5074: V1=1 V2=0 for (2) \n \
5075: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5076: output of IMaCh is often meaningless.\n \
5077: Exiting.\n",lval,linei, i,line,j);
1.141 brouard 5078: fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136 brouard 5079: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5080: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5081: For example, for multinomial values like 1, 2 and 3,\n \
5082: build V1=0 V2=0 for the reference value (1),\n \
5083: V1=1 V2=0 for (2) \n \
5084: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5085: output of IMaCh is often meaningless.\n \
5086: Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
5087: return 1;
5088: }
5089: covar[j][i]=(double)(lval);
5090: strcpy(line,stra);
5091: }
5092: lstra=strlen(stra);
5093:
5094: if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
5095: stratrunc = &(stra[lstra-9]);
5096: num[i]=atol(stratrunc);
5097: }
5098: else
5099: num[i]=atol(stra);
5100: /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
5101: 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;}*/
5102:
5103: i=i+1;
5104: } /* End loop reading data */
1.126 brouard 5105:
1.136 brouard 5106: *imax=i-1; /* Number of individuals */
5107: fclose(fic);
5108:
5109: return (0);
5110: endread:
5111: printf("Exiting readdata: ");
5112: fclose(fic);
5113: return (1);
1.126 brouard 5114:
5115:
5116:
1.136 brouard 5117: }
1.145 brouard 5118: void removespace(char *str) {
5119: char *p1 = str, *p2 = str;
5120: do
5121: while (*p2 == ' ')
5122: p2++;
5123: while (*p1++ = *p2++);
5124: }
5125:
5126: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
5127: * Model V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age
5128: * - cptcovt total number of covariates of the model nbocc(+)+1 = 8
5129: * - cptcovn or number of covariates k of the models excluding age*products =6
5130: * - cptcovage number of covariates with age*products =2
5131: * - cptcovs number of simple covariates
5132: * - 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
5133: * which is a new column after the 9 (ncovcol) variables.
5134: * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
5135: * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
5136: * Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
5137: * - Tvard[k] p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
5138: */
1.136 brouard 5139: {
1.145 brouard 5140: int i, j, k, ks;
1.136 brouard 5141: int i1, j1, k1, k2;
5142: char modelsav[80];
1.145 brouard 5143: char stra[80], strb[80], strc[80], strd[80],stre[80];
1.136 brouard 5144:
1.145 brouard 5145: /*removespace(model);*/
1.136 brouard 5146: if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145 brouard 5147: j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
5148: j=nbocc(model,'+'); /**< j=Number of '+' */
5149: j1=nbocc(model,'*'); /**< j1=Number of '*' */
5150: cptcovs=j+1-j1; /**< Number of simple covariates V1+V2*age+V3 +V3*V4=> V1 + V3 =2 */
5151: cptcovt= j+1; /* Number of total covariates in the model V1 + V2*age+ V3 + V3*V4=> 4*/
5152: /* including age products which are counted in cptcovage.
5153: /* but the covariates which are products must be treated separately: ncovn=4- 2=2 (V1+V3). */
5154: cptcovprod=j1; /**< Number of products V1*V2 +v3*age = 2 */
5155: cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1 */
1.136 brouard 5156: strcpy(modelsav,model);
1.137 brouard 5157: if (strstr(model,"AGE") !=0){
5158: printf("Error. AGE must be in lower case 'age' model=%s ",model);
5159: fprintf(ficlog,"Error. AGE must be in lower case model=%s ",model);fflush(ficlog);
1.136 brouard 5160: return 1;
5161: }
1.141 brouard 5162: if (strstr(model,"v") !=0){
5163: printf("Error. 'v' must be in upper case 'V' model=%s ",model);
5164: fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
5165: return 1;
5166: }
1.136 brouard 5167:
1.145 brouard 5168: /* Design
5169: * V1 V2 V3 V4 V5 V6 V7 V8 V9 Weight
5170: * < ncovcol=8 >
5171: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
5172: * k= 1 2 3 4 5 6 7 8
5173: * cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
5174: * covar[k,i], value of kth covariate if not including age for individual i:
5175: * covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
5176: * Tvar[k] # of the kth covariate: Tvar[1]=2 Tvar[4]=3 Tvar[8]=8
5177: * if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and
5178: * Tage[++cptcovage]=k
5179: * if products, new covar are created after ncovcol with k1
5180: * Tvar[k]=ncovcol+k1; # of the kth covariate product: Tvar[5]=ncovcol+1=10 Tvar[6]=ncovcol+1=11
5181: * Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
5182: * 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
5183: * Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
5184: * Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
5185: * V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
5186: * < ncovcol=8 >
5187: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 d1 d1 d2 d2
5188: * k= 1 2 3 4 5 6 7 8 9 10 11 12
5189: * Tvar[k]= 2 1 3 3 10 11 8 8 5 6 7 8
5190: * p Tvar[1]@12={2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5191: * p Tprod[1]@2={ 6, 5}
5192: *p Tvard[1][1]@4= {7, 8, 5, 6}
5193: * covar[k][i]= V2 V1 ? V3 V5*V6? V7*V8? ? V8
5194: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
5195: *How to reorganize?
5196: * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
5197: * Tvars {2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5198: * {2, 1, 4, 8, 5, 6, 3, 7}
5199: * Struct []
5200: */
5201:
1.136 brouard 5202: /* This loop fills the array Tvar from the string 'model'.*/
5203: /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
1.137 brouard 5204: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 */
5205: /* k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
5206: /* k=3 V4 Tvar[k=3]= 4 (from V4) */
5207: /* k=2 V1 Tvar[k=2]= 1 (from V1) */
5208: /* k=1 Tvar[1]=2 (from V2) */
5209: /* k=5 Tvar[5] */
5210: /* for (k=1; k<=cptcovn;k++) { */
5211: /* cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
5212: /* } */
5213: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.145 brouard 5214: /*
5215: * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
5216: for(k=cptcovt; k>=1;k--) /**< Number of covariates */
5217: Tvar[k]=0;
5218: cptcovage=0;
5219: for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
5220: cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+'
5221: modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */
1.137 brouard 5222: if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
1.136 brouard 5223: /* printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
5224: /*scanf("%d",i);*/
1.145 brouard 5225: if (strchr(strb,'*')) { /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
5226: cutl(strc,strd,strb,'*'); /**< strd*strc Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
5227: if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
5228: /* covar is not filled and then is empty */
1.136 brouard 5229: cptcovprod--;
1.145 brouard 5230: cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
5231: Tvar[k]=atoi(stre); /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2 */
1.136 brouard 5232: cptcovage++; /* Sums the number of covariates which include age as a product */
1.137 brouard 5233: Tage[cptcovage]=k; /* Tage[1] = 4 */
1.136 brouard 5234: /*printf("stre=%s ", stre);*/
1.137 brouard 5235: } else if (strcmp(strd,"age")==0) { /* or age*Vn */
1.136 brouard 5236: cptcovprod--;
1.145 brouard 5237: cutl(stre,strb,strc,'V');
1.136 brouard 5238: Tvar[k]=atoi(stre);
5239: cptcovage++;
5240: Tage[cptcovage]=k;
1.137 brouard 5241: } else { /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2 strb=V3*V2*/
5242: /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
1.145 brouard 5243: cptcovn++;
5244: cptcovprodnoage++;k1++;
5245: cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
5246: Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
1.137 brouard 5247: because this model-covariate is a construction we invent a new column
5248: ncovcol + k1
5249: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
5250: Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
1.145 brouard 5251: cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
1.137 brouard 5252: Tprod[k1]=k; /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 */
1.145 brouard 5253: Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
5254: Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
5255: k2=k2+2;
5256: Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
5257: Tvar[cptcovt+k2+1]=Tvard[k1][2]; /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
1.137 brouard 5258: for (i=1; i<=lastobs;i++){
5259: /* Computes the new covariate which is a product of
1.145 brouard 5260: covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
1.136 brouard 5261: covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
1.137 brouard 5262: }
5263: } /* End age is not in the model */
5264: } /* End if model includes a product */
1.136 brouard 5265: else { /* no more sum */
5266: /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
5267: /* scanf("%d",i);*/
1.145 brouard 5268: cutl(strd,strc,strb,'V');
5269: ks++; /**< Number of simple covariates */
5270: cptcovn++;
5271: Tvar[k]=atoi(strd);
1.136 brouard 5272: }
1.137 brouard 5273: strcpy(modelsav,stra); /* modelsav=V2+V1+V4 stra=V2+V1+V4 */
1.136 brouard 5274: /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
5275: scanf("%d",i);*/
5276: } /* end of loop + */
5277: } /* end model */
5278:
5279: /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
5280: If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
5281:
5282: /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
5283: printf("cptcovprod=%d ", cptcovprod);
5284: fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
5285:
5286: scanf("%d ",i);*/
5287:
5288:
1.137 brouard 5289: return (0); /* with covar[new additional covariate if product] and Tage if age */
1.136 brouard 5290: endread:
5291: printf("Exiting decodemodel: ");
5292: return (1);
5293: }
5294:
5295: calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
5296: {
5297: int i, m;
5298:
5299: for (i=1; i<=imx; i++) {
5300: for(m=2; (m<= maxwav); m++) {
5301: if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
5302: anint[m][i]=9999;
5303: s[m][i]=-1;
5304: }
5305: if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
5306: *nberr++;
5307: 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);
5308: 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);
5309: s[m][i]=-1;
5310: }
5311: if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
5312: *nberr++;
5313: 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]);
5314: 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]);
5315: s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
5316: }
5317: }
5318: }
5319:
5320: for (i=1; i<=imx; i++) {
5321: agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
5322: for(m=firstpass; (m<= lastpass); m++){
5323: if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
5324: if (s[m][i] >= nlstate+1) {
5325: if(agedc[i]>0)
5326: if((int)moisdc[i]!=99 && (int)andc[i]!=9999)
5327: agev[m][i]=agedc[i];
5328: /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
5329: else {
5330: if ((int)andc[i]!=9999){
5331: nbwarn++;
5332: printf("Warning negative age at death: %ld line:%d\n",num[i],i);
5333: fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
5334: agev[m][i]=-1;
5335: }
5336: }
5337: }
5338: else if(s[m][i] !=9){ /* Standard case, age in fractional
5339: years but with the precision of a month */
5340: agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
5341: if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
5342: agev[m][i]=1;
5343: else if(agev[m][i] < *agemin){
5344: *agemin=agev[m][i];
5345: printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
5346: }
5347: else if(agev[m][i] >*agemax){
5348: *agemax=agev[m][i];
1.156 brouard 5349: /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136 brouard 5350: }
5351: /*agev[m][i]=anint[m][i]-annais[i];*/
5352: /* agev[m][i] = age[i]+2*m;*/
5353: }
5354: else { /* =9 */
5355: agev[m][i]=1;
5356: s[m][i]=-1;
5357: }
5358: }
5359: else /*= 0 Unknown */
5360: agev[m][i]=1;
5361: }
5362:
5363: }
5364: for (i=1; i<=imx; i++) {
5365: for(m=firstpass; (m<=lastpass); m++){
5366: if (s[m][i] > (nlstate+ndeath)) {
5367: *nberr++;
5368: 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);
5369: 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);
5370: return 1;
5371: }
5372: }
5373: }
5374:
5375: /*for (i=1; i<=imx; i++){
5376: for (m=firstpass; (m<lastpass); m++){
5377: printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
5378: }
5379:
5380: }*/
5381:
5382:
1.139 brouard 5383: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
5384: fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
1.136 brouard 5385:
5386: return (0);
5387: endread:
5388: printf("Exiting calandcheckages: ");
5389: return (1);
5390: }
5391:
5392:
5393: /***********************************************/
5394: /**************** Main Program *****************/
5395: /***********************************************/
5396:
5397: int main(int argc, char *argv[])
5398: {
5399: #ifdef GSL
5400: const gsl_multimin_fminimizer_type *T;
5401: size_t iteri = 0, it;
5402: int rval = GSL_CONTINUE;
5403: int status = GSL_SUCCESS;
5404: double ssval;
5405: #endif
5406: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
5407: int i,j, k, n=MAXN,iter,m,size=100,cptcode, cptcod;
5408: int linei, month, year,iout;
5409: int jj, ll, li, lj, lk, imk;
5410: int numlinepar=0; /* Current linenumber of parameter file */
5411: int itimes;
5412: int NDIM=2;
5413: int vpopbased=0;
5414:
5415: char ca[32], cb[32], cc[32];
5416: /* FILE *fichtm; *//* Html File */
5417: /* FILE *ficgp;*/ /*Gnuplot File */
5418: struct stat info;
5419: double agedeb, agefin,hf;
5420: double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
5421:
5422: double fret;
5423: double **xi,tmp,delta;
5424:
5425: double dum; /* Dummy variable */
5426: double ***p3mat;
5427: double ***mobaverage;
5428: int *indx;
5429: char line[MAXLINE], linepar[MAXLINE];
5430: char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
5431: char pathr[MAXLINE], pathimach[MAXLINE];
5432: char **bp, *tok, *val; /* pathtot */
5433: int firstobs=1, lastobs=10;
5434: int sdeb, sfin; /* Status at beginning and end */
5435: int c, h , cpt,l;
5436: int ju,jl, mi;
5437: int i1,j1, jk,aa,bb, stepsize, ij;
5438: int jnais,jdc,jint4,jint1,jint2,jint3,*tab;
5439: int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
5440: int mobilav=0,popforecast=0;
5441: int hstepm, nhstepm;
5442: int agemortsup;
5443: float sumlpop=0.;
5444: double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
5445: double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
5446:
5447: double bage, fage, age, agelim, agebase;
5448: double ftolpl=FTOL;
5449: double **prlim;
5450: double ***param; /* Matrix of parameters */
5451: double *p;
5452: double **matcov; /* Matrix of covariance */
5453: double ***delti3; /* Scale */
5454: double *delti; /* Scale */
5455: double ***eij, ***vareij;
5456: double **varpl; /* Variances of prevalence limits by age */
5457: double *epj, vepp;
5458: double kk1, kk2;
5459: double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
5460: double **ximort;
1.145 brouard 5461: char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136 brouard 5462: int *dcwave;
5463:
5464: char z[1]="c", occ;
5465:
5466: /*char *strt;*/
5467: char strtend[80];
1.126 brouard 5468:
5469: long total_usecs;
5470:
5471: /* setlocale (LC_ALL, ""); */
5472: /* bindtextdomain (PACKAGE, LOCALEDIR); */
5473: /* textdomain (PACKAGE); */
5474: /* setlocale (LC_CTYPE, ""); */
5475: /* setlocale (LC_MESSAGES, ""); */
5476:
5477: /* gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157 brouard 5478: rstart_time = time(NULL);
5479: /* (void) gettimeofday(&start_time,&tzp);*/
5480: start_time = *localtime(&rstart_time);
1.126 brouard 5481: curr_time=start_time;
1.157 brouard 5482: /*tml = *localtime(&start_time.tm_sec);*/
5483: /* strcpy(strstart,asctime(&tml)); */
5484: strcpy(strstart,asctime(&start_time));
1.126 brouard 5485:
5486: /* printf("Localtime (at start)=%s",strstart); */
1.157 brouard 5487: /* tp.tm_sec = tp.tm_sec +86400; */
5488: /* tm = *localtime(&start_time.tm_sec); */
1.126 brouard 5489: /* tmg.tm_year=tmg.tm_year +dsign*dyear; */
5490: /* tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
5491: /* tmg.tm_hour=tmg.tm_hour + 1; */
1.157 brouard 5492: /* tp.tm_sec = mktime(&tmg); */
1.126 brouard 5493: /* strt=asctime(&tmg); */
5494: /* printf("Time(after) =%s",strstart); */
5495: /* (void) time (&time_value);
5496: * printf("time=%d,t-=%d\n",time_value,time_value-86400);
5497: * tm = *localtime(&time_value);
5498: * strstart=asctime(&tm);
5499: * printf("tim_value=%d,asctime=%s\n",time_value,strstart);
5500: */
5501:
5502: nberr=0; /* Number of errors and warnings */
5503: nbwarn=0;
5504: getcwd(pathcd, size);
5505:
5506: printf("\n%s\n%s",version,fullversion);
5507: if(argc <=1){
5508: printf("\nEnter the parameter file name: ");
5509: fgets(pathr,FILENAMELENGTH,stdin);
5510: i=strlen(pathr);
5511: if(pathr[i-1]=='\n')
5512: pathr[i-1]='\0';
1.156 brouard 5513: i=strlen(pathr);
5514: if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
5515: pathr[i-1]='\0';
1.126 brouard 5516: for (tok = pathr; tok != NULL; ){
5517: printf("Pathr |%s|\n",pathr);
5518: while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
5519: printf("val= |%s| pathr=%s\n",val,pathr);
5520: strcpy (pathtot, val);
5521: if(pathr[0] == '\0') break; /* Dirty */
5522: }
5523: }
5524: else{
5525: strcpy(pathtot,argv[1]);
5526: }
5527: /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
5528: /*cygwin_split_path(pathtot,path,optionfile);
5529: printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
5530: /* cutv(path,optionfile,pathtot,'\\');*/
5531:
5532: /* Split argv[0], imach program to get pathimach */
5533: printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
5534: split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
5535: printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
5536: /* strcpy(pathimach,argv[0]); */
5537: /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
5538: split(pathtot,path,optionfile,optionfilext,optionfilefiname);
5539: printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
5540: chdir(path); /* Can be a relative path */
5541: if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
5542: printf("Current directory %s!\n",pathcd);
5543: strcpy(command,"mkdir ");
5544: strcat(command,optionfilefiname);
5545: if((outcmd=system(command)) != 0){
5546: printf("Problem creating directory or it already exists %s%s, err=%d\n",path,optionfilefiname,outcmd);
5547: /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
5548: /* fclose(ficlog); */
5549: /* exit(1); */
5550: }
5551: /* if((imk=mkdir(optionfilefiname))<0){ */
5552: /* perror("mkdir"); */
5553: /* } */
5554:
5555: /*-------- arguments in the command line --------*/
5556:
5557: /* Log file */
5558: strcat(filelog, optionfilefiname);
5559: strcat(filelog,".log"); /* */
5560: if((ficlog=fopen(filelog,"w"))==NULL) {
5561: printf("Problem with logfile %s\n",filelog);
5562: goto end;
5563: }
5564: fprintf(ficlog,"Log filename:%s\n",filelog);
5565: fprintf(ficlog,"\n%s\n%s",version,fullversion);
5566: fprintf(ficlog,"\nEnter the parameter file name: \n");
5567: fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
5568: path=%s \n\
5569: optionfile=%s\n\
5570: optionfilext=%s\n\
1.156 brouard 5571: optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126 brouard 5572:
5573: printf("Local time (at start):%s",strstart);
5574: fprintf(ficlog,"Local time (at start): %s",strstart);
5575: fflush(ficlog);
5576: /* (void) gettimeofday(&curr_time,&tzp); */
1.157 brouard 5577: /* printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126 brouard 5578:
5579: /* */
5580: strcpy(fileres,"r");
5581: strcat(fileres, optionfilefiname);
5582: strcat(fileres,".txt"); /* Other files have txt extension */
5583:
5584: /*---------arguments file --------*/
5585:
5586: if((ficpar=fopen(optionfile,"r"))==NULL) {
1.155 brouard 5587: printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
5588: fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126 brouard 5589: fflush(ficlog);
1.149 brouard 5590: /* goto end; */
5591: exit(70);
1.126 brouard 5592: }
5593:
5594:
5595:
5596: strcpy(filereso,"o");
5597: strcat(filereso,fileres);
5598: if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
5599: printf("Problem with Output resultfile: %s\n", filereso);
5600: fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
5601: fflush(ficlog);
5602: goto end;
5603: }
5604:
5605: /* Reads comments: lines beginning with '#' */
5606: numlinepar=0;
5607: while((c=getc(ficpar))=='#' && c!= EOF){
5608: ungetc(c,ficpar);
5609: fgets(line, MAXLINE, ficpar);
5610: numlinepar++;
1.141 brouard 5611: fputs(line,stdout);
1.126 brouard 5612: fputs(line,ficparo);
5613: fputs(line,ficlog);
5614: }
5615: ungetc(c,ficpar);
5616:
5617: 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);
5618: numlinepar++;
5619: 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);
5620: 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);
5621: 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);
5622: fflush(ficlog);
5623: while((c=getc(ficpar))=='#' && c!= EOF){
5624: ungetc(c,ficpar);
5625: fgets(line, MAXLINE, ficpar);
5626: numlinepar++;
1.141 brouard 5627: fputs(line, stdout);
5628: //puts(line);
1.126 brouard 5629: fputs(line,ficparo);
5630: fputs(line,ficlog);
5631: }
5632: ungetc(c,ficpar);
5633:
5634:
1.145 brouard 5635: covar=matrix(0,NCOVMAX,1,n); /**< used in readdata */
1.136 brouard 5636: cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
5637: /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
5638: v1+v2*age+v2*v3 makes cptcovn = 3
5639: */
5640: if (strlen(model)>1)
1.145 brouard 5641: 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*/
5642: else
5643: ncovmodel=2;
1.126 brouard 5644: nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
1.133 brouard 5645: nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
5646: npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131 brouard 5647: if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
5648: 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);
5649: 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);
5650: fflush(stdout);
5651: fclose (ficlog);
5652: goto end;
5653: }
1.126 brouard 5654: delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5655: delti=delti3[1][1];
5656: /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
5657: if(mle==-1){ /* Print a wizard for help writing covariance matrix */
5658: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
5659: printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
5660: fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
5661: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
5662: fclose (ficparo);
5663: fclose (ficlog);
5664: goto end;
5665: exit(0);
5666: }
5667: else if(mle==-3) {
5668: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
5669: printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
5670: fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
5671: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5672: matcov=matrix(1,npar,1,npar);
5673: }
5674: else{
1.145 brouard 5675: /* Read guessed parameters */
1.126 brouard 5676: /* Reads comments: lines beginning with '#' */
5677: while((c=getc(ficpar))=='#' && c!= EOF){
5678: ungetc(c,ficpar);
5679: fgets(line, MAXLINE, ficpar);
5680: numlinepar++;
1.141 brouard 5681: fputs(line,stdout);
1.126 brouard 5682: fputs(line,ficparo);
5683: fputs(line,ficlog);
5684: }
5685: ungetc(c,ficpar);
5686:
5687: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5688: for(i=1; i <=nlstate; i++){
5689: j=0;
5690: for(jj=1; jj <=nlstate+ndeath; jj++){
5691: if(jj==i) continue;
5692: j++;
5693: fscanf(ficpar,"%1d%1d",&i1,&j1);
5694: if ((i1 != i) && (j1 != j)){
5695: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
5696: It might be a problem of design; if ncovcol and the model are correct\n \
5697: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
5698: exit(1);
5699: }
5700: fprintf(ficparo,"%1d%1d",i1,j1);
5701: if(mle==1)
5702: printf("%1d%1d",i,j);
5703: fprintf(ficlog,"%1d%1d",i,j);
5704: for(k=1; k<=ncovmodel;k++){
5705: fscanf(ficpar," %lf",¶m[i][j][k]);
5706: if(mle==1){
5707: printf(" %lf",param[i][j][k]);
5708: fprintf(ficlog," %lf",param[i][j][k]);
5709: }
5710: else
5711: fprintf(ficlog," %lf",param[i][j][k]);
5712: fprintf(ficparo," %lf",param[i][j][k]);
5713: }
5714: fscanf(ficpar,"\n");
5715: numlinepar++;
5716: if(mle==1)
5717: printf("\n");
5718: fprintf(ficlog,"\n");
5719: fprintf(ficparo,"\n");
5720: }
5721: }
5722: fflush(ficlog);
5723:
1.145 brouard 5724: /* Reads scales values */
1.126 brouard 5725: p=param[1][1];
5726:
5727: /* Reads comments: lines beginning with '#' */
5728: while((c=getc(ficpar))=='#' && c!= EOF){
5729: ungetc(c,ficpar);
5730: fgets(line, MAXLINE, ficpar);
5731: numlinepar++;
1.141 brouard 5732: fputs(line,stdout);
1.126 brouard 5733: fputs(line,ficparo);
5734: fputs(line,ficlog);
5735: }
5736: ungetc(c,ficpar);
5737:
5738: for(i=1; i <=nlstate; i++){
5739: for(j=1; j <=nlstate+ndeath-1; j++){
5740: fscanf(ficpar,"%1d%1d",&i1,&j1);
5741: if ((i1-i)*(j1-j)!=0){
5742: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
5743: exit(1);
5744: }
5745: printf("%1d%1d",i,j);
5746: fprintf(ficparo,"%1d%1d",i1,j1);
5747: fprintf(ficlog,"%1d%1d",i1,j1);
5748: for(k=1; k<=ncovmodel;k++){
5749: fscanf(ficpar,"%le",&delti3[i][j][k]);
5750: printf(" %le",delti3[i][j][k]);
5751: fprintf(ficparo," %le",delti3[i][j][k]);
5752: fprintf(ficlog," %le",delti3[i][j][k]);
5753: }
5754: fscanf(ficpar,"\n");
5755: numlinepar++;
5756: printf("\n");
5757: fprintf(ficparo,"\n");
5758: fprintf(ficlog,"\n");
5759: }
5760: }
5761: fflush(ficlog);
5762:
1.145 brouard 5763: /* Reads covariance matrix */
1.126 brouard 5764: delti=delti3[1][1];
5765:
5766:
5767: /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
5768:
5769: /* Reads comments: lines beginning with '#' */
5770: while((c=getc(ficpar))=='#' && c!= EOF){
5771: ungetc(c,ficpar);
5772: fgets(line, MAXLINE, ficpar);
5773: numlinepar++;
1.141 brouard 5774: fputs(line,stdout);
1.126 brouard 5775: fputs(line,ficparo);
5776: fputs(line,ficlog);
5777: }
5778: ungetc(c,ficpar);
5779:
5780: matcov=matrix(1,npar,1,npar);
1.131 brouard 5781: for(i=1; i <=npar; i++)
5782: for(j=1; j <=npar; j++) matcov[i][j]=0.;
5783:
1.126 brouard 5784: for(i=1; i <=npar; i++){
1.145 brouard 5785: fscanf(ficpar,"%s",str);
1.126 brouard 5786: if(mle==1)
5787: printf("%s",str);
5788: fprintf(ficlog,"%s",str);
5789: fprintf(ficparo,"%s",str);
5790: for(j=1; j <=i; j++){
5791: fscanf(ficpar," %le",&matcov[i][j]);
5792: if(mle==1){
5793: printf(" %.5le",matcov[i][j]);
5794: }
5795: fprintf(ficlog," %.5le",matcov[i][j]);
5796: fprintf(ficparo," %.5le",matcov[i][j]);
5797: }
5798: fscanf(ficpar,"\n");
5799: numlinepar++;
5800: if(mle==1)
5801: printf("\n");
5802: fprintf(ficlog,"\n");
5803: fprintf(ficparo,"\n");
5804: }
5805: for(i=1; i <=npar; i++)
5806: for(j=i+1;j<=npar;j++)
5807: matcov[i][j]=matcov[j][i];
5808:
5809: if(mle==1)
5810: printf("\n");
5811: fprintf(ficlog,"\n");
5812:
5813: fflush(ficlog);
5814:
5815: /*-------- Rewriting parameter file ----------*/
5816: strcpy(rfileres,"r"); /* "Rparameterfile */
5817: strcat(rfileres,optionfilefiname); /* Parameter file first name*/
5818: strcat(rfileres,"."); /* */
5819: strcat(rfileres,optionfilext); /* Other files have txt extension */
5820: if((ficres =fopen(rfileres,"w"))==NULL) {
5821: printf("Problem writing new parameter file: %s\n", fileres);goto end;
5822: fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
5823: }
5824: fprintf(ficres,"#%s\n",version);
5825: } /* End of mle != -3 */
5826:
5827:
5828: n= lastobs;
5829: num=lvector(1,n);
5830: moisnais=vector(1,n);
5831: annais=vector(1,n);
5832: moisdc=vector(1,n);
5833: andc=vector(1,n);
5834: agedc=vector(1,n);
5835: cod=ivector(1,n);
5836: weight=vector(1,n);
5837: for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
5838: mint=matrix(1,maxwav,1,n);
5839: anint=matrix(1,maxwav,1,n);
1.131 brouard 5840: s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */
1.126 brouard 5841: tab=ivector(1,NCOVMAX);
1.144 brouard 5842: ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.126 brouard 5843:
1.136 brouard 5844: /* Reads data from file datafile */
5845: if (readdata(datafile, firstobs, lastobs, &imx)==1)
5846: goto end;
5847:
5848: /* Calculation of the number of parameters from char model */
1.137 brouard 5849: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4
5850: k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
5851: k=3 V4 Tvar[k=3]= 4 (from V4)
5852: k=2 V1 Tvar[k=2]= 1 (from V1)
5853: k=1 Tvar[1]=2 (from V2)
5854: */
5855: Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
5856: /* V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs).
5857: For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4,
5858: Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
5859: */
5860: /* For model-covariate k tells which data-covariate to use but
5861: because this model-covariate is a construction we invent a new column
5862: ncovcol + k1
5863: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
5864: Tvar[3=V1*V4]=4+1 etc */
1.145 brouard 5865: Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137 brouard 5866: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
5867: if V2+V1+V1*V4+age*V3+V3*V2 TProd[k1=2]=5 (V3*V2)
5868: */
1.145 brouard 5869: Tvaraff=ivector(1,NCOVMAX); /* Unclear */
5870: 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 5871: * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd.
5872: * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145 brouard 5873: Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137 brouard 5874: 4 covariates (3 plus signs)
5875: Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
5876: */
1.136 brouard 5877:
5878: if(decodemodel(model, lastobs) == 1)
5879: goto end;
5880:
1.137 brouard 5881: if((double)(lastobs-imx)/(double)imx > 1.10){
5882: nbwarn++;
5883: 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);
5884: 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);
5885: }
1.136 brouard 5886: /* if(mle==1){*/
1.137 brouard 5887: if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
5888: for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136 brouard 5889: }
5890:
5891: /*-calculation of age at interview from date of interview and age at death -*/
5892: agev=matrix(1,maxwav,1,imx);
5893:
5894: if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
5895: goto end;
5896:
1.126 brouard 5897:
1.136 brouard 5898: agegomp=(int)agemin;
5899: free_vector(moisnais,1,n);
5900: free_vector(annais,1,n);
1.126 brouard 5901: /* free_matrix(mint,1,maxwav,1,n);
5902: free_matrix(anint,1,maxwav,1,n);*/
5903: free_vector(moisdc,1,n);
5904: free_vector(andc,1,n);
1.145 brouard 5905: /* */
5906:
1.126 brouard 5907: wav=ivector(1,imx);
5908: dh=imatrix(1,lastpass-firstpass+1,1,imx);
5909: bh=imatrix(1,lastpass-firstpass+1,1,imx);
5910: mw=imatrix(1,lastpass-firstpass+1,1,imx);
5911:
5912: /* Concatenates waves */
5913: concatwav(wav, dh, bh, mw, s, agedc, agev, firstpass, lastpass, imx, nlstate, stepm);
1.145 brouard 5914: /* */
5915:
1.126 brouard 5916: /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
5917:
5918: nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
5919: ncodemax[1]=1;
1.145 brouard 5920: Ndum =ivector(-1,NCOVMAX);
5921: if (ncovmodel > 2)
5922: tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
5923:
5924: codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
5925: /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
5926: h=0;
5927:
5928:
5929: /*if (cptcovn > 0) */
1.126 brouard 5930:
1.145 brouard 5931:
1.126 brouard 5932: m=pow(2,cptcoveff);
5933:
1.131 brouard 5934: for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
1.143 brouard 5935: 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 */
5936: for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
5937: 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 5938: h++;
1.141 brouard 5939: if (h>m)
1.136 brouard 5940: h=1;
1.144 brouard 5941: /**< codtab(h,k) k = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.143 brouard 5942: * h 1 2 3 4
5943: *______________________________
5944: * 1 i=1 1 i=1 1 i=1 1 i=1 1
5945: * 2 2 1 1 1
5946: * 3 i=2 1 2 1 1
5947: * 4 2 2 1 1
5948: * 5 i=3 1 i=2 1 2 1
5949: * 6 2 1 2 1
5950: * 7 i=4 1 2 2 1
5951: * 8 2 2 2 1
5952: * 9 i=5 1 i=3 1 i=2 1 1
5953: * 10 2 1 1 1
5954: * 11 i=6 1 2 1 1
5955: * 12 2 2 1 1
5956: * 13 i=7 1 i=4 1 2 1
5957: * 14 2 1 2 1
5958: * 15 i=8 1 2 2 1
5959: * 16 2 2 2 1
5960: */
1.141 brouard 5961: codtab[h][k]=j;
1.145 brouard 5962: /*codtab[h][Tvar[k]]=j;*/
1.130 brouard 5963: 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 5964: }
5965: }
5966: }
5967: }
5968: /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
5969: codtab[1][2]=1;codtab[2][2]=2; */
5970: /* for(i=1; i <=m ;i++){
5971: for(k=1; k <=cptcovn; k++){
1.131 brouard 5972: printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
1.126 brouard 5973: }
5974: printf("\n");
5975: }
5976: scanf("%d",i);*/
1.145 brouard 5977:
5978: free_ivector(Ndum,-1,NCOVMAX);
5979:
5980:
1.126 brouard 5981:
5982: /*------------ gnuplot -------------*/
5983: strcpy(optionfilegnuplot,optionfilefiname);
5984: if(mle==-3)
5985: strcat(optionfilegnuplot,"-mort");
5986: strcat(optionfilegnuplot,".gp");
5987:
5988: if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
5989: printf("Problem with file %s",optionfilegnuplot);
5990: }
5991: else{
5992: fprintf(ficgp,"\n# %s\n", version);
5993: fprintf(ficgp,"# %s\n", optionfilegnuplot);
1.141 brouard 5994: //fprintf(ficgp,"set missing 'NaNq'\n");
5995: fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126 brouard 5996: }
5997: /* fclose(ficgp);*/
5998: /*--------- index.htm --------*/
5999:
6000: strcpy(optionfilehtm,optionfilefiname); /* Main html file */
6001: if(mle==-3)
6002: strcat(optionfilehtm,"-mort");
6003: strcat(optionfilehtm,".htm");
6004: if((fichtm=fopen(optionfilehtm,"w"))==NULL) {
1.131 brouard 6005: printf("Problem with %s \n",optionfilehtm);
6006: exit(0);
1.126 brouard 6007: }
6008:
6009: strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
6010: strcat(optionfilehtmcov,"-cov.htm");
6011: if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL) {
6012: printf("Problem with %s \n",optionfilehtmcov), exit(0);
6013: }
6014: else{
6015: fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6016: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6017: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
6018: optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
6019: }
6020:
6021: fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6022: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6023: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
6024: \n\
6025: <hr size=\"2\" color=\"#EC5E5E\">\
6026: <ul><li><h4>Parameter files</h4>\n\
6027: - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
6028: - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
6029: - Log file of the run: <a href=\"%s\">%s</a><br>\n\
6030: - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
6031: - Date and time at start: %s</ul>\n",\
6032: optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
6033: optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
6034: fileres,fileres,\
6035: filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
6036: fflush(fichtm);
6037:
6038: strcpy(pathr,path);
6039: strcat(pathr,optionfilefiname);
6040: chdir(optionfilefiname); /* Move to directory named optionfile */
6041:
6042: /* Calculates basic frequencies. Computes observed prevalence at single age
6043: and prints on file fileres'p'. */
6044: freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
6045:
6046: fprintf(fichtm,"\n");
6047: fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
6048: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
6049: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
6050: imx,agemin,agemax,jmin,jmax,jmean);
6051: pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6052: oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6053: newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6054: savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6055: oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
6056:
6057:
6058: /* For Powell, parameters are in a vector p[] starting at p[1]
6059: so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
6060: p=param[1][1]; /* *(*(*(param +1)+1)+0) */
6061:
6062: globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
6063:
6064: if (mle==-3){
1.136 brouard 6065: ximort=matrix(1,NDIM,1,NDIM);
6066: /* ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126 brouard 6067: cens=ivector(1,n);
6068: ageexmed=vector(1,n);
6069: agecens=vector(1,n);
6070: dcwave=ivector(1,n);
6071:
6072: for (i=1; i<=imx; i++){
6073: dcwave[i]=-1;
6074: for (m=firstpass; m<=lastpass; m++)
6075: if (s[m][i]>nlstate) {
6076: dcwave[i]=m;
6077: /* printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
6078: break;
6079: }
6080: }
6081:
6082: for (i=1; i<=imx; i++) {
6083: if (wav[i]>0){
6084: ageexmed[i]=agev[mw[1][i]][i];
6085: j=wav[i];
6086: agecens[i]=1.;
6087:
6088: if (ageexmed[i]> 1 && wav[i] > 0){
6089: agecens[i]=agev[mw[j][i]][i];
6090: cens[i]= 1;
6091: }else if (ageexmed[i]< 1)
6092: cens[i]= -1;
6093: if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
6094: cens[i]=0 ;
6095: }
6096: else cens[i]=-1;
6097: }
6098:
6099: for (i=1;i<=NDIM;i++) {
6100: for (j=1;j<=NDIM;j++)
6101: ximort[i][j]=(i == j ? 1.0 : 0.0);
6102: }
6103:
1.145 brouard 6104: /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126 brouard 6105: /*printf("%lf %lf", p[1], p[2]);*/
6106:
6107:
1.136 brouard 6108: #ifdef GSL
6109: printf("GSL optimization\n"); fprintf(ficlog,"Powell\n");
1.162 ! brouard 6110: #else
1.126 brouard 6111: printf("Powell\n"); fprintf(ficlog,"Powell\n");
1.136 brouard 6112: #endif
1.126 brouard 6113: strcpy(filerespow,"pow-mort");
6114: strcat(filerespow,fileres);
6115: if((ficrespow=fopen(filerespow,"w"))==NULL) {
6116: printf("Problem with resultfile: %s\n", filerespow);
6117: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
6118: }
1.136 brouard 6119: #ifdef GSL
6120: fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162 ! brouard 6121: #else
1.126 brouard 6122: fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136 brouard 6123: #endif
1.126 brouard 6124: /* for (i=1;i<=nlstate;i++)
6125: for(j=1;j<=nlstate+ndeath;j++)
6126: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
6127: */
6128: fprintf(ficrespow,"\n");
1.136 brouard 6129: #ifdef GSL
6130: /* gsl starts here */
6131: T = gsl_multimin_fminimizer_nmsimplex;
6132: gsl_multimin_fminimizer *sfm = NULL;
6133: gsl_vector *ss, *x;
6134: gsl_multimin_function minex_func;
6135:
6136: /* Initial vertex size vector */
6137: ss = gsl_vector_alloc (NDIM);
6138:
6139: if (ss == NULL){
6140: GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
6141: }
6142: /* Set all step sizes to 1 */
6143: gsl_vector_set_all (ss, 0.001);
6144:
6145: /* Starting point */
1.126 brouard 6146:
1.136 brouard 6147: x = gsl_vector_alloc (NDIM);
6148:
6149: if (x == NULL){
6150: gsl_vector_free(ss);
6151: GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
6152: }
6153:
6154: /* Initialize method and iterate */
6155: /* p[1]=0.0268; p[NDIM]=0.083; */
6156: /* gsl_vector_set(x, 0, 0.0268); */
6157: /* gsl_vector_set(x, 1, 0.083); */
6158: gsl_vector_set(x, 0, p[1]);
6159: gsl_vector_set(x, 1, p[2]);
6160:
6161: minex_func.f = &gompertz_f;
6162: minex_func.n = NDIM;
6163: minex_func.params = (void *)&p; /* ??? */
6164:
6165: sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
6166: gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
6167:
6168: printf("Iterations beginning .....\n\n");
6169: printf("Iter. # Intercept Slope -Log Likelihood Simplex size\n");
6170:
6171: iteri=0;
6172: while (rval == GSL_CONTINUE){
6173: iteri++;
6174: status = gsl_multimin_fminimizer_iterate(sfm);
6175:
6176: if (status) printf("error: %s\n", gsl_strerror (status));
6177: fflush(0);
6178:
6179: if (status)
6180: break;
6181:
6182: rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
6183: ssval = gsl_multimin_fminimizer_size (sfm);
6184:
6185: if (rval == GSL_SUCCESS)
6186: printf ("converged to a local maximum at\n");
6187:
6188: printf("%5d ", iteri);
6189: for (it = 0; it < NDIM; it++){
6190: printf ("%10.5f ", gsl_vector_get (sfm->x, it));
6191: }
6192: printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
6193: }
6194:
6195: printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
6196:
6197: gsl_vector_free(x); /* initial values */
6198: gsl_vector_free(ss); /* inital step size */
6199: for (it=0; it<NDIM; it++){
6200: p[it+1]=gsl_vector_get(sfm->x,it);
6201: fprintf(ficrespow," %.12lf", p[it]);
6202: }
6203: gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1) */
6204: #endif
6205: #ifdef POWELL
6206: powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
6207: #endif
1.126 brouard 6208: fclose(ficrespow);
6209:
6210: hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);
6211:
6212: for(i=1; i <=NDIM; i++)
6213: for(j=i+1;j<=NDIM;j++)
6214: matcov[i][j]=matcov[j][i];
6215:
6216: printf("\nCovariance matrix\n ");
6217: for(i=1; i <=NDIM; i++) {
6218: for(j=1;j<=NDIM;j++){
6219: printf("%f ",matcov[i][j]);
6220: }
6221: printf("\n ");
6222: }
6223:
6224: printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
6225: for (i=1;i<=NDIM;i++)
6226: printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
6227:
6228: lsurv=vector(1,AGESUP);
6229: lpop=vector(1,AGESUP);
6230: tpop=vector(1,AGESUP);
6231: lsurv[agegomp]=100000;
6232:
6233: for (k=agegomp;k<=AGESUP;k++) {
6234: agemortsup=k;
6235: if (p[1]*exp(p[2]*(k-agegomp))>1) break;
6236: }
6237:
6238: for (k=agegomp;k<agemortsup;k++)
6239: lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
6240:
6241: for (k=agegomp;k<agemortsup;k++){
6242: lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
6243: sumlpop=sumlpop+lpop[k];
6244: }
6245:
6246: tpop[agegomp]=sumlpop;
6247: for (k=agegomp;k<(agemortsup-3);k++){
6248: /* tpop[k+1]=2;*/
6249: tpop[k+1]=tpop[k]-lpop[k];
6250: }
6251:
6252:
6253: printf("\nAge lx qx dx Lx Tx e(x)\n");
6254: for (k=agegomp;k<(agemortsup-2);k++)
6255: 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]);
6256:
6257:
6258: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6259: printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6260:
6261: printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
6262: stepm, weightopt,\
6263: model,imx,p,matcov,agemortsup);
6264:
6265: free_vector(lsurv,1,AGESUP);
6266: free_vector(lpop,1,AGESUP);
6267: free_vector(tpop,1,AGESUP);
1.136 brouard 6268: #ifdef GSL
6269: free_ivector(cens,1,n);
6270: free_vector(agecens,1,n);
6271: free_ivector(dcwave,1,n);
6272: free_matrix(ximort,1,NDIM,1,NDIM);
6273: #endif
1.126 brouard 6274: } /* Endof if mle==-3 */
6275:
6276: else{ /* For mle >=1 */
1.132 brouard 6277: globpr=0;/* debug */
6278: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126 brouard 6279: printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6280: for (k=1; k<=npar;k++)
6281: printf(" %d %8.5f",k,p[k]);
6282: printf("\n");
6283: globpr=1; /* to print the contributions */
6284: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
6285: printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6286: for (k=1; k<=npar;k++)
6287: printf(" %d %8.5f",k,p[k]);
6288: printf("\n");
6289: if(mle>=1){ /* Could be 1 or 2 */
6290: mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
6291: }
6292:
6293: /*--------- results files --------------*/
6294: 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);
6295:
6296:
6297: fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6298: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6299: fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6300: for(i=1,jk=1; i <=nlstate; i++){
6301: for(k=1; k <=(nlstate+ndeath); k++){
6302: if (k != i) {
6303: printf("%d%d ",i,k);
6304: fprintf(ficlog,"%d%d ",i,k);
6305: fprintf(ficres,"%1d%1d ",i,k);
6306: for(j=1; j <=ncovmodel; j++){
6307: printf("%lf ",p[jk]);
6308: fprintf(ficlog,"%lf ",p[jk]);
6309: fprintf(ficres,"%lf ",p[jk]);
6310: jk++;
6311: }
6312: printf("\n");
6313: fprintf(ficlog,"\n");
6314: fprintf(ficres,"\n");
6315: }
6316: }
6317: }
6318: if(mle!=0){
6319: /* Computing hessian and covariance matrix */
6320: ftolhess=ftol; /* Usually correct */
6321: hesscov(matcov, p, npar, delti, ftolhess, func);
6322: }
6323: fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
6324: printf("# Scales (for hessian or gradient estimation)\n");
6325: fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
6326: for(i=1,jk=1; i <=nlstate; i++){
6327: for(j=1; j <=nlstate+ndeath; j++){
6328: if (j!=i) {
6329: fprintf(ficres,"%1d%1d",i,j);
6330: printf("%1d%1d",i,j);
6331: fprintf(ficlog,"%1d%1d",i,j);
6332: for(k=1; k<=ncovmodel;k++){
6333: printf(" %.5e",delti[jk]);
6334: fprintf(ficlog," %.5e",delti[jk]);
6335: fprintf(ficres," %.5e",delti[jk]);
6336: jk++;
6337: }
6338: printf("\n");
6339: fprintf(ficlog,"\n");
6340: fprintf(ficres,"\n");
6341: }
6342: }
6343: }
6344:
6345: 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");
6346: if(mle>=1)
6347: 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");
6348: 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");
6349: /* # 121 Var(a12)\n\ */
6350: /* # 122 Cov(b12,a12) Var(b12)\n\ */
6351: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
6352: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
6353: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
6354: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
6355: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
6356: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
6357:
6358:
6359: /* Just to have a covariance matrix which will be more understandable
6360: even is we still don't want to manage dictionary of variables
6361: */
6362: for(itimes=1;itimes<=2;itimes++){
6363: jj=0;
6364: for(i=1; i <=nlstate; i++){
6365: for(j=1; j <=nlstate+ndeath; j++){
6366: if(j==i) continue;
6367: for(k=1; k<=ncovmodel;k++){
6368: jj++;
6369: ca[0]= k+'a'-1;ca[1]='\0';
6370: if(itimes==1){
6371: if(mle>=1)
6372: printf("#%1d%1d%d",i,j,k);
6373: fprintf(ficlog,"#%1d%1d%d",i,j,k);
6374: fprintf(ficres,"#%1d%1d%d",i,j,k);
6375: }else{
6376: if(mle>=1)
6377: printf("%1d%1d%d",i,j,k);
6378: fprintf(ficlog,"%1d%1d%d",i,j,k);
6379: fprintf(ficres,"%1d%1d%d",i,j,k);
6380: }
6381: ll=0;
6382: for(li=1;li <=nlstate; li++){
6383: for(lj=1;lj <=nlstate+ndeath; lj++){
6384: if(lj==li) continue;
6385: for(lk=1;lk<=ncovmodel;lk++){
6386: ll++;
6387: if(ll<=jj){
6388: cb[0]= lk +'a'-1;cb[1]='\0';
6389: if(ll<jj){
6390: if(itimes==1){
6391: if(mle>=1)
6392: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6393: fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6394: fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6395: }else{
6396: if(mle>=1)
6397: printf(" %.5e",matcov[jj][ll]);
6398: fprintf(ficlog," %.5e",matcov[jj][ll]);
6399: fprintf(ficres," %.5e",matcov[jj][ll]);
6400: }
6401: }else{
6402: if(itimes==1){
6403: if(mle>=1)
6404: printf(" Var(%s%1d%1d)",ca,i,j);
6405: fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
6406: fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
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: }
6414: }
6415: } /* end lk */
6416: } /* end lj */
6417: } /* end li */
6418: if(mle>=1)
6419: printf("\n");
6420: fprintf(ficlog,"\n");
6421: fprintf(ficres,"\n");
6422: numlinepar++;
6423: } /* end k*/
6424: } /*end j */
6425: } /* end i */
6426: } /* end itimes */
6427:
6428: fflush(ficlog);
6429: fflush(ficres);
6430:
6431: while((c=getc(ficpar))=='#' && c!= EOF){
6432: ungetc(c,ficpar);
6433: fgets(line, MAXLINE, ficpar);
1.141 brouard 6434: fputs(line,stdout);
1.126 brouard 6435: fputs(line,ficparo);
6436: }
6437: ungetc(c,ficpar);
6438:
6439: estepm=0;
6440: fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
6441: if (estepm==0 || estepm < stepm) estepm=stepm;
6442: if (fage <= 2) {
6443: bage = ageminpar;
6444: fage = agemaxpar;
6445: }
6446:
6447: fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
6448: fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6449: fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6450:
6451: while((c=getc(ficpar))=='#' && c!= EOF){
6452: ungetc(c,ficpar);
6453: fgets(line, MAXLINE, ficpar);
1.141 brouard 6454: fputs(line,stdout);
1.126 brouard 6455: fputs(line,ficparo);
6456: }
6457: ungetc(c,ficpar);
6458:
6459: 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);
6460: 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);
6461: 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);
6462: printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
6463: 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);
6464:
6465: while((c=getc(ficpar))=='#' && c!= EOF){
6466: ungetc(c,ficpar);
6467: fgets(line, MAXLINE, ficpar);
1.141 brouard 6468: fputs(line,stdout);
1.126 brouard 6469: fputs(line,ficparo);
6470: }
6471: ungetc(c,ficpar);
6472:
6473:
6474: dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
6475: dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
6476:
6477: fscanf(ficpar,"pop_based=%d\n",&popbased);
6478: fprintf(ficparo,"pop_based=%d\n",popbased);
6479: fprintf(ficres,"pop_based=%d\n",popbased);
6480:
6481: while((c=getc(ficpar))=='#' && c!= EOF){
6482: ungetc(c,ficpar);
6483: fgets(line, MAXLINE, ficpar);
1.141 brouard 6484: fputs(line,stdout);
1.126 brouard 6485: fputs(line,ficparo);
6486: }
6487: ungetc(c,ficpar);
6488:
6489: 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);
6490: 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);
6491: 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);
6492: 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);
6493: 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);
6494: /* day and month of proj2 are not used but only year anproj2.*/
6495:
6496:
6497:
1.145 brouard 6498: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
6499: /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126 brouard 6500:
6501: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6502: printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6503:
6504: printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
6505: model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
6506: jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
6507:
6508: /*------------ free_vector -------------*/
6509: /* chdir(path); */
6510:
6511: free_ivector(wav,1,imx);
6512: free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
6513: free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
6514: free_imatrix(mw,1,lastpass-firstpass+1,1,imx);
6515: free_lvector(num,1,n);
6516: free_vector(agedc,1,n);
6517: /*free_matrix(covar,0,NCOVMAX,1,n);*/
6518: /*free_matrix(covar,1,NCOVMAX,1,n);*/
6519: fclose(ficparo);
6520: fclose(ficres);
6521:
6522:
6523: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
1.145 brouard 6524: #include "prevlim.h" /* Use ficrespl, ficlog */
1.126 brouard 6525: fclose(ficrespl);
6526:
1.145 brouard 6527: #ifdef FREEEXIT2
6528: #include "freeexit2.h"
6529: #endif
6530:
1.126 brouard 6531: /*------------- h Pij x at various ages ------------*/
1.145 brouard 6532: #include "hpijx.h"
6533: fclose(ficrespij);
1.126 brouard 6534:
1.145 brouard 6535: /*-------------- Variance of one-step probabilities---*/
6536: k=1;
1.126 brouard 6537: varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
6538:
6539:
6540: probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
6541: for(i=1;i<=AGESUP;i++)
6542: for(j=1;j<=NCOVMAX;j++)
6543: for(k=1;k<=NCOVMAX;k++)
6544: probs[i][j][k]=0.;
6545:
6546: /*---------- Forecasting ------------------*/
6547: /*if((stepm == 1) && (strcmp(model,".")==0)){*/
6548: if(prevfcast==1){
6549: /* if(stepm ==1){*/
6550: prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
6551: /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
6552: /* } */
6553: /* else{ */
6554: /* erreur=108; */
6555: /* 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); */
6556: /* 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); */
6557: /* } */
6558: }
6559:
6560:
1.127 brouard 6561: /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
6562:
6563: prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
6564: /* 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",\
6565: ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
6566: */
1.126 brouard 6567:
1.127 brouard 6568: if (mobilav!=0) {
6569: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
6570: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
6571: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
6572: printf(" Error in movingaverage mobilav=%d\n",mobilav);
6573: }
1.126 brouard 6574: }
6575:
6576:
1.127 brouard 6577: /*---------- Health expectancies, no variances ------------*/
6578:
1.126 brouard 6579: strcpy(filerese,"e");
6580: strcat(filerese,fileres);
6581: if((ficreseij=fopen(filerese,"w"))==NULL) {
6582: printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
6583: fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
6584: }
6585: printf("Computing Health Expectancies: result on file '%s' \n", filerese);
6586: fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
1.145 brouard 6587: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6588: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6589:
6590: for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127 brouard 6591: fprintf(ficreseij,"\n#****** ");
6592: for(j=1;j<=cptcoveff;j++) {
6593: fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6594: }
6595: fprintf(ficreseij,"******\n");
6596:
6597: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6598: oldm=oldms;savm=savms;
6599: evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);
6600:
6601: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145 brouard 6602: /*}*/
1.127 brouard 6603: }
6604: fclose(ficreseij);
6605:
6606:
6607: /*---------- Health expectancies and variances ------------*/
6608:
6609:
6610: strcpy(filerest,"t");
6611: strcat(filerest,fileres);
6612: if((ficrest=fopen(filerest,"w"))==NULL) {
6613: printf("Problem with total LE resultfile: %s\n", filerest);goto end;
6614: fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
6615: }
6616: printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
6617: fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
6618:
1.126 brouard 6619:
6620: strcpy(fileresstde,"stde");
6621: strcat(fileresstde,fileres);
6622: if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
6623: printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
6624: fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
6625: }
6626: printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
6627: fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
6628:
6629: strcpy(filerescve,"cve");
6630: strcat(filerescve,fileres);
6631: if((ficrescveij=fopen(filerescve,"w"))==NULL) {
6632: printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
6633: fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
6634: }
6635: printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
6636: fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
6637:
6638: strcpy(fileresv,"v");
6639: strcat(fileresv,fileres);
6640: if((ficresvij=fopen(fileresv,"w"))==NULL) {
6641: printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
6642: fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
6643: }
6644: printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
6645: fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
6646:
1.145 brouard 6647: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6648: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6649:
6650: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6651: fprintf(ficrest,"\n#****** ");
1.126 brouard 6652: for(j=1;j<=cptcoveff;j++)
6653: fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6654: fprintf(ficrest,"******\n");
6655:
6656: fprintf(ficresstdeij,"\n#****** ");
6657: fprintf(ficrescveij,"\n#****** ");
6658: for(j=1;j<=cptcoveff;j++) {
6659: fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6660: fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6661: }
6662: fprintf(ficresstdeij,"******\n");
6663: fprintf(ficrescveij,"******\n");
6664:
6665: fprintf(ficresvij,"\n#****** ");
6666: for(j=1;j<=cptcoveff;j++)
6667: fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6668: fprintf(ficresvij,"******\n");
6669:
6670: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6671: oldm=oldms;savm=savms;
1.127 brouard 6672: cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
1.145 brouard 6673: /*
6674: */
6675: /* goto endfree; */
1.126 brouard 6676:
6677: vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6678: pstamp(ficrest);
1.145 brouard 6679:
6680:
1.128 brouard 6681: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.145 brouard 6682: oldm=oldms;savm=savms; /* Segmentation fault */
1.161 brouard 6683: cptcod= 0; /* To be deleted */
6684: 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 6685: 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 6686: if(vpopbased==1)
6687: 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);
6688: else
6689: fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
6690: fprintf(ficrest,"# Age e.. (std) ");
6691: for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
6692: fprintf(ficrest,"\n");
1.126 brouard 6693:
1.128 brouard 6694: epj=vector(1,nlstate+1);
6695: for(age=bage; age <=fage ;age++){
6696: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
6697: if (vpopbased==1) {
6698: if(mobilav ==0){
6699: for(i=1; i<=nlstate;i++)
6700: prlim[i][i]=probs[(int)age][i][k];
6701: }else{ /* mobilav */
6702: for(i=1; i<=nlstate;i++)
6703: prlim[i][i]=mobaverage[(int)age][i][k];
6704: }
1.126 brouard 6705: }
6706:
1.128 brouard 6707: fprintf(ficrest," %4.0f",age);
6708: for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
6709: for(i=1, epj[j]=0.;i <=nlstate;i++) {
6710: epj[j] += prlim[i][i]*eij[i][j][(int)age];
6711: /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
6712: }
6713: epj[nlstate+1] +=epj[j];
1.126 brouard 6714: }
6715:
1.128 brouard 6716: for(i=1, vepp=0.;i <=nlstate;i++)
6717: for(j=1;j <=nlstate;j++)
6718: vepp += vareij[i][j][(int)age];
6719: fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
6720: for(j=1;j <=nlstate;j++){
6721: fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
6722: }
6723: fprintf(ficrest,"\n");
1.126 brouard 6724: }
6725: }
6726: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
6727: free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
6728: free_vector(epj,1,nlstate+1);
1.145 brouard 6729: /*}*/
1.126 brouard 6730: }
6731: free_vector(weight,1,n);
1.145 brouard 6732: free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126 brouard 6733: free_imatrix(s,1,maxwav+1,1,n);
6734: free_matrix(anint,1,maxwav,1,n);
6735: free_matrix(mint,1,maxwav,1,n);
6736: free_ivector(cod,1,n);
6737: free_ivector(tab,1,NCOVMAX);
6738: fclose(ficresstdeij);
6739: fclose(ficrescveij);
6740: fclose(ficresvij);
6741: fclose(ficrest);
6742: fclose(ficpar);
6743:
6744: /*------- Variance of period (stable) prevalence------*/
6745:
6746: strcpy(fileresvpl,"vpl");
6747: strcat(fileresvpl,fileres);
6748: if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
6749: printf("Problem with variance of period (stable) prevalence resultfile: %s\n", fileresvpl);
6750: exit(0);
6751: }
6752: printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
6753:
1.145 brouard 6754: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6755: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6756:
6757: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6758: fprintf(ficresvpl,"\n#****** ");
1.126 brouard 6759: for(j=1;j<=cptcoveff;j++)
6760: fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6761: fprintf(ficresvpl,"******\n");
6762:
6763: varpl=matrix(1,nlstate,(int) bage, (int) fage);
6764: oldm=oldms;savm=savms;
6765: varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
6766: free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145 brouard 6767: /*}*/
1.126 brouard 6768: }
6769:
6770: fclose(ficresvpl);
6771:
6772: /*---------- End : free ----------------*/
6773: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
6774: free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
6775: } /* mle==-3 arrives here for freeing */
1.131 brouard 6776: endfree:
1.141 brouard 6777: free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126 brouard 6778: free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
6779: free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
6780: free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
6781: free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
6782: free_matrix(covar,0,NCOVMAX,1,n);
6783: free_matrix(matcov,1,npar,1,npar);
6784: /*free_vector(delti,1,npar);*/
6785: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
6786: free_matrix(agev,1,maxwav,1,imx);
6787: free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
6788:
1.145 brouard 6789: free_ivector(ncodemax,1,NCOVMAX);
6790: free_ivector(Tvar,1,NCOVMAX);
6791: free_ivector(Tprod,1,NCOVMAX);
6792: free_ivector(Tvaraff,1,NCOVMAX);
6793: free_ivector(Tage,1,NCOVMAX);
1.126 brouard 6794:
6795: free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
6796: free_imatrix(codtab,1,100,1,10);
6797: fflush(fichtm);
6798: fflush(ficgp);
6799:
6800:
6801: if((nberr >0) || (nbwarn>0)){
6802: printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
6803: fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
6804: }else{
6805: printf("End of Imach\n");
6806: fprintf(ficlog,"End of Imach\n");
6807: }
6808: printf("See log file on %s\n",filelog);
6809: /* gettimeofday(&end_time, (struct timezone*)0);*/ /* after time */
1.157 brouard 6810: /*(void) gettimeofday(&end_time,&tzp);*/
6811: rend_time = time(NULL);
6812: end_time = *localtime(&rend_time);
6813: /* tml = *localtime(&end_time.tm_sec); */
6814: strcpy(strtend,asctime(&end_time));
1.126 brouard 6815: printf("Local time at start %s\nLocal time at end %s",strstart, strtend);
6816: fprintf(ficlog,"Local time at start %s\nLocal time at end %s\n",strstart, strtend);
1.157 brouard 6817: printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126 brouard 6818:
1.157 brouard 6819: printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
6820: fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
6821: fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126 brouard 6822: /* printf("Total time was %d uSec.\n", total_usecs);*/
6823: /* if(fileappend(fichtm,optionfilehtm)){ */
6824: fprintf(fichtm,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
6825: fclose(fichtm);
6826: fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
6827: fclose(fichtmcov);
6828: fclose(ficgp);
6829: fclose(ficlog);
6830: /*------ End -----------*/
6831:
6832:
6833: printf("Before Current directory %s!\n",pathcd);
6834: if(chdir(pathcd) != 0)
6835: printf("Can't move to directory %s!\n",path);
6836: if(getcwd(pathcd,MAXLINE) > 0)
6837: printf("Current directory %s!\n",pathcd);
6838: /*strcat(plotcmd,CHARSEPARATOR);*/
6839: sprintf(plotcmd,"gnuplot");
1.157 brouard 6840: #ifdef _WIN32
1.126 brouard 6841: sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
6842: #endif
6843: if(!stat(plotcmd,&info)){
1.158 brouard 6844: printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 6845: if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158 brouard 6846: printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126 brouard 6847: }else
6848: strcpy(pplotcmd,plotcmd);
1.157 brouard 6849: #ifdef __unix
1.126 brouard 6850: strcpy(plotcmd,GNUPLOTPROGRAM);
6851: if(!stat(plotcmd,&info)){
1.158 brouard 6852: printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 6853: }else
6854: strcpy(pplotcmd,plotcmd);
6855: #endif
6856: }else
6857: strcpy(pplotcmd,plotcmd);
6858:
6859: sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158 brouard 6860: printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126 brouard 6861:
6862: if((outcmd=system(plotcmd)) != 0){
1.158 brouard 6863: printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154 brouard 6864: printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152 brouard 6865: sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150 brouard 6866: if((outcmd=system(plotcmd)) != 0)
1.153 brouard 6867: printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126 brouard 6868: }
1.158 brouard 6869: printf(" Successful, please wait...");
1.126 brouard 6870: while (z[0] != 'q') {
6871: /* chdir(path); */
1.154 brouard 6872: printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126 brouard 6873: scanf("%s",z);
6874: /* if (z[0] == 'c') system("./imach"); */
6875: if (z[0] == 'e') {
1.158 brouard 6876: #ifdef __APPLE__
1.152 brouard 6877: sprintf(pplotcmd, "open %s", optionfilehtm);
1.157 brouard 6878: #elif __linux
6879: sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153 brouard 6880: #else
1.152 brouard 6881: sprintf(pplotcmd, "%s", optionfilehtm);
1.153 brouard 6882: #endif
6883: printf("Starting browser with: %s",pplotcmd);fflush(stdout);
6884: system(pplotcmd);
1.126 brouard 6885: }
6886: else if (z[0] == 'g') system(plotcmd);
6887: else if (z[0] == 'q') exit(0);
6888: }
6889: end:
6890: while (z[0] != 'q') {
6891: printf("\nType q for exiting: ");
6892: scanf("%s",z);
6893: }
6894: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>