1: /* $Id: imach.c,v 1.163 2014/12/16 10:30:11 brouard Exp $
2: $State: Exp $
3: $Log: imach.c,v $
4: Revision 1.163 2014/12/16 10:30:11 brouard
5: * imach.c (Module): Merging 1.61 to 1.162
6:
7: Revision 1.162 2014/09/25 11:43:39 brouard
8: Summary: temporary backup 0.99!
9:
10: Revision 1.1 2014/09/16 11:06:58 brouard
11: Summary: With some code (wrong) for nlopt
12:
13: Author:
14:
15: Revision 1.161 2014/09/15 20:41:41 brouard
16: Summary: Problem with macro SQR on Intel compiler
17:
18: Revision 1.160 2014/09/02 09:24:05 brouard
19: *** empty log message ***
20:
21: Revision 1.159 2014/09/01 10:34:10 brouard
22: Summary: WIN32
23: Author: Brouard
24:
25: Revision 1.158 2014/08/27 17:11:51 brouard
26: *** empty log message ***
27:
28: Revision 1.157 2014/08/27 16:26:55 brouard
29: Summary: Preparing windows Visual studio version
30: Author: Brouard
31:
32: In order to compile on Visual studio, time.h is now correct and time_t
33: and tm struct should be used. difftime should be used but sometimes I
34: just make the differences in raw time format (time(&now).
35: Trying to suppress #ifdef LINUX
36: Add xdg-open for __linux in order to open default browser.
37:
38: Revision 1.156 2014/08/25 20:10:10 brouard
39: *** empty log message ***
40:
41: Revision 1.155 2014/08/25 18:32:34 brouard
42: Summary: New compile, minor changes
43: Author: Brouard
44:
45: Revision 1.154 2014/06/20 17:32:08 brouard
46: Summary: Outputs now all graphs of convergence to period prevalence
47:
48: Revision 1.153 2014/06/20 16:45:46 brouard
49: Summary: If 3 live state, convergence to period prevalence on same graph
50: Author: Brouard
51:
52: Revision 1.152 2014/06/18 17:54:09 brouard
53: Summary: open browser, use gnuplot on same dir than imach if not found in the path
54:
55: Revision 1.151 2014/06/18 16:43:30 brouard
56: *** empty log message ***
57:
58: Revision 1.150 2014/06/18 16:42:35 brouard
59: Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
60: Author: brouard
61:
62: Revision 1.149 2014/06/18 15:51:14 brouard
63: Summary: Some fixes in parameter files errors
64: Author: Nicolas Brouard
65:
66: Revision 1.148 2014/06/17 17:38:48 brouard
67: Summary: Nothing new
68: Author: Brouard
69:
70: Just a new packaging for OS/X version 0.98nS
71:
72: Revision 1.147 2014/06/16 10:33:11 brouard
73: *** empty log message ***
74:
75: Revision 1.146 2014/06/16 10:20:28 brouard
76: Summary: Merge
77: Author: Brouard
78:
79: Merge, before building revised version.
80:
81: Revision 1.145 2014/06/10 21:23:15 brouard
82: Summary: Debugging with valgrind
83: Author: Nicolas Brouard
84:
85: Lot of changes in order to output the results with some covariates
86: After the Edimburgh REVES conference 2014, it seems mandatory to
87: improve the code.
88: No more memory valgrind error but a lot has to be done in order to
89: continue the work of splitting the code into subroutines.
90: Also, decodemodel has been improved. Tricode is still not
91: optimal. nbcode should be improved. Documentation has been added in
92: the source code.
93:
94: Revision 1.143 2014/01/26 09:45:38 brouard
95: Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
96:
97: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
98: (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
99:
100: Revision 1.142 2014/01/26 03:57:36 brouard
101: Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
102:
103: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
104:
105: Revision 1.141 2014/01/26 02:42:01 brouard
106: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
107:
108: Revision 1.140 2011/09/02 10:37:54 brouard
109: Summary: times.h is ok with mingw32 now.
110:
111: Revision 1.139 2010/06/14 07:50:17 brouard
112: After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
113: I remember having already fixed agemin agemax which are pointers now but not cvs saved.
114:
115: Revision 1.138 2010/04/30 18:19:40 brouard
116: *** empty log message ***
117:
118: Revision 1.137 2010/04/29 18:11:38 brouard
119: (Module): Checking covariates for more complex models
120: than V1+V2. A lot of change to be done. Unstable.
121:
122: Revision 1.136 2010/04/26 20:30:53 brouard
123: (Module): merging some libgsl code. Fixing computation
124: of likelione (using inter/intrapolation if mle = 0) in order to
125: get same likelihood as if mle=1.
126: Some cleaning of code and comments added.
127:
128: Revision 1.135 2009/10/29 15:33:14 brouard
129: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
130:
131: Revision 1.134 2009/10/29 13:18:53 brouard
132: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
133:
134: Revision 1.133 2009/07/06 10:21:25 brouard
135: just nforces
136:
137: Revision 1.132 2009/07/06 08:22:05 brouard
138: Many tings
139:
140: Revision 1.131 2009/06/20 16:22:47 brouard
141: Some dimensions resccaled
142:
143: Revision 1.130 2009/05/26 06:44:34 brouard
144: (Module): Max Covariate is now set to 20 instead of 8. A
145: lot of cleaning with variables initialized to 0. Trying to make
146: V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
147:
148: Revision 1.129 2007/08/31 13:49:27 lievre
149: Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
150:
151: Revision 1.128 2006/06/30 13:02:05 brouard
152: (Module): Clarifications on computing e.j
153:
154: Revision 1.127 2006/04/28 18:11:50 brouard
155: (Module): Yes the sum of survivors was wrong since
156: imach-114 because nhstepm was no more computed in the age
157: loop. Now we define nhstepma in the age loop.
158: (Module): In order to speed up (in case of numerous covariates) we
159: compute health expectancies (without variances) in a first step
160: and then all the health expectancies with variances or standard
161: deviation (needs data from the Hessian matrices) which slows the
162: computation.
163: In the future we should be able to stop the program is only health
164: expectancies and graph are needed without standard deviations.
165:
166: Revision 1.126 2006/04/28 17:23:28 brouard
167: (Module): Yes the sum of survivors was wrong since
168: imach-114 because nhstepm was no more computed in the age
169: loop. Now we define nhstepma in the age loop.
170: Version 0.98h
171:
172: Revision 1.125 2006/04/04 15:20:31 lievre
173: Errors in calculation of health expectancies. Age was not initialized.
174: Forecasting file added.
175:
176: Revision 1.124 2006/03/22 17:13:53 lievre
177: Parameters are printed with %lf instead of %f (more numbers after the comma).
178: The log-likelihood is printed in the log file
179:
180: Revision 1.123 2006/03/20 10:52:43 brouard
181: * imach.c (Module): <title> changed, corresponds to .htm file
182: name. <head> headers where missing.
183:
184: * imach.c (Module): Weights can have a decimal point as for
185: English (a comma might work with a correct LC_NUMERIC environment,
186: otherwise the weight is truncated).
187: Modification of warning when the covariates values are not 0 or
188: 1.
189: Version 0.98g
190:
191: Revision 1.122 2006/03/20 09:45:41 brouard
192: (Module): Weights can have a decimal point as for
193: English (a comma might work with a correct LC_NUMERIC environment,
194: otherwise the weight is truncated).
195: Modification of warning when the covariates values are not 0 or
196: 1.
197: Version 0.98g
198:
199: Revision 1.121 2006/03/16 17:45:01 lievre
200: * imach.c (Module): Comments concerning covariates added
201:
202: * imach.c (Module): refinements in the computation of lli if
203: status=-2 in order to have more reliable computation if stepm is
204: not 1 month. Version 0.98f
205:
206: Revision 1.120 2006/03/16 15:10:38 lievre
207: (Module): refinements in the computation of lli if
208: status=-2 in order to have more reliable computation if stepm is
209: not 1 month. Version 0.98f
210:
211: Revision 1.119 2006/03/15 17:42:26 brouard
212: (Module): Bug if status = -2, the loglikelihood was
213: computed as likelihood omitting the logarithm. Version O.98e
214:
215: Revision 1.118 2006/03/14 18:20:07 brouard
216: (Module): varevsij Comments added explaining the second
217: table of variances if popbased=1 .
218: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
219: (Module): Function pstamp added
220: (Module): Version 0.98d
221:
222: Revision 1.117 2006/03/14 17:16:22 brouard
223: (Module): varevsij Comments added explaining the second
224: table of variances if popbased=1 .
225: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
226: (Module): Function pstamp added
227: (Module): Version 0.98d
228:
229: Revision 1.116 2006/03/06 10:29:27 brouard
230: (Module): Variance-covariance wrong links and
231: varian-covariance of ej. is needed (Saito).
232:
233: Revision 1.115 2006/02/27 12:17:45 brouard
234: (Module): One freematrix added in mlikeli! 0.98c
235:
236: Revision 1.114 2006/02/26 12:57:58 brouard
237: (Module): Some improvements in processing parameter
238: filename with strsep.
239:
240: Revision 1.113 2006/02/24 14:20:24 brouard
241: (Module): Memory leaks checks with valgrind and:
242: datafile was not closed, some imatrix were not freed and on matrix
243: allocation too.
244:
245: Revision 1.112 2006/01/30 09:55:26 brouard
246: (Module): Back to gnuplot.exe instead of wgnuplot.exe
247:
248: Revision 1.111 2006/01/25 20:38:18 brouard
249: (Module): Lots of cleaning and bugs added (Gompertz)
250: (Module): Comments can be added in data file. Missing date values
251: can be a simple dot '.'.
252:
253: Revision 1.110 2006/01/25 00:51:50 brouard
254: (Module): Lots of cleaning and bugs added (Gompertz)
255:
256: Revision 1.109 2006/01/24 19:37:15 brouard
257: (Module): Comments (lines starting with a #) are allowed in data.
258:
259: Revision 1.108 2006/01/19 18:05:42 lievre
260: Gnuplot problem appeared...
261: To be fixed
262:
263: Revision 1.107 2006/01/19 16:20:37 brouard
264: Test existence of gnuplot in imach path
265:
266: Revision 1.106 2006/01/19 13:24:36 brouard
267: Some cleaning and links added in html output
268:
269: Revision 1.105 2006/01/05 20:23:19 lievre
270: *** empty log message ***
271:
272: Revision 1.104 2005/09/30 16:11:43 lievre
273: (Module): sump fixed, loop imx fixed, and simplifications.
274: (Module): If the status is missing at the last wave but we know
275: that the person is alive, then we can code his/her status as -2
276: (instead of missing=-1 in earlier versions) and his/her
277: contributions to the likelihood is 1 - Prob of dying from last
278: health status (= 1-p13= p11+p12 in the easiest case of somebody in
279: the healthy state at last known wave). Version is 0.98
280:
281: Revision 1.103 2005/09/30 15:54:49 lievre
282: (Module): sump fixed, loop imx fixed, and simplifications.
283:
284: Revision 1.102 2004/09/15 17:31:30 brouard
285: Add the possibility to read data file including tab characters.
286:
287: Revision 1.101 2004/09/15 10:38:38 brouard
288: Fix on curr_time
289:
290: Revision 1.100 2004/07/12 18:29:06 brouard
291: Add version for Mac OS X. Just define UNIX in Makefile
292:
293: Revision 1.99 2004/06/05 08:57:40 brouard
294: *** empty log message ***
295:
296: Revision 1.98 2004/05/16 15:05:56 brouard
297: New version 0.97 . First attempt to estimate force of mortality
298: directly from the data i.e. without the need of knowing the health
299: state at each age, but using a Gompertz model: log u =a + b*age .
300: This is the basic analysis of mortality and should be done before any
301: other analysis, in order to test if the mortality estimated from the
302: cross-longitudinal survey is different from the mortality estimated
303: from other sources like vital statistic data.
304:
305: The same imach parameter file can be used but the option for mle should be -3.
306:
307: Agnès, who wrote this part of the code, tried to keep most of the
308: former routines in order to include the new code within the former code.
309:
310: The output is very simple: only an estimate of the intercept and of
311: the slope with 95% confident intervals.
312:
313: Current limitations:
314: A) Even if you enter covariates, i.e. with the
315: model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
316: B) There is no computation of Life Expectancy nor Life Table.
317:
318: Revision 1.97 2004/02/20 13:25:42 lievre
319: Version 0.96d. Population forecasting command line is (temporarily)
320: suppressed.
321:
322: Revision 1.96 2003/07/15 15:38:55 brouard
323: * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
324: rewritten within the same printf. Workaround: many printfs.
325:
326: Revision 1.95 2003/07/08 07:54:34 brouard
327: * imach.c (Repository):
328: (Repository): Using imachwizard code to output a more meaningful covariance
329: matrix (cov(a12,c31) instead of numbers.
330:
331: Revision 1.94 2003/06/27 13:00:02 brouard
332: Just cleaning
333:
334: Revision 1.93 2003/06/25 16:33:55 brouard
335: (Module): On windows (cygwin) function asctime_r doesn't
336: exist so I changed back to asctime which exists.
337: (Module): Version 0.96b
338:
339: Revision 1.92 2003/06/25 16:30:45 brouard
340: (Module): On windows (cygwin) function asctime_r doesn't
341: exist so I changed back to asctime which exists.
342:
343: Revision 1.91 2003/06/25 15:30:29 brouard
344: * imach.c (Repository): Duplicated warning errors corrected.
345: (Repository): Elapsed time after each iteration is now output. It
346: helps to forecast when convergence will be reached. Elapsed time
347: is stamped in powell. We created a new html file for the graphs
348: concerning matrix of covariance. It has extension -cov.htm.
349:
350: Revision 1.90 2003/06/24 12:34:15 brouard
351: (Module): Some bugs corrected for windows. Also, when
352: mle=-1 a template is output in file "or"mypar.txt with the design
353: of the covariance matrix to be input.
354:
355: Revision 1.89 2003/06/24 12:30:52 brouard
356: (Module): Some bugs corrected for windows. Also, when
357: mle=-1 a template is output in file "or"mypar.txt with the design
358: of the covariance matrix to be input.
359:
360: Revision 1.88 2003/06/23 17:54:56 brouard
361: * 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.
362:
363: Revision 1.87 2003/06/18 12:26:01 brouard
364: Version 0.96
365:
366: Revision 1.86 2003/06/17 20:04:08 brouard
367: (Module): Change position of html and gnuplot routines and added
368: routine fileappend.
369:
370: Revision 1.85 2003/06/17 13:12:43 brouard
371: * imach.c (Repository): Check when date of death was earlier that
372: current date of interview. It may happen when the death was just
373: prior to the death. In this case, dh was negative and likelihood
374: was wrong (infinity). We still send an "Error" but patch by
375: assuming that the date of death was just one stepm after the
376: interview.
377: (Repository): Because some people have very long ID (first column)
378: we changed int to long in num[] and we added a new lvector for
379: memory allocation. But we also truncated to 8 characters (left
380: truncation)
381: (Repository): No more line truncation errors.
382:
383: Revision 1.84 2003/06/13 21:44:43 brouard
384: * imach.c (Repository): Replace "freqsummary" at a correct
385: place. It differs from routine "prevalence" which may be called
386: many times. Probs is memory consuming and must be used with
387: parcimony.
388: Version 0.95a3 (should output exactly the same maximization than 0.8a2)
389:
390: Revision 1.83 2003/06/10 13:39:11 lievre
391: *** empty log message ***
392:
393: Revision 1.82 2003/06/05 15:57:20 brouard
394: Add log in imach.c and fullversion number is now printed.
395:
396: */
397: /*
398: Interpolated Markov Chain
399:
400: Short summary of the programme:
401:
402: This program computes Healthy Life Expectancies from
403: cross-longitudinal data. Cross-longitudinal data consist in: -1- a
404: first survey ("cross") where individuals from different ages are
405: interviewed on their health status or degree of disability (in the
406: case of a health survey which is our main interest) -2- at least a
407: second wave of interviews ("longitudinal") which measure each change
408: (if any) in individual health status. Health expectancies are
409: computed from the time spent in each health state according to a
410: model. More health states you consider, more time is necessary to reach the
411: Maximum Likelihood of the parameters involved in the model. The
412: simplest model is the multinomial logistic model where pij is the
413: probability to be observed in state j at the second wave
414: conditional to be observed in state i at the first wave. Therefore
415: the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
416: 'age' is age and 'sex' is a covariate. If you want to have a more
417: complex model than "constant and age", you should modify the program
418: where the markup *Covariates have to be included here again* invites
419: you to do it. More covariates you add, slower the
420: convergence.
421:
422: The advantage of this computer programme, compared to a simple
423: multinomial logistic model, is clear when the delay between waves is not
424: identical for each individual. Also, if a individual missed an
425: intermediate interview, the information is lost, but taken into
426: account using an interpolation or extrapolation.
427:
428: hPijx is the probability to be observed in state i at age x+h
429: conditional to the observed state i at age x. The delay 'h' can be
430: split into an exact number (nh*stepm) of unobserved intermediate
431: states. This elementary transition (by month, quarter,
432: semester or year) is modelled as a multinomial logistic. The hPx
433: matrix is simply the matrix product of nh*stepm elementary matrices
434: and the contribution of each individual to the likelihood is simply
435: hPijx.
436:
437: Also this programme outputs the covariance matrix of the parameters but also
438: of the life expectancies. It also computes the period (stable) prevalence.
439:
440: Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
441: Institut national d'études démographiques, Paris.
442: This software have been partly granted by Euro-REVES, a concerted action
443: from the European Union.
444: It is copyrighted identically to a GNU software product, ie programme and
445: software can be distributed freely for non commercial use. Latest version
446: can be accessed at http://euroreves.ined.fr/imach .
447:
448: Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
449: or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
450:
451: **********************************************************************/
452: /*
453: main
454: read parameterfile
455: read datafile
456: concatwav
457: freqsummary
458: if (mle >= 1)
459: mlikeli
460: print results files
461: if mle==1
462: computes hessian
463: read end of parameter file: agemin, agemax, bage, fage, estepm
464: begin-prev-date,...
465: open gnuplot file
466: open html file
467: period (stable) prevalence | pl_nom 1-1 2-2 etc by covariate
468: for age prevalim() | #****** V1=0 V2=1 V3=1 V4=0 ******
469: | 65 1 0 2 1 3 1 4 0 0.96326 0.03674
470: freexexit2 possible for memory heap.
471:
472: h Pij x | pij_nom ficrestpij
473: # Cov Agex agex+h hpijx with i,j= 1-1 1-2 1-3 2-1 2-2 2-3
474: 1 85 85 1.00000 0.00000 0.00000 0.00000 1.00000 0.00000
475: 1 85 86 0.68299 0.22291 0.09410 0.71093 0.00000 0.28907
476:
477: 1 65 99 0.00364 0.00322 0.99314 0.00350 0.00310 0.99340
478: 1 65 100 0.00214 0.00204 0.99581 0.00206 0.00196 0.99597
479: variance of p one-step probabilities varprob | prob_nom ficresprob #One-step probabilities and stand. devi in ()
480: Standard deviation of one-step probabilities | probcor_nom ficresprobcor #One-step probabilities and correlation matrix
481: Matrix of variance covariance of one-step probabilities | probcov_nom ficresprobcov #One-step probabilities and covariance matrix
482:
483: forecasting if prevfcast==1 prevforecast call prevalence()
484: health expectancies
485: Variance-covariance of DFLE
486: prevalence()
487: movingaverage()
488: varevsij()
489: if popbased==1 varevsij(,popbased)
490: total life expectancies
491: Variance of period (stable) prevalence
492: end
493: */
494:
495:
496:
497:
498: #include <math.h>
499: #include <stdio.h>
500: #include <stdlib.h>
501: #include <string.h>
502:
503: #ifdef _WIN32
504: #include <io.h>
505: #else
506: #include <unistd.h>
507: #endif
508:
509: #include <limits.h>
510: #include <sys/types.h>
511: #include <sys/stat.h>
512: #include <errno.h>
513: /* extern int errno; */
514:
515: /* #ifdef LINUX */
516: /* #include <time.h> */
517: /* #include "timeval.h" */
518: /* #else */
519: /* #include <sys/time.h> */
520: /* #endif */
521:
522: #include <time.h>
523:
524: #ifdef GSL
525: #include <gsl/gsl_errno.h>
526: #include <gsl/gsl_multimin.h>
527: #endif
528:
529: #ifdef NLOPT
530: #include <nlopt.h>
531: typedef struct {
532: double (* function)(double [] );
533: } myfunc_data ;
534: #endif
535:
536: /* #include <libintl.h> */
537: /* #define _(String) gettext (String) */
538:
539: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
540:
541: #define GNUPLOTPROGRAM "gnuplot"
542: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
543: #define FILENAMELENGTH 132
544:
545: #define GLOCK_ERROR_NOPATH -1 /* empty path */
546: #define GLOCK_ERROR_GETCWD -2 /* cannot get cwd */
547:
548: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
549: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
550:
551: #define NINTERVMAX 8
552: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
553: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
554: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
555: #define codtabm(h,k) 1 & (h-1) >> (k-1) ;
556: #define MAXN 20000
557: #define YEARM 12. /**< Number of months per year */
558: #define AGESUP 130
559: #define AGEBASE 40
560: #define AGEGOMP 10. /**< Minimal age for Gompertz adjustment */
561: #ifdef _WIN32
562: #define DIRSEPARATOR '\\'
563: #define CHARSEPARATOR "\\"
564: #define ODIRSEPARATOR '/'
565: #else
566: #define DIRSEPARATOR '/'
567: #define CHARSEPARATOR "/"
568: #define ODIRSEPARATOR '\\'
569: #endif
570:
571: /* $Id: imach.c,v 1.163 2014/12/16 10:30:11 brouard Exp $ */
572: /* $State: Exp $ */
573:
574: 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)";
575: char fullversion[]="$Revision: 1.163 $ $Date: 2014/12/16 10:30:11 $";
576: char strstart[80];
577: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
578: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings */
579: int nvar=0, nforce=0; /* Number of variables, number of forces */
580: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
581: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
582: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
583: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
584: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
585: int cptcovprodnoage=0; /**< Number of covariate products without age */
586: int cptcoveff=0; /* Total number of covariates to vary for printing results */
587: int cptcov=0; /* Working variable */
588: int npar=NPARMAX;
589: int nlstate=2; /* Number of live states */
590: int ndeath=1; /* Number of dead states */
591: int ncovmodel=0, ncovcol=0; /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
592: int popbased=0;
593:
594: int *wav; /* Number of waves for this individuual 0 is possible */
595: int maxwav=0; /* Maxim number of waves */
596: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
597: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */
598: int gipmx=0, gsw=0; /* Global variables on the number of contributions
599: to the likelihood and the sum of weights (done by funcone)*/
600: int mle=1, weightopt=0;
601: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
602: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
603: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
604: * wave mi and wave mi+1 is not an exact multiple of stepm. */
605: int countcallfunc=0; /* Count the number of calls to func */
606: double jmean=1; /* Mean space between 2 waves */
607: double **matprod2(); /* test */
608: double **oldm, **newm, **savm; /* Working pointers to matrices */
609: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
610: /*FILE *fic ; */ /* Used in readdata only */
611: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
612: FILE *ficlog, *ficrespow;
613: int globpr=0; /* Global variable for printing or not */
614: double fretone; /* Only one call to likelihood */
615: long ipmx=0; /* Number of contributions */
616: double sw; /* Sum of weights */
617: char filerespow[FILENAMELENGTH];
618: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
619: FILE *ficresilk;
620: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
621: FILE *ficresprobmorprev;
622: FILE *fichtm, *fichtmcov; /* Html File */
623: FILE *ficreseij;
624: char filerese[FILENAMELENGTH];
625: FILE *ficresstdeij;
626: char fileresstde[FILENAMELENGTH];
627: FILE *ficrescveij;
628: char filerescve[FILENAMELENGTH];
629: FILE *ficresvij;
630: char fileresv[FILENAMELENGTH];
631: FILE *ficresvpl;
632: char fileresvpl[FILENAMELENGTH];
633: char title[MAXLINE];
634: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH], filerespl[FILENAMELENGTH];
635: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
636: char tmpout[FILENAMELENGTH], tmpout2[FILENAMELENGTH];
637: char command[FILENAMELENGTH];
638: int outcmd=0;
639:
640: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
641:
642: char filelog[FILENAMELENGTH]; /* Log file */
643: char filerest[FILENAMELENGTH];
644: char fileregp[FILENAMELENGTH];
645: char popfile[FILENAMELENGTH];
646:
647: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
648:
649: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
650: /* struct timezone tzp; */
651: /* extern int gettimeofday(); */
652: struct tm tml, *gmtime(), *localtime();
653:
654: extern time_t time();
655:
656: struct tm start_time, end_time, curr_time, last_time, forecast_time;
657: time_t rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
658: struct tm tm;
659:
660: char strcurr[80], strfor[80];
661:
662: char *endptr;
663: long lval;
664: double dval;
665:
666: #define NR_END 1
667: #define FREE_ARG char*
668: #define FTOL 1.0e-10
669:
670: #define NRANSI
671: #define ITMAX 200
672:
673: #define TOL 2.0e-4
674:
675: #define CGOLD 0.3819660
676: #define ZEPS 1.0e-10
677: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
678:
679: #define GOLD 1.618034
680: #define GLIMIT 100.0
681: #define TINY 1.0e-20
682:
683: static double maxarg1,maxarg2;
684: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
685: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
686:
687: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
688: #define rint(a) floor(a+0.5)
689:
690: static double sqrarg;
691: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
692: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
693: int agegomp= AGEGOMP;
694:
695: int imx;
696: int stepm=1;
697: /* Stepm, step in month: minimum step interpolation*/
698:
699: int estepm;
700: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
701:
702: int m,nb;
703: long *num;
704: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
705: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
706: double **pmmij, ***probs;
707: double *ageexmed,*agecens;
708: double dateintmean=0;
709:
710: double *weight;
711: int **s; /* Status */
712: double *agedc;
713: double **covar; /**< covar[j,i], value of jth covariate for individual i,
714: * covar=matrix(0,NCOVMAX,1,n);
715: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; */
716: double idx;
717: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
718: int *Ndum; /** Freq of modality (tricode */
719: int **codtab; /**< codtab=imatrix(1,100,1,10); */
720: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
721: double *lsurv, *lpop, *tpop;
722:
723: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
724: double ftolhess; /**< Tolerance for computing hessian */
725:
726: /**************** split *************************/
727: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
728: {
729: /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
730: the name of the file (name), its extension only (ext) and its first part of the name (finame)
731: */
732: char *ss; /* pointer */
733: int l1, l2; /* length counters */
734:
735: l1 = strlen(path ); /* length of path */
736: if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
737: ss= strrchr( path, DIRSEPARATOR ); /* find last / */
738: if ( ss == NULL ) { /* no directory, so determine current directory */
739: strcpy( name, path ); /* we got the fullname name because no directory */
740: /*if(strrchr(path, ODIRSEPARATOR )==NULL)
741: printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
742: /* get current working directory */
743: /* extern char* getcwd ( char *buf , int len);*/
744: if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
745: return( GLOCK_ERROR_GETCWD );
746: }
747: /* got dirc from getcwd*/
748: printf(" DIRC = %s \n",dirc);
749: } else { /* strip direcotry from path */
750: ss++; /* after this, the filename */
751: l2 = strlen( ss ); /* length of filename */
752: if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
753: strcpy( name, ss ); /* save file name */
754: strncpy( dirc, path, l1 - l2 ); /* now the directory */
755: dirc[l1-l2] = 0; /* add zero */
756: printf(" DIRC2 = %s \n",dirc);
757: }
758: /* We add a separator at the end of dirc if not exists */
759: l1 = strlen( dirc ); /* length of directory */
760: if( dirc[l1-1] != DIRSEPARATOR ){
761: dirc[l1] = DIRSEPARATOR;
762: dirc[l1+1] = 0;
763: printf(" DIRC3 = %s \n",dirc);
764: }
765: ss = strrchr( name, '.' ); /* find last / */
766: if (ss >0){
767: ss++;
768: strcpy(ext,ss); /* save extension */
769: l1= strlen( name);
770: l2= strlen(ss)+1;
771: strncpy( finame, name, l1-l2);
772: finame[l1-l2]= 0;
773: }
774:
775: return( 0 ); /* we're done */
776: }
777:
778:
779: /******************************************/
780:
781: void replace_back_to_slash(char *s, char*t)
782: {
783: int i;
784: int lg=0;
785: i=0;
786: lg=strlen(t);
787: for(i=0; i<= lg; i++) {
788: (s[i] = t[i]);
789: if (t[i]== '\\') s[i]='/';
790: }
791: }
792:
793: char *trimbb(char *out, char *in)
794: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
795: char *s;
796: s=out;
797: while (*in != '\0'){
798: while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
799: in++;
800: }
801: *out++ = *in++;
802: }
803: *out='\0';
804: return s;
805: }
806:
807: char *cutl(char *blocc, char *alocc, char *in, char occ)
808: {
809: /* cuts string in into blocc and alocc where blocc ends before first occurence of char 'occ'
810: and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
811: gives blocc="abcdef2ghi" and alocc="j".
812: If occ is not found blocc is null and alocc is equal to in. Returns blocc
813: */
814: char *s, *t;
815: t=in;s=in;
816: while ((*in != occ) && (*in != '\0')){
817: *alocc++ = *in++;
818: }
819: if( *in == occ){
820: *(alocc)='\0';
821: s=++in;
822: }
823:
824: if (s == t) {/* occ not found */
825: *(alocc-(in-s))='\0';
826: in=s;
827: }
828: while ( *in != '\0'){
829: *blocc++ = *in++;
830: }
831:
832: *blocc='\0';
833: return t;
834: }
835: char *cutv(char *blocc, char *alocc, char *in, char occ)
836: {
837: /* cuts string in into blocc and alocc where blocc ends before last occurence of char 'occ'
838: and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
839: gives blocc="abcdef2ghi" and alocc="j".
840: If occ is not found blocc is null and alocc is equal to in. Returns alocc
841: */
842: char *s, *t;
843: t=in;s=in;
844: while (*in != '\0'){
845: while( *in == occ){
846: *blocc++ = *in++;
847: s=in;
848: }
849: *blocc++ = *in++;
850: }
851: if (s == t) /* occ not found */
852: *(blocc-(in-s))='\0';
853: else
854: *(blocc-(in-s)-1)='\0';
855: in=s;
856: while ( *in != '\0'){
857: *alocc++ = *in++;
858: }
859:
860: *alocc='\0';
861: return s;
862: }
863:
864: int nbocc(char *s, char occ)
865: {
866: int i,j=0;
867: int lg=20;
868: i=0;
869: lg=strlen(s);
870: for(i=0; i<= lg; i++) {
871: if (s[i] == occ ) j++;
872: }
873: return j;
874: }
875:
876: /* void cutv(char *u,char *v, char*t, char occ) */
877: /* { */
878: /* /\* cuts string t into u and v where u ends before last occurence of char 'occ' */
879: /* and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
880: /* gives u="abcdef2ghi" and v="j" *\/ */
881: /* int i,lg,j,p=0; */
882: /* i=0; */
883: /* lg=strlen(t); */
884: /* for(j=0; j<=lg-1; j++) { */
885: /* if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
886: /* } */
887:
888: /* for(j=0; j<p; j++) { */
889: /* (u[j] = t[j]); */
890: /* } */
891: /* u[p]='\0'; */
892:
893: /* for(j=0; j<= lg; j++) { */
894: /* if (j>=(p+1))(v[j-p-1] = t[j]); */
895: /* } */
896: /* } */
897:
898: #ifdef _WIN32
899: char * strsep(char **pp, const char *delim)
900: {
901: char *p, *q;
902:
903: if ((p = *pp) == NULL)
904: return 0;
905: if ((q = strpbrk (p, delim)) != NULL)
906: {
907: *pp = q + 1;
908: *q = '\0';
909: }
910: else
911: *pp = 0;
912: return p;
913: }
914: #endif
915:
916: /********************** nrerror ********************/
917:
918: void nrerror(char error_text[])
919: {
920: fprintf(stderr,"ERREUR ...\n");
921: fprintf(stderr,"%s\n",error_text);
922: exit(EXIT_FAILURE);
923: }
924: /*********************** vector *******************/
925: double *vector(int nl, int nh)
926: {
927: double *v;
928: v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
929: if (!v) nrerror("allocation failure in vector");
930: return v-nl+NR_END;
931: }
932:
933: /************************ free vector ******************/
934: void free_vector(double*v, int nl, int nh)
935: {
936: free((FREE_ARG)(v+nl-NR_END));
937: }
938:
939: /************************ivector *******************************/
940: int *ivector(long nl,long nh)
941: {
942: int *v;
943: v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
944: if (!v) nrerror("allocation failure in ivector");
945: return v-nl+NR_END;
946: }
947:
948: /******************free ivector **************************/
949: void free_ivector(int *v, long nl, long nh)
950: {
951: free((FREE_ARG)(v+nl-NR_END));
952: }
953:
954: /************************lvector *******************************/
955: long *lvector(long nl,long nh)
956: {
957: long *v;
958: v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
959: if (!v) nrerror("allocation failure in ivector");
960: return v-nl+NR_END;
961: }
962:
963: /******************free lvector **************************/
964: void free_lvector(long *v, long nl, long nh)
965: {
966: free((FREE_ARG)(v+nl-NR_END));
967: }
968:
969: /******************* imatrix *******************************/
970: int **imatrix(long nrl, long nrh, long ncl, long nch)
971: /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
972: {
973: long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
974: int **m;
975:
976: /* allocate pointers to rows */
977: m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
978: if (!m) nrerror("allocation failure 1 in matrix()");
979: m += NR_END;
980: m -= nrl;
981:
982:
983: /* allocate rows and set pointers to them */
984: m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
985: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
986: m[nrl] += NR_END;
987: m[nrl] -= ncl;
988:
989: for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
990:
991: /* return pointer to array of pointers to rows */
992: return m;
993: }
994:
995: /****************** free_imatrix *************************/
996: void free_imatrix(m,nrl,nrh,ncl,nch)
997: int **m;
998: long nch,ncl,nrh,nrl;
999: /* free an int matrix allocated by imatrix() */
1000: {
1001: free((FREE_ARG) (m[nrl]+ncl-NR_END));
1002: free((FREE_ARG) (m+nrl-NR_END));
1003: }
1004:
1005: /******************* matrix *******************************/
1006: double **matrix(long nrl, long nrh, long ncl, long nch)
1007: {
1008: long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
1009: double **m;
1010:
1011: m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1012: if (!m) nrerror("allocation failure 1 in matrix()");
1013: m += NR_END;
1014: m -= nrl;
1015:
1016: m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1017: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1018: m[nrl] += NR_END;
1019: m[nrl] -= ncl;
1020:
1021: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1022: return m;
1023: /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
1024: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
1025: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1026: */
1027: }
1028:
1029: /*************************free matrix ************************/
1030: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
1031: {
1032: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1033: free((FREE_ARG)(m+nrl-NR_END));
1034: }
1035:
1036: /******************* ma3x *******************************/
1037: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
1038: {
1039: long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
1040: double ***m;
1041:
1042: m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1043: if (!m) nrerror("allocation failure 1 in matrix()");
1044: m += NR_END;
1045: m -= nrl;
1046:
1047: m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1048: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1049: m[nrl] += NR_END;
1050: m[nrl] -= ncl;
1051:
1052: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1053:
1054: m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
1055: if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
1056: m[nrl][ncl] += NR_END;
1057: m[nrl][ncl] -= nll;
1058: for (j=ncl+1; j<=nch; j++)
1059: m[nrl][j]=m[nrl][j-1]+nlay;
1060:
1061: for (i=nrl+1; i<=nrh; i++) {
1062: m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
1063: for (j=ncl+1; j<=nch; j++)
1064: m[i][j]=m[i][j-1]+nlay;
1065: }
1066: return m;
1067: /* gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
1068: &(m[i][j][k]) <=> *((*(m+i) + j)+k)
1069: */
1070: }
1071:
1072: /*************************free ma3x ************************/
1073: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
1074: {
1075: free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
1076: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1077: free((FREE_ARG)(m+nrl-NR_END));
1078: }
1079:
1080: /*************** function subdirf ***********/
1081: char *subdirf(char fileres[])
1082: {
1083: /* Caution optionfilefiname is hidden */
1084: strcpy(tmpout,optionfilefiname);
1085: strcat(tmpout,"/"); /* Add to the right */
1086: strcat(tmpout,fileres);
1087: return tmpout;
1088: }
1089:
1090: /*************** function subdirf2 ***********/
1091: char *subdirf2(char fileres[], char *preop)
1092: {
1093:
1094: /* Caution optionfilefiname is hidden */
1095: strcpy(tmpout,optionfilefiname);
1096: strcat(tmpout,"/");
1097: strcat(tmpout,preop);
1098: strcat(tmpout,fileres);
1099: return tmpout;
1100: }
1101:
1102: /*************** function subdirf3 ***********/
1103: char *subdirf3(char fileres[], char *preop, char *preop2)
1104: {
1105:
1106: /* Caution optionfilefiname is hidden */
1107: strcpy(tmpout,optionfilefiname);
1108: strcat(tmpout,"/");
1109: strcat(tmpout,preop);
1110: strcat(tmpout,preop2);
1111: strcat(tmpout,fileres);
1112: return tmpout;
1113: }
1114:
1115: char *asc_diff_time(long time_sec, char ascdiff[])
1116: {
1117: long sec_left, days, hours, minutes;
1118: days = (time_sec) / (60*60*24);
1119: sec_left = (time_sec) % (60*60*24);
1120: hours = (sec_left) / (60*60) ;
1121: sec_left = (sec_left) %(60*60);
1122: minutes = (sec_left) /60;
1123: sec_left = (sec_left) % (60);
1124: sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);
1125: return ascdiff;
1126: }
1127:
1128: /***************** f1dim *************************/
1129: extern int ncom;
1130: extern double *pcom,*xicom;
1131: extern double (*nrfunc)(double []);
1132:
1133: double f1dim(double x)
1134: {
1135: int j;
1136: double f;
1137: double *xt;
1138:
1139: xt=vector(1,ncom);
1140: for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
1141: f=(*nrfunc)(xt);
1142: free_vector(xt,1,ncom);
1143: return f;
1144: }
1145:
1146: /*****************brent *************************/
1147: double brent(double ax, double bx, double cx, double (*f)(double), double tol, double *xmin)
1148: {
1149: int iter;
1150: double a,b,d,etemp;
1151: double fu=0,fv,fw,fx;
1152: double ftemp;
1153: double p,q,r,tol1,tol2,u,v,w,x,xm;
1154: double e=0.0;
1155:
1156: a=(ax < cx ? ax : cx);
1157: b=(ax > cx ? ax : cx);
1158: x=w=v=bx;
1159: fw=fv=fx=(*f)(x);
1160: for (iter=1;iter<=ITMAX;iter++) {
1161: xm=0.5*(a+b);
1162: tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
1163: /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
1164: printf(".");fflush(stdout);
1165: fprintf(ficlog,".");fflush(ficlog);
1166: #ifdef DEBUGBRENT
1167: 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);
1168: 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);
1169: /* if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
1170: #endif
1171: if (fabs(x-xm) <= (tol2-0.5*(b-a))){
1172: *xmin=x;
1173: return fx;
1174: }
1175: ftemp=fu;
1176: if (fabs(e) > tol1) {
1177: r=(x-w)*(fx-fv);
1178: q=(x-v)*(fx-fw);
1179: p=(x-v)*q-(x-w)*r;
1180: q=2.0*(q-r);
1181: if (q > 0.0) p = -p;
1182: q=fabs(q);
1183: etemp=e;
1184: e=d;
1185: if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
1186: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1187: else {
1188: d=p/q;
1189: u=x+d;
1190: if (u-a < tol2 || b-u < tol2)
1191: d=SIGN(tol1,xm-x);
1192: }
1193: } else {
1194: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1195: }
1196: u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
1197: fu=(*f)(u);
1198: if (fu <= fx) {
1199: if (u >= x) a=x; else b=x;
1200: SHFT(v,w,x,u)
1201: SHFT(fv,fw,fx,fu)
1202: } else {
1203: if (u < x) a=u; else b=u;
1204: if (fu <= fw || w == x) {
1205: v=w;
1206: w=u;
1207: fv=fw;
1208: fw=fu;
1209: } else if (fu <= fv || v == x || v == w) {
1210: v=u;
1211: fv=fu;
1212: }
1213: }
1214: }
1215: nrerror("Too many iterations in brent");
1216: *xmin=x;
1217: return fx;
1218: }
1219:
1220: /****************** mnbrak ***********************/
1221:
1222: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
1223: double (*func)(double))
1224: {
1225: double ulim,u,r,q, dum;
1226: double fu;
1227:
1228: *fa=(*func)(*ax);
1229: *fb=(*func)(*bx);
1230: if (*fb > *fa) {
1231: SHFT(dum,*ax,*bx,dum)
1232: SHFT(dum,*fb,*fa,dum)
1233: }
1234: *cx=(*bx)+GOLD*(*bx-*ax);
1235: *fc=(*func)(*cx);
1236: while (*fb > *fc) { /* Declining fa, fb, fc */
1237: r=(*bx-*ax)*(*fb-*fc);
1238: q=(*bx-*cx)*(*fb-*fa);
1239: u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
1240: (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscisse of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
1241: ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscisse where function can be evaluated */
1242: if ((*bx-u)*(u-*cx) > 0.0) { /* if u between b and c */
1243: fu=(*func)(u);
1244: #ifdef DEBUG
1245: /* f(x)=A(x-u)**2+f(u) */
1246: double A, fparabu;
1247: A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
1248: fparabu= *fa - A*(*ax-u)*(*ax-u);
1249: printf("mnbrak (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf), (*u=%.12f, fu=%.12lf, fparabu=%.12f)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu, fparabu);
1250: fprintf(ficlog, "mnbrak (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf), (*u=%.12f, fu=%.12lf, fparabu=%.12f)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu, fparabu);
1251: #endif
1252: } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1253: fu=(*func)(u);
1254: if (fu < *fc) {
1255: SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
1256: SHFT(*fb,*fc,fu,(*func)(u))
1257: }
1258: } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1259: u=ulim;
1260: fu=(*func)(u);
1261: } else {
1262: u=(*cx)+GOLD*(*cx-*bx);
1263: fu=(*func)(u);
1264: }
1265: SHFT(*ax,*bx,*cx,u)
1266: SHFT(*fa,*fb,*fc,fu)
1267: }
1268: }
1269:
1270: /*************** linmin ************************/
1271: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
1272: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
1273: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
1274: the value of func at the returned location p . This is actually all accomplished by calling the
1275: routines mnbrak and brent .*/
1276: int ncom;
1277: double *pcom,*xicom;
1278: double (*nrfunc)(double []);
1279:
1280: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
1281: {
1282: double brent(double ax, double bx, double cx,
1283: double (*f)(double), double tol, double *xmin);
1284: double f1dim(double x);
1285: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
1286: double *fc, double (*func)(double));
1287: int j;
1288: double xx,xmin,bx,ax;
1289: double fx,fb,fa;
1290:
1291: ncom=n;
1292: pcom=vector(1,n);
1293: xicom=vector(1,n);
1294: nrfunc=func;
1295: for (j=1;j<=n;j++) {
1296: pcom[j]=p[j];
1297: xicom[j]=xi[j];
1298: }
1299: ax=0.0;
1300: xx=1.0;
1301: mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Find a bracket a,x,b in direction n=xi ie xicom */
1302: *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Find a minimum P+lambda n in that direction (lambdamin), with TOL between abscisses */
1303: #ifdef DEBUG
1304: printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1305: fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1306: #endif
1307: for (j=1;j<=n;j++) {
1308: xi[j] *= xmin;
1309: p[j] += xi[j];
1310: }
1311: free_vector(xicom,1,n);
1312: free_vector(pcom,1,n);
1313: }
1314:
1315:
1316: /*************** powell ************************/
1317: /*
1318: Minimization of a function func of n variables. Input consists of an initial starting point
1319: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
1320: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
1321: such that failure to decrease by more than this amount on one iteration signals doneness. On
1322: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
1323: function value at p , and iter is the number of iterations taken. The routine linmin is used.
1324: */
1325: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
1326: double (*func)(double []))
1327: {
1328: void linmin(double p[], double xi[], int n, double *fret,
1329: double (*func)(double []));
1330: int i,ibig,j;
1331: double del,t,*pt,*ptt,*xit;
1332: double fp,fptt;
1333: double *xits;
1334: int niterf, itmp;
1335:
1336: pt=vector(1,n);
1337: ptt=vector(1,n);
1338: xit=vector(1,n);
1339: xits=vector(1,n);
1340: *fret=(*func)(p);
1341: for (j=1;j<=n;j++) pt[j]=p[j];
1342: rcurr_time = time(NULL);
1343: for (*iter=1;;++(*iter)) {
1344: fp=(*fret);
1345: ibig=0;
1346: del=0.0;
1347: rlast_time=rcurr_time;
1348: /* (void) gettimeofday(&curr_time,&tzp); */
1349: rcurr_time = time(NULL);
1350: curr_time = *localtime(&rcurr_time);
1351: printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
1352: fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1353: /* fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1354: for (i=1;i<=n;i++) {
1355: printf(" %d %.12f",i, p[i]);
1356: fprintf(ficlog," %d %.12lf",i, p[i]);
1357: fprintf(ficrespow," %.12lf", p[i]);
1358: }
1359: printf("\n");
1360: fprintf(ficlog,"\n");
1361: fprintf(ficrespow,"\n");fflush(ficrespow);
1362: if(*iter <=3){
1363: tml = *localtime(&rcurr_time);
1364: strcpy(strcurr,asctime(&tml));
1365: rforecast_time=rcurr_time;
1366: itmp = strlen(strcurr);
1367: if(strcurr[itmp-1]=='\n') /* Windows outputs with a new line */
1368: strcurr[itmp-1]='\0';
1369: printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1370: fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1371: for(niterf=10;niterf<=30;niterf+=10){
1372: rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
1373: forecast_time = *localtime(&rforecast_time);
1374: strcpy(strfor,asctime(&forecast_time));
1375: itmp = strlen(strfor);
1376: if(strfor[itmp-1]=='\n')
1377: strfor[itmp-1]='\0';
1378: 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);
1379: 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);
1380: }
1381: }
1382: for (i=1;i<=n;i++) {
1383: for (j=1;j<=n;j++) xit[j]=xi[j][i];
1384: fptt=(*fret);
1385: #ifdef DEBUG
1386: printf("fret=%lf \n",*fret);
1387: fprintf(ficlog,"fret=%lf \n",*fret);
1388: #endif
1389: printf("%d",i);fflush(stdout);
1390: fprintf(ficlog,"%d",i);fflush(ficlog);
1391: linmin(p,xit,n,fret,func);
1392: if (fabs(fptt-(*fret)) > del) {
1393: del=fabs(fptt-(*fret));
1394: ibig=i;
1395: }
1396: #ifdef DEBUG
1397: printf("%d %.12e",i,(*fret));
1398: fprintf(ficlog,"%d %.12e",i,(*fret));
1399: for (j=1;j<=n;j++) {
1400: xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
1401: printf(" x(%d)=%.12e",j,xit[j]);
1402: fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1403: }
1404: for(j=1;j<=n;j++) {
1405: printf(" p(%d)=%.12e",j,p[j]);
1406: fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1407: }
1408: printf("\n");
1409: fprintf(ficlog,"\n");
1410: #endif
1411: } /* end i */
1412: if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
1413: #ifdef DEBUG
1414: int k[2],l;
1415: k[0]=1;
1416: k[1]=-1;
1417: printf("Max: %.12e",(*func)(p));
1418: fprintf(ficlog,"Max: %.12e",(*func)(p));
1419: for (j=1;j<=n;j++) {
1420: printf(" %.12e",p[j]);
1421: fprintf(ficlog," %.12e",p[j]);
1422: }
1423: printf("\n");
1424: fprintf(ficlog,"\n");
1425: for(l=0;l<=1;l++) {
1426: for (j=1;j<=n;j++) {
1427: ptt[j]=p[j]+(p[j]-pt[j])*k[l];
1428: printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1429: fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1430: }
1431: printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1432: fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1433: }
1434: #endif
1435:
1436:
1437: free_vector(xit,1,n);
1438: free_vector(xits,1,n);
1439: free_vector(ptt,1,n);
1440: free_vector(pt,1,n);
1441: return;
1442: }
1443: if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
1444: for (j=1;j<=n;j++) { /* Computes an extrapolated point */
1445: ptt[j]=2.0*p[j]-pt[j];
1446: xit[j]=p[j]-pt[j];
1447: pt[j]=p[j];
1448: }
1449: fptt=(*func)(ptt);
1450: if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1451: /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1452: /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1453: /* Let f"(x2) be the 2nd derivative equal everywhere. */
1454: /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
1455: /* will reach at f3 = fm + h^2/2 f"m ; f" = (f1 -2f2 +f3 ) / h**2 */
1456: /* f1-f3 = delta(2h) = 2 h**2 f'' = 2(f1- 2f2 +f3) */
1457: /* Thus we compare delta(2h) with observed f1-f3 */
1458: /* or best gain on one ancient line 'del' with total */
1459: /* gain f1-f2 = f1 - f2 - 'del' with del */
1460: /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1461:
1462: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del);
1463: t= t- del*SQR(fp-fptt);
1464: printf("t1= %.12lf, t2= %.12lf, t=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t);
1465: 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);
1466: #ifdef DEBUG
1467: printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1468: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1469: fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1470: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1471: 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);
1472: 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);
1473: #endif
1474: if (t < 0.0) { /* Then we use it for last direction */
1475: linmin(p,xit,n,fret,func); /* computes mean on the extrapolated direction.*/
1476: for (j=1;j<=n;j++) {
1477: xi[j][ibig]=xi[j][n]; /* Replace the direction with biggest decrease by n */
1478: xi[j][n]=xit[j]; /* and nth direction by the extrapolated */
1479: }
1480: printf("Gaining to use average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1481: fprintf(ficlog,"Gaining to use average direction of P0 P%d instead of biggest increase direction :\n",n,ibig);
1482:
1483: #ifdef DEBUG
1484: for(j=1;j<=n;j++){
1485: printf(" %.12e",xit[j]);
1486: fprintf(ficlog," %.12e",xit[j]);
1487: }
1488: printf("\n");
1489: fprintf(ficlog,"\n");
1490: #endif
1491: } /* end of t negative */
1492: } /* end if (fptt < fp) */
1493: }
1494: }
1495:
1496: /**** Prevalence limit (stable or period prevalence) ****************/
1497:
1498: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
1499: {
1500: /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1501: matrix by transitions matrix until convergence is reached */
1502:
1503: int i, ii,j,k;
1504: double min, max, maxmin, maxmax,sumnew=0.;
1505: /* double **matprod2(); */ /* test */
1506: double **out, cov[NCOVMAX+1], **pmij();
1507: double **newm;
1508: double agefin, delaymax=50 ; /* Max number of years to converge */
1509:
1510: for (ii=1;ii<=nlstate+ndeath;ii++)
1511: for (j=1;j<=nlstate+ndeath;j++){
1512: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1513: }
1514:
1515: cov[1]=1.;
1516:
1517: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1518: for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1519: newm=savm;
1520: /* Covariates have to be included here again */
1521: cov[2]=agefin;
1522:
1523: for (k=1; k<=cptcovn;k++) {
1524: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1525: /*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]]);*/
1526: }
1527: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1528: /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
1529: /* cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]] * nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]]; */
1530:
1531: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
1532: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
1533: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1534: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1535: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1536: out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1537:
1538: savm=oldm;
1539: oldm=newm;
1540: maxmax=0.;
1541: for(j=1;j<=nlstate;j++){
1542: min=1.;
1543: max=0.;
1544: for(i=1; i<=nlstate; i++) {
1545: sumnew=0;
1546: for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
1547: prlim[i][j]= newm[i][j]/(1-sumnew);
1548: /*printf(" prevalim i=%d, j=%d, prmlim[%d][%d]=%f, agefin=%d \n", i, j, i, j, prlim[i][j],(int)agefin);*/
1549: max=FMAX(max,prlim[i][j]);
1550: min=FMIN(min,prlim[i][j]);
1551: }
1552: maxmin=max-min;
1553: maxmax=FMAX(maxmax,maxmin);
1554: }
1555: if(maxmax < ftolpl){
1556: return prlim;
1557: }
1558: }
1559: }
1560:
1561: /*************** transition probabilities ***************/
1562:
1563: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1564: {
1565: /* According to parameters values stored in x and the covariate's values stored in cov,
1566: computes the probability to be observed in state j being in state i by appying the
1567: model to the ncovmodel covariates (including constant and age).
1568: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
1569: and, according on how parameters are entered, the position of the coefficient xij(nc) of the
1570: ncth covariate in the global vector x is given by the formula:
1571: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
1572: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
1573: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
1574: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1575: Outputs ps[i][j] the probability to be observed in j being in j according to
1576: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1577: */
1578: double s1, lnpijopii;
1579: /*double t34;*/
1580: int i,j,j1, nc, ii, jj;
1581:
1582: for(i=1; i<= nlstate; i++){
1583: for(j=1; j<i;j++){
1584: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1585: /*lnpijopii += param[i][j][nc]*cov[nc];*/
1586: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
1587: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1588: }
1589: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1590: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1591: }
1592: for(j=i+1; j<=nlstate+ndeath;j++){
1593: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1594: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
1595: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
1596: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1597: }
1598: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1599: }
1600: }
1601:
1602: for(i=1; i<= nlstate; i++){
1603: s1=0;
1604: for(j=1; j<i; j++){
1605: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1606: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1607: }
1608: for(j=i+1; j<=nlstate+ndeath; j++){
1609: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1610: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1611: }
1612: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1613: ps[i][i]=1./(s1+1.);
1614: /* Computing other pijs */
1615: for(j=1; j<i; j++)
1616: ps[i][j]= exp(ps[i][j])*ps[i][i];
1617: for(j=i+1; j<=nlstate+ndeath; j++)
1618: ps[i][j]= exp(ps[i][j])*ps[i][i];
1619: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
1620: } /* end i */
1621:
1622: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
1623: for(jj=1; jj<= nlstate+ndeath; jj++){
1624: ps[ii][jj]=0;
1625: ps[ii][ii]=1;
1626: }
1627: }
1628:
1629:
1630: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
1631: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */
1632: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
1633: /* } */
1634: /* printf("\n "); */
1635: /* } */
1636: /* printf("\n ");printf("%lf ",cov[2]);*/
1637: /*
1638: for(i=1; i<= npar; i++) printf("%f ",x[i]);
1639: goto end;*/
1640: return ps;
1641: }
1642:
1643: /**************** Product of 2 matrices ******************/
1644:
1645: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1646: {
1647: /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
1648: b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
1649: /* in, b, out are matrice of pointers which should have been initialized
1650: before: only the contents of out is modified. The function returns
1651: a pointer to pointers identical to out */
1652: int i, j, k;
1653: for(i=nrl; i<= nrh; i++)
1654: for(k=ncolol; k<=ncoloh; k++){
1655: out[i][k]=0.;
1656: for(j=ncl; j<=nch; j++)
1657: out[i][k] +=in[i][j]*b[j][k];
1658: }
1659: return out;
1660: }
1661:
1662:
1663: /************* Higher Matrix Product ***************/
1664:
1665: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
1666: {
1667: /* Computes the transition matrix starting at age 'age' over
1668: 'nhstepm*hstepm*stepm' months (i.e. until
1669: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
1670: nhstepm*hstepm matrices.
1671: Output is stored in matrix po[i][j][h] for h every 'hstepm' step
1672: (typically every 2 years instead of every month which is too big
1673: for the memory).
1674: Model is determined by parameters x and covariates have to be
1675: included manually here.
1676:
1677: */
1678:
1679: int i, j, d, h, k;
1680: double **out, cov[NCOVMAX+1];
1681: double **newm;
1682:
1683: /* Hstepm could be zero and should return the unit matrix */
1684: for (i=1;i<=nlstate+ndeath;i++)
1685: for (j=1;j<=nlstate+ndeath;j++){
1686: oldm[i][j]=(i==j ? 1.0 : 0.0);
1687: po[i][j][0]=(i==j ? 1.0 : 0.0);
1688: }
1689: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1690: for(h=1; h <=nhstepm; h++){
1691: for(d=1; d <=hstepm; d++){
1692: newm=savm;
1693: /* Covariates have to be included here again */
1694: cov[1]=1.;
1695: cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
1696: for (k=1; k<=cptcovn;k++)
1697: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1698: for (k=1; k<=cptcovage;k++)
1699: cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
1700: for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1701: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
1702:
1703:
1704: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
1705: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1706: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
1707: pmij(pmmij,cov,ncovmodel,x,nlstate));
1708: savm=oldm;
1709: oldm=newm;
1710: }
1711: for(i=1; i<=nlstate+ndeath; i++)
1712: for(j=1;j<=nlstate+ndeath;j++) {
1713: po[i][j][h]=newm[i][j];
1714: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1715: }
1716: /*printf("h=%d ",h);*/
1717: } /* end h */
1718: /* printf("\n H=%d \n",h); */
1719: return po;
1720: }
1721:
1722: #ifdef NLOPT
1723: double myfunc(unsigned n, const double *p1, double *grad, void *pd){
1724: double fret;
1725: double *xt;
1726: int j;
1727: myfunc_data *d2 = (myfunc_data *) pd;
1728: /* xt = (p1-1); */
1729: xt=vector(1,n);
1730: for (j=1;j<=n;j++) xt[j]=p1[j-1]; /* xt[1]=p1[0] */
1731:
1732: fret=(d2->function)(xt); /* p xt[1]@8 is fine */
1733: /* fret=(*func)(xt); /\* p xt[1]@8 is fine *\/ */
1734: printf("Function = %.12lf ",fret);
1735: for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]);
1736: printf("\n");
1737: free_vector(xt,1,n);
1738: return fret;
1739: }
1740: #endif
1741:
1742: /*************** log-likelihood *************/
1743: double func( double *x)
1744: {
1745: int i, ii, j, k, mi, d, kk;
1746: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1747: double **out;
1748: double sw; /* Sum of weights */
1749: double lli; /* Individual log likelihood */
1750: int s1, s2;
1751: double bbh, survp;
1752: long ipmx;
1753: /*extern weight */
1754: /* We are differentiating ll according to initial status */
1755: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
1756: /*for(i=1;i<imx;i++)
1757: printf(" %d\n",s[4][i]);
1758: */
1759:
1760: ++countcallfunc;
1761:
1762: cov[1]=1.;
1763:
1764: for(k=1; k<=nlstate; k++) ll[k]=0.;
1765:
1766: if(mle==1){
1767: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1768: /* Computes the values of the ncovmodel covariates of the model
1769: depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
1770: Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
1771: to be observed in j being in i according to the model.
1772: */
1773: for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1774: cov[2+k]=covar[Tvar[k]][i];
1775: }
1776: /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4]
1777: is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]
1778: has been calculated etc */
1779: for(mi=1; mi<= wav[i]-1; mi++){
1780: for (ii=1;ii<=nlstate+ndeath;ii++)
1781: for (j=1;j<=nlstate+ndeath;j++){
1782: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1783: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1784: }
1785: for(d=0; d<dh[mi][i]; d++){
1786: newm=savm;
1787: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1788: for (kk=1; kk<=cptcovage;kk++) {
1789: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; /* Tage[kk] gives the data-covariate associated with age */
1790: }
1791: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1792: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1793: savm=oldm;
1794: oldm=newm;
1795: } /* end mult */
1796:
1797: /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
1798: /* But now since version 0.9 we anticipate for bias at large stepm.
1799: * If stepm is larger than one month (smallest stepm) and if the exact delay
1800: * (in months) between two waves is not a multiple of stepm, we rounded to
1801: * the nearest (and in case of equal distance, to the lowest) interval but now
1802: * we keep into memory the bias bh[mi][i] and also the previous matrix product
1803: * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
1804: * probability in order to take into account the bias as a fraction of the way
1805: * from savm to out if bh is negative or even beyond if bh is positive. bh varies
1806: * -stepm/2 to stepm/2 .
1807: * For stepm=1 the results are the same as for previous versions of Imach.
1808: * For stepm > 1 the results are less biased than in previous versions.
1809: */
1810: s1=s[mw[mi][i]][i];
1811: s2=s[mw[mi+1][i]][i];
1812: bbh=(double)bh[mi][i]/(double)stepm;
1813: /* bias bh is positive if real duration
1814: * is higher than the multiple of stepm and negative otherwise.
1815: */
1816: /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
1817: if( s2 > nlstate){
1818: /* i.e. if s2 is a death state and if the date of death is known
1819: then the contribution to the likelihood is the probability to
1820: die between last step unit time and current step unit time,
1821: which is also equal to probability to die before dh
1822: minus probability to die before dh-stepm .
1823: In version up to 0.92 likelihood was computed
1824: as if date of death was unknown. Death was treated as any other
1825: health state: the date of the interview describes the actual state
1826: and not the date of a change in health state. The former idea was
1827: to consider that at each interview the state was recorded
1828: (healthy, disable or death) and IMaCh was corrected; but when we
1829: introduced the exact date of death then we should have modified
1830: the contribution of an exact death to the likelihood. This new
1831: contribution is smaller and very dependent of the step unit
1832: stepm. It is no more the probability to die between last interview
1833: and month of death but the probability to survive from last
1834: interview up to one month before death multiplied by the
1835: probability to die within a month. Thanks to Chris
1836: Jackson for correcting this bug. Former versions increased
1837: mortality artificially. The bad side is that we add another loop
1838: which slows down the processing. The difference can be up to 10%
1839: lower mortality.
1840: */
1841: lli=log(out[s1][s2] - savm[s1][s2]);
1842:
1843:
1844: } else if (s2==-2) {
1845: for (j=1,survp=0. ; j<=nlstate; j++)
1846: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1847: /*survp += out[s1][j]; */
1848: lli= log(survp);
1849: }
1850:
1851: else if (s2==-4) {
1852: for (j=3,survp=0. ; j<=nlstate; j++)
1853: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1854: lli= log(survp);
1855: }
1856:
1857: else if (s2==-5) {
1858: for (j=1,survp=0. ; j<=2; j++)
1859: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1860: lli= log(survp);
1861: }
1862:
1863: else{
1864: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1865: /* 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 */
1866: }
1867: /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
1868: /*if(lli ==000.0)*/
1869: /*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); */
1870: ipmx +=1;
1871: sw += weight[i];
1872: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1873: } /* end of wave */
1874: } /* end of individual */
1875: } else if(mle==2){
1876: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1877: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1878: for(mi=1; mi<= wav[i]-1; mi++){
1879: for (ii=1;ii<=nlstate+ndeath;ii++)
1880: for (j=1;j<=nlstate+ndeath;j++){
1881: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1882: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1883: }
1884: for(d=0; d<=dh[mi][i]; d++){
1885: newm=savm;
1886: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1887: for (kk=1; kk<=cptcovage;kk++) {
1888: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1889: }
1890: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1891: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1892: savm=oldm;
1893: oldm=newm;
1894: } /* end mult */
1895:
1896: s1=s[mw[mi][i]][i];
1897: s2=s[mw[mi+1][i]][i];
1898: bbh=(double)bh[mi][i]/(double)stepm;
1899: 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 */
1900: ipmx +=1;
1901: sw += weight[i];
1902: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1903: } /* end of wave */
1904: } /* end of individual */
1905: } else if(mle==3){ /* exponential inter-extrapolation */
1906: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1907: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1908: for(mi=1; mi<= wav[i]-1; mi++){
1909: for (ii=1;ii<=nlstate+ndeath;ii++)
1910: for (j=1;j<=nlstate+ndeath;j++){
1911: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1912: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1913: }
1914: for(d=0; d<dh[mi][i]; d++){
1915: newm=savm;
1916: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1917: for (kk=1; kk<=cptcovage;kk++) {
1918: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1919: }
1920: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1921: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1922: savm=oldm;
1923: oldm=newm;
1924: } /* end mult */
1925:
1926: s1=s[mw[mi][i]][i];
1927: s2=s[mw[mi+1][i]][i];
1928: bbh=(double)bh[mi][i]/(double)stepm;
1929: 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 */
1930: ipmx +=1;
1931: sw += weight[i];
1932: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1933: } /* end of wave */
1934: } /* end of individual */
1935: }else if (mle==4){ /* ml=4 no inter-extrapolation */
1936: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1937: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1938: for(mi=1; mi<= wav[i]-1; mi++){
1939: for (ii=1;ii<=nlstate+ndeath;ii++)
1940: for (j=1;j<=nlstate+ndeath;j++){
1941: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1942: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1943: }
1944: for(d=0; d<dh[mi][i]; d++){
1945: newm=savm;
1946: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1947: for (kk=1; kk<=cptcovage;kk++) {
1948: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1949: }
1950:
1951: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1952: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1953: savm=oldm;
1954: oldm=newm;
1955: } /* end mult */
1956:
1957: s1=s[mw[mi][i]][i];
1958: s2=s[mw[mi+1][i]][i];
1959: if( s2 > nlstate){
1960: lli=log(out[s1][s2] - savm[s1][s2]);
1961: }else{
1962: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
1963: }
1964: ipmx +=1;
1965: sw += weight[i];
1966: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1967: /* 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]); */
1968: } /* end of wave */
1969: } /* end of individual */
1970: }else{ /* ml=5 no inter-extrapolation no jackson =0.8a */
1971: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1972: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1973: for(mi=1; mi<= wav[i]-1; mi++){
1974: for (ii=1;ii<=nlstate+ndeath;ii++)
1975: for (j=1;j<=nlstate+ndeath;j++){
1976: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1977: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1978: }
1979: for(d=0; d<dh[mi][i]; d++){
1980: newm=savm;
1981: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1982: for (kk=1; kk<=cptcovage;kk++) {
1983: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1984: }
1985:
1986: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1987: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1988: savm=oldm;
1989: oldm=newm;
1990: } /* end mult */
1991:
1992: s1=s[mw[mi][i]][i];
1993: s2=s[mw[mi+1][i]][i];
1994: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
1995: ipmx +=1;
1996: sw += weight[i];
1997: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1998: /*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]);*/
1999: } /* end of wave */
2000: } /* end of individual */
2001: } /* End of if */
2002: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2003: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2004: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2005: return -l;
2006: }
2007:
2008: /*************** log-likelihood *************/
2009: double funcone( double *x)
2010: {
2011: /* Same as likeli but slower because of a lot of printf and if */
2012: int i, ii, j, k, mi, d, kk;
2013: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
2014: double **out;
2015: double lli; /* Individual log likelihood */
2016: double llt;
2017: int s1, s2;
2018: double bbh, survp;
2019: /*extern weight */
2020: /* We are differentiating ll according to initial status */
2021: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2022: /*for(i=1;i<imx;i++)
2023: printf(" %d\n",s[4][i]);
2024: */
2025: cov[1]=1.;
2026:
2027: for(k=1; k<=nlstate; k++) ll[k]=0.;
2028:
2029: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2030: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2031: for(mi=1; mi<= wav[i]-1; mi++){
2032: for (ii=1;ii<=nlstate+ndeath;ii++)
2033: for (j=1;j<=nlstate+ndeath;j++){
2034: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2035: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2036: }
2037: for(d=0; d<dh[mi][i]; d++){
2038: newm=savm;
2039: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2040: for (kk=1; kk<=cptcovage;kk++) {
2041: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2042: }
2043: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
2044: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2045: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2046: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
2047: /* 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
2048: savm=oldm;
2049: oldm=newm;
2050: } /* end mult */
2051:
2052: s1=s[mw[mi][i]][i];
2053: s2=s[mw[mi+1][i]][i];
2054: bbh=(double)bh[mi][i]/(double)stepm;
2055: /* bias is positive if real duration
2056: * is higher than the multiple of stepm and negative otherwise.
2057: */
2058: if( s2 > nlstate && (mle <5) ){ /* Jackson */
2059: lli=log(out[s1][s2] - savm[s1][s2]);
2060: } else if (s2==-2) {
2061: for (j=1,survp=0. ; j<=nlstate; j++)
2062: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2063: lli= log(survp);
2064: }else if (mle==1){
2065: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2066: } else if(mle==2){
2067: 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 */
2068: } else if(mle==3){ /* exponential inter-extrapolation */
2069: 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 */
2070: } else if (mle==4){ /* mle=4 no inter-extrapolation */
2071: lli=log(out[s1][s2]); /* Original formula */
2072: } else{ /* mle=0 back to 1 */
2073: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2074: /*lli=log(out[s1][s2]); */ /* Original formula */
2075: } /* End of if */
2076: ipmx +=1;
2077: sw += weight[i];
2078: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2079: /*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]); */
2080: if(globpr){
2081: fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
2082: %11.6f %11.6f %11.6f ", \
2083: num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
2084: 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
2085: for(k=1,llt=0.,l=0.; k<=nlstate; k++){
2086: llt +=ll[k]*gipmx/gsw;
2087: fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
2088: }
2089: fprintf(ficresilk," %10.6f\n", -llt);
2090: }
2091: } /* end of wave */
2092: } /* end of individual */
2093: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2094: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2095: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2096: if(globpr==0){ /* First time we count the contributions and weights */
2097: gipmx=ipmx;
2098: gsw=sw;
2099: }
2100: return -l;
2101: }
2102:
2103:
2104: /*************** function likelione ***********/
2105: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
2106: {
2107: /* This routine should help understanding what is done with
2108: the selection of individuals/waves and
2109: to check the exact contribution to the likelihood.
2110: Plotting could be done.
2111: */
2112: int k;
2113:
2114: if(*globpri !=0){ /* Just counts and sums, no printings */
2115: strcpy(fileresilk,"ilk");
2116: strcat(fileresilk,fileres);
2117: if((ficresilk=fopen(fileresilk,"w"))==NULL) {
2118: printf("Problem with resultfile: %s\n", fileresilk);
2119: fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
2120: }
2121: 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");
2122: fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
2123: /* i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
2124: for(k=1; k<=nlstate; k++)
2125: fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
2126: fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
2127: }
2128:
2129: *fretone=(*funcone)(p);
2130: if(*globpri !=0){
2131: fclose(ficresilk);
2132: fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
2133: fflush(fichtm);
2134: }
2135: return;
2136: }
2137:
2138:
2139: /*********** Maximum Likelihood Estimation ***************/
2140:
2141: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
2142: {
2143: int i,j, iter;
2144: double **xi;
2145: double fret;
2146: double fretone; /* Only one call to likelihood */
2147: /* char filerespow[FILENAMELENGTH];*/
2148:
2149: #ifdef NLOPT
2150: int creturn;
2151: nlopt_opt opt;
2152: /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
2153: double *lb;
2154: double minf; /* the minimum objective value, upon return */
2155: double * p1; /* Shifted parameters from 0 instead of 1 */
2156: myfunc_data dinst, *d = &dinst;
2157: #endif
2158:
2159:
2160: xi=matrix(1,npar,1,npar);
2161: for (i=1;i<=npar;i++)
2162: for (j=1;j<=npar;j++)
2163: xi[i][j]=(i==j ? 1.0 : 0.0);
2164: printf("Powell\n"); fprintf(ficlog,"Powell\n");
2165: strcpy(filerespow,"pow");
2166: strcat(filerespow,fileres);
2167: if((ficrespow=fopen(filerespow,"w"))==NULL) {
2168: printf("Problem with resultfile: %s\n", filerespow);
2169: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
2170: }
2171: fprintf(ficrespow,"# Powell\n# iter -2*LL");
2172: for (i=1;i<=nlstate;i++)
2173: for(j=1;j<=nlstate+ndeath;j++)
2174: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
2175: fprintf(ficrespow,"\n");
2176: #ifdef POWELL
2177: powell(p,xi,npar,ftol,&iter,&fret,func);
2178: #endif
2179:
2180: #ifdef NLOPT
2181: #ifdef NEWUOA
2182: opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
2183: #else
2184: opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
2185: #endif
2186: lb=vector(0,npar-1);
2187: for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
2188: nlopt_set_lower_bounds(opt, lb);
2189: nlopt_set_initial_step1(opt, 0.1);
2190:
2191: p1= (p+1); /* p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
2192: d->function = func;
2193: printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
2194: nlopt_set_min_objective(opt, myfunc, d);
2195: nlopt_set_xtol_rel(opt, ftol);
2196: if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
2197: printf("nlopt failed! %d\n",creturn);
2198: }
2199: else {
2200: printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
2201: printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
2202: iter=1; /* not equal */
2203: }
2204: nlopt_destroy(opt);
2205: #endif
2206: free_matrix(xi,1,npar,1,npar);
2207: fclose(ficrespow);
2208: printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2209: fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2210: fprintf(ficres,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2211:
2212: }
2213:
2214: /**** Computes Hessian and covariance matrix ***/
2215: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
2216: {
2217: double **a,**y,*x,pd;
2218: double **hess;
2219: int i, j,jk;
2220: int *indx;
2221:
2222: double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
2223: double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
2224: void lubksb(double **a, int npar, int *indx, double b[]) ;
2225: void ludcmp(double **a, int npar, int *indx, double *d) ;
2226: double gompertz(double p[]);
2227: hess=matrix(1,npar,1,npar);
2228:
2229: printf("\nCalculation of the hessian matrix. Wait...\n");
2230: fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
2231: for (i=1;i<=npar;i++){
2232: printf("%d",i);fflush(stdout);
2233: fprintf(ficlog,"%d",i);fflush(ficlog);
2234:
2235: hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
2236:
2237: /* printf(" %f ",p[i]);
2238: printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
2239: }
2240:
2241: for (i=1;i<=npar;i++) {
2242: for (j=1;j<=npar;j++) {
2243: if (j>i) {
2244: printf(".%d%d",i,j);fflush(stdout);
2245: fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
2246: hess[i][j]=hessij(p,delti,i,j,func,npar);
2247:
2248: hess[j][i]=hess[i][j];
2249: /*printf(" %lf ",hess[i][j]);*/
2250: }
2251: }
2252: }
2253: printf("\n");
2254: fprintf(ficlog,"\n");
2255:
2256: printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
2257: fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
2258:
2259: a=matrix(1,npar,1,npar);
2260: y=matrix(1,npar,1,npar);
2261: x=vector(1,npar);
2262: indx=ivector(1,npar);
2263: for (i=1;i<=npar;i++)
2264: for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
2265: ludcmp(a,npar,indx,&pd);
2266:
2267: for (j=1;j<=npar;j++) {
2268: for (i=1;i<=npar;i++) x[i]=0;
2269: x[j]=1;
2270: lubksb(a,npar,indx,x);
2271: for (i=1;i<=npar;i++){
2272: matcov[i][j]=x[i];
2273: }
2274: }
2275:
2276: printf("\n#Hessian matrix#\n");
2277: fprintf(ficlog,"\n#Hessian matrix#\n");
2278: for (i=1;i<=npar;i++) {
2279: for (j=1;j<=npar;j++) {
2280: printf("%.3e ",hess[i][j]);
2281: fprintf(ficlog,"%.3e ",hess[i][j]);
2282: }
2283: printf("\n");
2284: fprintf(ficlog,"\n");
2285: }
2286:
2287: /* Recompute Inverse */
2288: for (i=1;i<=npar;i++)
2289: for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
2290: ludcmp(a,npar,indx,&pd);
2291:
2292: /* printf("\n#Hessian matrix recomputed#\n");
2293:
2294: for (j=1;j<=npar;j++) {
2295: for (i=1;i<=npar;i++) x[i]=0;
2296: x[j]=1;
2297: lubksb(a,npar,indx,x);
2298: for (i=1;i<=npar;i++){
2299: y[i][j]=x[i];
2300: printf("%.3e ",y[i][j]);
2301: fprintf(ficlog,"%.3e ",y[i][j]);
2302: }
2303: printf("\n");
2304: fprintf(ficlog,"\n");
2305: }
2306: */
2307:
2308: free_matrix(a,1,npar,1,npar);
2309: free_matrix(y,1,npar,1,npar);
2310: free_vector(x,1,npar);
2311: free_ivector(indx,1,npar);
2312: free_matrix(hess,1,npar,1,npar);
2313:
2314:
2315: }
2316:
2317: /*************** hessian matrix ****************/
2318: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
2319: {
2320: int i;
2321: int l=1, lmax=20;
2322: double k1,k2;
2323: double p2[MAXPARM+1]; /* identical to x */
2324: double res;
2325: double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
2326: double fx;
2327: int k=0,kmax=10;
2328: double l1;
2329:
2330: fx=func(x);
2331: for (i=1;i<=npar;i++) p2[i]=x[i];
2332: for(l=0 ; l <=lmax; l++){ /* Enlarging the zone around the Maximum */
2333: l1=pow(10,l);
2334: delts=delt;
2335: for(k=1 ; k <kmax; k=k+1){
2336: delt = delta*(l1*k);
2337: p2[theta]=x[theta] +delt;
2338: k1=func(p2)-fx; /* Might be negative if too close to the theoretical maximum */
2339: p2[theta]=x[theta]-delt;
2340: k2=func(p2)-fx;
2341: /*res= (k1-2.0*fx+k2)/delt/delt; */
2342: res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
2343:
2344: #ifdef DEBUGHESS
2345: 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);
2346: 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);
2347: #endif
2348: /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
2349: if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
2350: k=kmax;
2351: }
2352: else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
2353: k=kmax; l=lmax*10.;
2354: }
2355: else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
2356: delts=delt;
2357: }
2358: }
2359: }
2360: delti[theta]=delts;
2361: return res;
2362:
2363: }
2364:
2365: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
2366: {
2367: int i;
2368: int l=1, l1, lmax=20;
2369: double k1,k2,k3,k4,res,fx;
2370: double p2[MAXPARM+1];
2371: int k;
2372:
2373: fx=func(x);
2374: for (k=1; k<=2; k++) {
2375: for (i=1;i<=npar;i++) p2[i]=x[i];
2376: p2[thetai]=x[thetai]+delti[thetai]/k;
2377: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2378: k1=func(p2)-fx;
2379:
2380: p2[thetai]=x[thetai]+delti[thetai]/k;
2381: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2382: k2=func(p2)-fx;
2383:
2384: p2[thetai]=x[thetai]-delti[thetai]/k;
2385: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2386: k3=func(p2)-fx;
2387:
2388: p2[thetai]=x[thetai]-delti[thetai]/k;
2389: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2390: k4=func(p2)-fx;
2391: res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
2392: #ifdef DEBUG
2393: 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);
2394: 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);
2395: #endif
2396: }
2397: return res;
2398: }
2399:
2400: /************** Inverse of matrix **************/
2401: void ludcmp(double **a, int n, int *indx, double *d)
2402: {
2403: int i,imax,j,k;
2404: double big,dum,sum,temp;
2405: double *vv;
2406:
2407: vv=vector(1,n);
2408: *d=1.0;
2409: for (i=1;i<=n;i++) {
2410: big=0.0;
2411: for (j=1;j<=n;j++)
2412: if ((temp=fabs(a[i][j])) > big) big=temp;
2413: if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
2414: vv[i]=1.0/big;
2415: }
2416: for (j=1;j<=n;j++) {
2417: for (i=1;i<j;i++) {
2418: sum=a[i][j];
2419: for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
2420: a[i][j]=sum;
2421: }
2422: big=0.0;
2423: for (i=j;i<=n;i++) {
2424: sum=a[i][j];
2425: for (k=1;k<j;k++)
2426: sum -= a[i][k]*a[k][j];
2427: a[i][j]=sum;
2428: if ( (dum=vv[i]*fabs(sum)) >= big) {
2429: big=dum;
2430: imax=i;
2431: }
2432: }
2433: if (j != imax) {
2434: for (k=1;k<=n;k++) {
2435: dum=a[imax][k];
2436: a[imax][k]=a[j][k];
2437: a[j][k]=dum;
2438: }
2439: *d = -(*d);
2440: vv[imax]=vv[j];
2441: }
2442: indx[j]=imax;
2443: if (a[j][j] == 0.0) a[j][j]=TINY;
2444: if (j != n) {
2445: dum=1.0/(a[j][j]);
2446: for (i=j+1;i<=n;i++) a[i][j] *= dum;
2447: }
2448: }
2449: free_vector(vv,1,n); /* Doesn't work */
2450: ;
2451: }
2452:
2453: void lubksb(double **a, int n, int *indx, double b[])
2454: {
2455: int i,ii=0,ip,j;
2456: double sum;
2457:
2458: for (i=1;i<=n;i++) {
2459: ip=indx[i];
2460: sum=b[ip];
2461: b[ip]=b[i];
2462: if (ii)
2463: for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
2464: else if (sum) ii=i;
2465: b[i]=sum;
2466: }
2467: for (i=n;i>=1;i--) {
2468: sum=b[i];
2469: for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
2470: b[i]=sum/a[i][i];
2471: }
2472: }
2473:
2474: void pstamp(FILE *fichier)
2475: {
2476: fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
2477: }
2478:
2479: /************ Frequencies ********************/
2480: 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[])
2481: { /* Some frequencies */
2482:
2483: int i, m, jk, k1,i1, j1, bool, z1,j;
2484: int first;
2485: double ***freq; /* Frequencies */
2486: double *pp, **prop;
2487: double pos,posprop, k2, dateintsum=0,k2cpt=0;
2488: char fileresp[FILENAMELENGTH];
2489:
2490: pp=vector(1,nlstate);
2491: prop=matrix(1,nlstate,iagemin,iagemax+3);
2492: strcpy(fileresp,"p");
2493: strcat(fileresp,fileres);
2494: if((ficresp=fopen(fileresp,"w"))==NULL) {
2495: printf("Problem with prevalence resultfile: %s\n", fileresp);
2496: fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
2497: exit(0);
2498: }
2499: freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
2500: j1=0;
2501:
2502: j=cptcoveff;
2503: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2504:
2505: first=1;
2506:
2507: /* for(k1=1; k1<=j ; k1++){ /* Loop on covariates */
2508: /* for(i1=1; i1<=ncodemax[k1];i1++){ /* Now it is 2 */
2509: /* j1++;
2510: */
2511: for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
2512: /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
2513: scanf("%d", i);*/
2514: for (i=-5; i<=nlstate+ndeath; i++)
2515: for (jk=-5; jk<=nlstate+ndeath; jk++)
2516: for(m=iagemin; m <= iagemax+3; m++)
2517: freq[i][jk][m]=0;
2518:
2519: for (i=1; i<=nlstate; i++)
2520: for(m=iagemin; m <= iagemax+3; m++)
2521: prop[i][m]=0;
2522:
2523: dateintsum=0;
2524: k2cpt=0;
2525: for (i=1; i<=imx; i++) {
2526: bool=1;
2527: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
2528: for (z1=1; z1<=cptcoveff; z1++)
2529: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
2530: /* Tests if the value of each of the covariates of i is equal to filter j1 */
2531: bool=0;
2532: /* 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",
2533: bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
2534: j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
2535: /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
2536: }
2537: }
2538:
2539: if (bool==1){
2540: for(m=firstpass; m<=lastpass; m++){
2541: k2=anint[m][i]+(mint[m][i]/12.);
2542: /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
2543: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2544: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2545: if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
2546: if (m<lastpass) {
2547: freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
2548: freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
2549: }
2550:
2551: if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
2552: dateintsum=dateintsum+k2;
2553: k2cpt++;
2554: }
2555: /*}*/
2556: }
2557: }
2558: } /* end i */
2559:
2560: /* fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
2561: pstamp(ficresp);
2562: if (cptcovn>0) {
2563: fprintf(ficresp, "\n#********** Variable ");
2564: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2565: fprintf(ficresp, "**********\n#");
2566: fprintf(ficlog, "\n#********** Variable ");
2567: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2568: fprintf(ficlog, "**********\n#");
2569: }
2570: for(i=1; i<=nlstate;i++)
2571: fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
2572: fprintf(ficresp, "\n");
2573:
2574: for(i=iagemin; i <= iagemax+3; i++){
2575: if(i==iagemax+3){
2576: fprintf(ficlog,"Total");
2577: }else{
2578: if(first==1){
2579: first=0;
2580: printf("See log file for details...\n");
2581: }
2582: fprintf(ficlog,"Age %d", i);
2583: }
2584: for(jk=1; jk <=nlstate ; jk++){
2585: for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
2586: pp[jk] += freq[jk][m][i];
2587: }
2588: for(jk=1; jk <=nlstate ; jk++){
2589: for(m=-1, pos=0; m <=0 ; m++)
2590: pos += freq[jk][m][i];
2591: if(pp[jk]>=1.e-10){
2592: if(first==1){
2593: printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
2594: }
2595: fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
2596: }else{
2597: if(first==1)
2598: printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2599: fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2600: }
2601: }
2602:
2603: for(jk=1; jk <=nlstate ; jk++){
2604: for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
2605: pp[jk] += freq[jk][m][i];
2606: }
2607: for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
2608: pos += pp[jk];
2609: posprop += prop[jk][i];
2610: }
2611: for(jk=1; jk <=nlstate ; jk++){
2612: if(pos>=1.e-5){
2613: if(first==1)
2614: printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2615: fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2616: }else{
2617: if(first==1)
2618: printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2619: fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2620: }
2621: if( i <= iagemax){
2622: if(pos>=1.e-5){
2623: fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
2624: /*probs[i][jk][j1]= pp[jk]/pos;*/
2625: /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
2626: }
2627: else
2628: fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
2629: }
2630: }
2631:
2632: for(jk=-1; jk <=nlstate+ndeath; jk++)
2633: for(m=-1; m <=nlstate+ndeath; m++)
2634: if(freq[jk][m][i] !=0 ) {
2635: if(first==1)
2636: printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
2637: fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
2638: }
2639: if(i <= iagemax)
2640: fprintf(ficresp,"\n");
2641: if(first==1)
2642: printf("Others in log...\n");
2643: fprintf(ficlog,"\n");
2644: }
2645: /*}*/
2646: }
2647: dateintmean=dateintsum/k2cpt;
2648:
2649: fclose(ficresp);
2650: free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
2651: free_vector(pp,1,nlstate);
2652: free_matrix(prop,1,nlstate,iagemin, iagemax+3);
2653: /* End of Freq */
2654: }
2655:
2656: /************ Prevalence ********************/
2657: 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)
2658: {
2659: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
2660: in each health status at the date of interview (if between dateprev1 and dateprev2).
2661: We still use firstpass and lastpass as another selection.
2662: */
2663:
2664: int i, m, jk, k1, i1, j1, bool, z1,j;
2665: double ***freq; /* Frequencies */
2666: double *pp, **prop;
2667: double pos,posprop;
2668: double y2; /* in fractional years */
2669: int iagemin, iagemax;
2670: int first; /** to stop verbosity which is redirected to log file */
2671:
2672: iagemin= (int) agemin;
2673: iagemax= (int) agemax;
2674: /*pp=vector(1,nlstate);*/
2675: prop=matrix(1,nlstate,iagemin,iagemax+3);
2676: /* freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
2677: j1=0;
2678:
2679: /*j=cptcoveff;*/
2680: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2681:
2682: first=1;
2683: for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
2684: /*for(i1=1; i1<=ncodemax[k1];i1++){
2685: j1++;*/
2686:
2687: for (i=1; i<=nlstate; i++)
2688: for(m=iagemin; m <= iagemax+3; m++)
2689: prop[i][m]=0.0;
2690:
2691: for (i=1; i<=imx; i++) { /* Each individual */
2692: bool=1;
2693: if (cptcovn>0) {
2694: for (z1=1; z1<=cptcoveff; z1++)
2695: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
2696: bool=0;
2697: }
2698: if (bool==1) {
2699: for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
2700: y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
2701: if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
2702: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2703: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2704: 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);
2705: if (s[m][i]>0 && s[m][i]<=nlstate) {
2706: /*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]]);*/
2707: prop[s[m][i]][(int)agev[m][i]] += weight[i];
2708: prop[s[m][i]][iagemax+3] += weight[i];
2709: }
2710: }
2711: } /* end selection of waves */
2712: }
2713: }
2714: for(i=iagemin; i <= iagemax+3; i++){
2715: for(jk=1,posprop=0; jk <=nlstate ; jk++) {
2716: posprop += prop[jk][i];
2717: }
2718:
2719: for(jk=1; jk <=nlstate ; jk++){
2720: if( i <= iagemax){
2721: if(posprop>=1.e-5){
2722: probs[i][jk][j1]= prop[jk][i]/posprop;
2723: } else{
2724: if(first==1){
2725: first=0;
2726: 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]);
2727: }
2728: }
2729: }
2730: }/* end jk */
2731: }/* end i */
2732: /*} *//* end i1 */
2733: } /* end j1 */
2734:
2735: /* free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
2736: /*free_vector(pp,1,nlstate);*/
2737: free_matrix(prop,1,nlstate, iagemin,iagemax+3);
2738: } /* End of prevalence */
2739:
2740: /************* Waves Concatenation ***************/
2741:
2742: 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)
2743: {
2744: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
2745: Death is a valid wave (if date is known).
2746: mw[mi][i] is the mi (mi=1 to wav[i]) effective wave of individual i
2747: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
2748: and mw[mi+1][i]. dh depends on stepm.
2749: */
2750:
2751: int i, mi, m;
2752: /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
2753: double sum=0., jmean=0.;*/
2754: int first;
2755: int j, k=0,jk, ju, jl;
2756: double sum=0.;
2757: first=0;
2758: jmin=1e+5;
2759: jmax=-1;
2760: jmean=0.;
2761: for(i=1; i<=imx; i++){
2762: mi=0;
2763: m=firstpass;
2764: while(s[m][i] <= nlstate){
2765: if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
2766: mw[++mi][i]=m;
2767: if(m >=lastpass)
2768: break;
2769: else
2770: m++;
2771: }/* end while */
2772: if (s[m][i] > nlstate){
2773: mi++; /* Death is another wave */
2774: /* if(mi==0) never been interviewed correctly before death */
2775: /* Only death is a correct wave */
2776: mw[mi][i]=m;
2777: }
2778:
2779: wav[i]=mi;
2780: if(mi==0){
2781: nbwarn++;
2782: if(first==0){
2783: printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
2784: first=1;
2785: }
2786: if(first==1){
2787: fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
2788: }
2789: } /* end mi==0 */
2790: } /* End individuals */
2791:
2792: for(i=1; i<=imx; i++){
2793: for(mi=1; mi<wav[i];mi++){
2794: if (stepm <=0)
2795: dh[mi][i]=1;
2796: else{
2797: if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
2798: if (agedc[i] < 2*AGESUP) {
2799: j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
2800: if(j==0) j=1; /* Survives at least one month after exam */
2801: else if(j<0){
2802: nberr++;
2803: 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]);
2804: j=1; /* Temporary Dangerous patch */
2805: 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);
2806: 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]);
2807: 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);
2808: }
2809: k=k+1;
2810: if (j >= jmax){
2811: jmax=j;
2812: ijmax=i;
2813: }
2814: if (j <= jmin){
2815: jmin=j;
2816: ijmin=i;
2817: }
2818: sum=sum+j;
2819: /*if (j<0) printf("j=%d num=%d \n",j,i);*/
2820: /* printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
2821: }
2822: }
2823: else{
2824: j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
2825: /* 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]); */
2826:
2827: k=k+1;
2828: if (j >= jmax) {
2829: jmax=j;
2830: ijmax=i;
2831: }
2832: else if (j <= jmin){
2833: jmin=j;
2834: ijmin=i;
2835: }
2836: /* if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
2837: /*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]);*/
2838: if(j<0){
2839: nberr++;
2840: 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]);
2841: 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]);
2842: }
2843: sum=sum+j;
2844: }
2845: jk= j/stepm;
2846: jl= j -jk*stepm;
2847: ju= j -(jk+1)*stepm;
2848: if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
2849: if(jl==0){
2850: dh[mi][i]=jk;
2851: bh[mi][i]=0;
2852: }else{ /* We want a negative bias in order to only have interpolation ie
2853: * to avoid the price of an extra matrix product in likelihood */
2854: dh[mi][i]=jk+1;
2855: bh[mi][i]=ju;
2856: }
2857: }else{
2858: if(jl <= -ju){
2859: dh[mi][i]=jk;
2860: bh[mi][i]=jl; /* bias is positive if real duration
2861: * is higher than the multiple of stepm and negative otherwise.
2862: */
2863: }
2864: else{
2865: dh[mi][i]=jk+1;
2866: bh[mi][i]=ju;
2867: }
2868: if(dh[mi][i]==0){
2869: dh[mi][i]=1; /* At least one step */
2870: bh[mi][i]=ju; /* At least one step */
2871: /* 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);*/
2872: }
2873: } /* end if mle */
2874: }
2875: } /* end wave */
2876: }
2877: jmean=sum/k;
2878: 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);
2879: 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);
2880: }
2881:
2882: /*********** Tricode ****************************/
2883: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
2884: {
2885: /**< Uses cptcovn+2*cptcovprod as the number of covariates */
2886: /* Tvar[i]=atoi(stre); find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1
2887: /* Boring subroutine which should only output nbcode[Tvar[j]][k]
2888: * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
2889: /* nbcode[Tvar[j]][1]=
2890: */
2891:
2892: int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
2893: int modmaxcovj=0; /* Modality max of covariates j */
2894: int cptcode=0; /* Modality max of covariates j */
2895: int modmincovj=0; /* Modality min of covariates j */
2896:
2897:
2898: cptcoveff=0;
2899:
2900: for (k=-1; k < maxncov; k++) Ndum[k]=0;
2901: for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
2902:
2903: /* Loop on covariates without age and products */
2904: for (j=1; j<=(cptcovs); j++) { /* model V1 + V2*age+ V3 + V3*V4 : V1 + V3 = 2 only */
2905: for (i=1; i<=imx; i++) { /* Lopp on individuals: reads the data file to get the maximum value of the
2906: modality of this covariate Vj*/
2907: ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
2908: * If product of Vn*Vm, still boolean *:
2909: * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
2910: * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0 */
2911: /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
2912: modality of the nth covariate of individual i. */
2913: if (ij > modmaxcovj)
2914: modmaxcovj=ij;
2915: else if (ij < modmincovj)
2916: modmincovj=ij;
2917: if ((ij < -1) && (ij > NCOVMAX)){
2918: printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
2919: exit(1);
2920: }else
2921: Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
2922: /* If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
2923: /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
2924: /* getting the maximum value of the modality of the covariate
2925: (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
2926: female is 1, then modmaxcovj=1.*/
2927: }
2928: printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
2929: cptcode=modmaxcovj;
2930: /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
2931: /*for (i=0; i<=cptcode; i++) {*/
2932: for (i=modmincovj; i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
2933: printf("Frequencies of covariates %d V%d %d\n", j, Tvar[j], Ndum[i]);
2934: if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
2935: ncodemax[j]++; /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
2936: }
2937: /* In fact ncodemax[j]=2 (dichotom. variables only) but it could be more for
2938: historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
2939: } /* Ndum[-1] number of undefined modalities */
2940:
2941: /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
2942: /* For covariate j, modalities could be 1, 2, 3, 4. If Ndum[2]=0 ncodemax[j] is not 4 but 3 */
2943: /* If Ndum[3}= 635; Ndum[4]=0; Ndum[5]=0; Ndum[6]=27; Ndum[7]=125;
2944: modmincovj=3; modmaxcovj = 7;
2945: There are only 3 modalities non empty (or 2 if 27 is too few) : ncodemax[j]=3;
2946: which will be coded 0, 1, 2 which in binary on 3-1 digits are 0=00 1=01, 2=10; defining two dummy
2947: variables V1_1 and V1_2.
2948: nbcode[Tvar[j]][ij]=k;
2949: nbcode[Tvar[j]][1]=0;
2950: nbcode[Tvar[j]][2]=1;
2951: nbcode[Tvar[j]][3]=2;
2952: */
2953: ij=1; /* ij is similar to i but can jumps over null modalities */
2954: for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
2955: for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
2956: /*recode from 0 */
2957: if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
2958: nbcode[Tvar[j]][ij]=k; /* stores the modality in an array nbcode.
2959: k is a modality. If we have model=V1+V1*sex
2960: then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
2961: ij++;
2962: }
2963: if (ij > ncodemax[j]) break;
2964: } /* end of loop on */
2965: } /* end of loop on modality */
2966: } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/
2967:
2968: for (k=-1; k< maxncov; k++) Ndum[k]=0;
2969:
2970: for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */
2971: /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
2972: ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
2973: Ndum[ij]++;
2974: }
2975:
2976: ij=1;
2977: for (i=0; i<= maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
2978: /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
2979: if((Ndum[i]!=0) && (i<=ncovcol)){
2980: /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
2981: Tvaraff[ij]=i; /*For printing (unclear) */
2982: ij++;
2983: }else
2984: Tvaraff[ij]=0;
2985: }
2986: ij--;
2987: cptcoveff=ij; /*Number of total covariates*/
2988:
2989: }
2990:
2991:
2992: /*********** Health Expectancies ****************/
2993:
2994: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
2995:
2996: {
2997: /* Health expectancies, no variances */
2998: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2;
2999: int nhstepma, nstepma; /* Decreasing with age */
3000: double age, agelim, hf;
3001: double ***p3mat;
3002: double eip;
3003:
3004: pstamp(ficreseij);
3005: fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
3006: fprintf(ficreseij,"# Age");
3007: for(i=1; i<=nlstate;i++){
3008: for(j=1; j<=nlstate;j++){
3009: fprintf(ficreseij," e%1d%1d ",i,j);
3010: }
3011: fprintf(ficreseij," e%1d. ",i);
3012: }
3013: fprintf(ficreseij,"\n");
3014:
3015:
3016: if(estepm < stepm){
3017: printf ("Problem %d lower than %d\n",estepm, stepm);
3018: }
3019: else hstepm=estepm;
3020: /* We compute the life expectancy from trapezoids spaced every estepm months
3021: * This is mainly to measure the difference between two models: for example
3022: * if stepm=24 months pijx are given only every 2 years and by summing them
3023: * we are calculating an estimate of the Life Expectancy assuming a linear
3024: * progression in between and thus overestimating or underestimating according
3025: * to the curvature of the survival function. If, for the same date, we
3026: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3027: * to compare the new estimate of Life expectancy with the same linear
3028: * hypothesis. A more precise result, taking into account a more precise
3029: * curvature will be obtained if estepm is as small as stepm. */
3030:
3031: /* For example we decided to compute the life expectancy with the smallest unit */
3032: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3033: nhstepm is the number of hstepm from age to agelim
3034: nstepm is the number of stepm from age to agelin.
3035: Look at hpijx to understand the reason of that which relies in memory size
3036: and note for a fixed period like estepm months */
3037: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3038: survival function given by stepm (the optimization length). Unfortunately it
3039: means that if the survival funtion is printed only each two years of age and if
3040: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3041: results. So we changed our mind and took the option of the best precision.
3042: */
3043: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3044:
3045: agelim=AGESUP;
3046: /* If stepm=6 months */
3047: /* Computed by stepm unit matrices, product of hstepm matrices, stored
3048: in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
3049:
3050: /* nhstepm age range expressed in number of stepm */
3051: nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3052: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3053: /* if (stepm >= YEARM) hstepm=1;*/
3054: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3055: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3056:
3057: for (age=bage; age<=fage; age ++){
3058: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3059: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3060: /* if (stepm >= YEARM) hstepm=1;*/
3061: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3062:
3063: /* If stepm=6 months */
3064: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3065: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3066:
3067: hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3068:
3069: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3070:
3071: printf("%d|",(int)age);fflush(stdout);
3072: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3073:
3074: /* Computing expectancies */
3075: for(i=1; i<=nlstate;i++)
3076: for(j=1; j<=nlstate;j++)
3077: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3078: eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
3079:
3080: /* 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]);*/
3081:
3082: }
3083:
3084: fprintf(ficreseij,"%3.0f",age );
3085: for(i=1; i<=nlstate;i++){
3086: eip=0;
3087: for(j=1; j<=nlstate;j++){
3088: eip +=eij[i][j][(int)age];
3089: fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
3090: }
3091: fprintf(ficreseij,"%9.4f", eip );
3092: }
3093: fprintf(ficreseij,"\n");
3094:
3095: }
3096: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3097: printf("\n");
3098: fprintf(ficlog,"\n");
3099:
3100: }
3101:
3102: 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[] )
3103:
3104: {
3105: /* Covariances of health expectancies eij and of total life expectancies according
3106: to initial status i, ei. .
3107: */
3108: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
3109: int nhstepma, nstepma; /* Decreasing with age */
3110: double age, agelim, hf;
3111: double ***p3matp, ***p3matm, ***varhe;
3112: double **dnewm,**doldm;
3113: double *xp, *xm;
3114: double **gp, **gm;
3115: double ***gradg, ***trgradg;
3116: int theta;
3117:
3118: double eip, vip;
3119:
3120: varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
3121: xp=vector(1,npar);
3122: xm=vector(1,npar);
3123: dnewm=matrix(1,nlstate*nlstate,1,npar);
3124: doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
3125:
3126: pstamp(ficresstdeij);
3127: fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
3128: fprintf(ficresstdeij,"# Age");
3129: for(i=1; i<=nlstate;i++){
3130: for(j=1; j<=nlstate;j++)
3131: fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
3132: fprintf(ficresstdeij," e%1d. ",i);
3133: }
3134: fprintf(ficresstdeij,"\n");
3135:
3136: pstamp(ficrescveij);
3137: fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
3138: fprintf(ficrescveij,"# Age");
3139: for(i=1; i<=nlstate;i++)
3140: for(j=1; j<=nlstate;j++){
3141: cptj= (j-1)*nlstate+i;
3142: for(i2=1; i2<=nlstate;i2++)
3143: for(j2=1; j2<=nlstate;j2++){
3144: cptj2= (j2-1)*nlstate+i2;
3145: if(cptj2 <= cptj)
3146: fprintf(ficrescveij," %1d%1d,%1d%1d",i,j,i2,j2);
3147: }
3148: }
3149: fprintf(ficrescveij,"\n");
3150:
3151: if(estepm < stepm){
3152: printf ("Problem %d lower than %d\n",estepm, stepm);
3153: }
3154: else hstepm=estepm;
3155: /* We compute the life expectancy from trapezoids spaced every estepm months
3156: * This is mainly to measure the difference between two models: for example
3157: * if stepm=24 months pijx are given only every 2 years and by summing them
3158: * we are calculating an estimate of the Life Expectancy assuming a linear
3159: * progression in between and thus overestimating or underestimating according
3160: * to the curvature of the survival function. If, for the same date, we
3161: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3162: * to compare the new estimate of Life expectancy with the same linear
3163: * hypothesis. A more precise result, taking into account a more precise
3164: * curvature will be obtained if estepm is as small as stepm. */
3165:
3166: /* For example we decided to compute the life expectancy with the smallest unit */
3167: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3168: nhstepm is the number of hstepm from age to agelim
3169: nstepm is the number of stepm from age to agelin.
3170: Look at hpijx to understand the reason of that which relies in memory size
3171: and note for a fixed period like estepm months */
3172: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3173: survival function given by stepm (the optimization length). Unfortunately it
3174: means that if the survival funtion is printed only each two years of age and if
3175: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3176: results. So we changed our mind and took the option of the best precision.
3177: */
3178: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3179:
3180: /* If stepm=6 months */
3181: /* nhstepm age range expressed in number of stepm */
3182: agelim=AGESUP;
3183: nstepm=(int) rint((agelim-bage)*YEARM/stepm);
3184: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3185: /* if (stepm >= YEARM) hstepm=1;*/
3186: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3187:
3188: p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3189: p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3190: gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
3191: trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
3192: gp=matrix(0,nhstepm,1,nlstate*nlstate);
3193: gm=matrix(0,nhstepm,1,nlstate*nlstate);
3194:
3195: for (age=bage; age<=fage; age ++){
3196: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3197: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3198: /* if (stepm >= YEARM) hstepm=1;*/
3199: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3200:
3201: /* If stepm=6 months */
3202: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3203: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3204:
3205: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3206:
3207: /* Computing Variances of health expectancies */
3208: /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
3209: decrease memory allocation */
3210: for(theta=1; theta <=npar; theta++){
3211: for(i=1; i<=npar; i++){
3212: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3213: xm[i] = x[i] - (i==theta ?delti[theta]:0);
3214: }
3215: hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);
3216: hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);
3217:
3218: for(j=1; j<= nlstate; j++){
3219: for(i=1; i<=nlstate; i++){
3220: for(h=0; h<=nhstepm-1; h++){
3221: gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
3222: gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
3223: }
3224: }
3225: }
3226:
3227: for(ij=1; ij<= nlstate*nlstate; ij++)
3228: for(h=0; h<=nhstepm-1; h++){
3229: gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
3230: }
3231: }/* End theta */
3232:
3233:
3234: for(h=0; h<=nhstepm-1; h++)
3235: for(j=1; j<=nlstate*nlstate;j++)
3236: for(theta=1; theta <=npar; theta++)
3237: trgradg[h][j][theta]=gradg[h][theta][j];
3238:
3239:
3240: for(ij=1;ij<=nlstate*nlstate;ij++)
3241: for(ji=1;ji<=nlstate*nlstate;ji++)
3242: varhe[ij][ji][(int)age] =0.;
3243:
3244: printf("%d|",(int)age);fflush(stdout);
3245: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3246: for(h=0;h<=nhstepm-1;h++){
3247: for(k=0;k<=nhstepm-1;k++){
3248: matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
3249: matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
3250: for(ij=1;ij<=nlstate*nlstate;ij++)
3251: for(ji=1;ji<=nlstate*nlstate;ji++)
3252: varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
3253: }
3254: }
3255:
3256: /* Computing expectancies */
3257: hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3258: for(i=1; i<=nlstate;i++)
3259: for(j=1; j<=nlstate;j++)
3260: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3261: eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
3262:
3263: /* 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]);*/
3264:
3265: }
3266:
3267: fprintf(ficresstdeij,"%3.0f",age );
3268: for(i=1; i<=nlstate;i++){
3269: eip=0.;
3270: vip=0.;
3271: for(j=1; j<=nlstate;j++){
3272: eip += eij[i][j][(int)age];
3273: for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
3274: vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
3275: fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
3276: }
3277: fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
3278: }
3279: fprintf(ficresstdeij,"\n");
3280:
3281: fprintf(ficrescveij,"%3.0f",age );
3282: for(i=1; i<=nlstate;i++)
3283: for(j=1; j<=nlstate;j++){
3284: cptj= (j-1)*nlstate+i;
3285: for(i2=1; i2<=nlstate;i2++)
3286: for(j2=1; j2<=nlstate;j2++){
3287: cptj2= (j2-1)*nlstate+i2;
3288: if(cptj2 <= cptj)
3289: fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
3290: }
3291: }
3292: fprintf(ficrescveij,"\n");
3293:
3294: }
3295: free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
3296: free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
3297: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
3298: free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
3299: free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3300: free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3301: printf("\n");
3302: fprintf(ficlog,"\n");
3303:
3304: free_vector(xm,1,npar);
3305: free_vector(xp,1,npar);
3306: free_matrix(dnewm,1,nlstate*nlstate,1,npar);
3307: free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
3308: free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
3309: }
3310:
3311: /************ Variance ******************/
3312: 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[])
3313: {
3314: /* Variance of health expectancies */
3315: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
3316: /* double **newm;*/
3317: double **dnewm,**doldm;
3318: double **dnewmp,**doldmp;
3319: int i, j, nhstepm, hstepm, h, nstepm ;
3320: int k, cptcode;
3321: double *xp;
3322: double **gp, **gm; /* for var eij */
3323: double ***gradg, ***trgradg; /*for var eij */
3324: double **gradgp, **trgradgp; /* for var p point j */
3325: double *gpp, *gmp; /* for var p point j */
3326: double **varppt; /* for var p point j nlstate to nlstate+ndeath */
3327: double ***p3mat;
3328: double age,agelim, hf;
3329: double ***mobaverage;
3330: int theta;
3331: char digit[4];
3332: char digitp[25];
3333:
3334: char fileresprobmorprev[FILENAMELENGTH];
3335:
3336: if(popbased==1){
3337: if(mobilav!=0)
3338: strcpy(digitp,"-populbased-mobilav-");
3339: else strcpy(digitp,"-populbased-nomobil-");
3340: }
3341: else
3342: strcpy(digitp,"-stablbased-");
3343:
3344: if (mobilav!=0) {
3345: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3346: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
3347: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
3348: printf(" Error in movingaverage mobilav=%d\n",mobilav);
3349: }
3350: }
3351:
3352: strcpy(fileresprobmorprev,"prmorprev");
3353: sprintf(digit,"%-d",ij);
3354: /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
3355: strcat(fileresprobmorprev,digit); /* Tvar to be done */
3356: strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
3357: strcat(fileresprobmorprev,fileres);
3358: if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
3359: printf("Problem with resultfile: %s\n", fileresprobmorprev);
3360: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
3361: }
3362: printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3363:
3364: fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3365: pstamp(ficresprobmorprev);
3366: 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);
3367: fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
3368: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3369: fprintf(ficresprobmorprev," p.%-d SE",j);
3370: for(i=1; i<=nlstate;i++)
3371: fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
3372: }
3373: fprintf(ficresprobmorprev,"\n");
3374: fprintf(ficgp,"\n# Routine varevsij");
3375: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
3376: 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");
3377: fprintf(fichtm,"\n<br>%s <br>\n",digitp);
3378: /* } */
3379: varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3380: pstamp(ficresvij);
3381: fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n# (weighted average of eij where weights are ");
3382: if(popbased==1)
3383: 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);
3384: else
3385: fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
3386: fprintf(ficresvij,"# Age");
3387: for(i=1; i<=nlstate;i++)
3388: for(j=1; j<=nlstate;j++)
3389: fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
3390: fprintf(ficresvij,"\n");
3391:
3392: xp=vector(1,npar);
3393: dnewm=matrix(1,nlstate,1,npar);
3394: doldm=matrix(1,nlstate,1,nlstate);
3395: dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
3396: doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3397:
3398: gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
3399: gpp=vector(nlstate+1,nlstate+ndeath);
3400: gmp=vector(nlstate+1,nlstate+ndeath);
3401: trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
3402:
3403: if(estepm < stepm){
3404: printf ("Problem %d lower than %d\n",estepm, stepm);
3405: }
3406: else hstepm=estepm;
3407: /* For example we decided to compute the life expectancy with the smallest unit */
3408: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3409: nhstepm is the number of hstepm from age to agelim
3410: nstepm is the number of stepm from age to agelin.
3411: Look at function hpijx to understand why (it is linked to memory size questions) */
3412: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3413: survival function given by stepm (the optimization length). Unfortunately it
3414: means that if the survival funtion is printed every two years of age and if
3415: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3416: results. So we changed our mind and took the option of the best precision.
3417: */
3418: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3419: agelim = AGESUP;
3420: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3421: nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3422: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3423: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3424: gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
3425: gp=matrix(0,nhstepm,1,nlstate);
3426: gm=matrix(0,nhstepm,1,nlstate);
3427:
3428:
3429: for(theta=1; theta <=npar; theta++){
3430: for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
3431: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3432: }
3433: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3434: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3435:
3436: if (popbased==1) {
3437: if(mobilav ==0){
3438: for(i=1; i<=nlstate;i++)
3439: prlim[i][i]=probs[(int)age][i][ij];
3440: }else{ /* mobilav */
3441: for(i=1; i<=nlstate;i++)
3442: prlim[i][i]=mobaverage[(int)age][i][ij];
3443: }
3444: }
3445:
3446: for(j=1; j<= nlstate; j++){
3447: for(h=0; h<=nhstepm; h++){
3448: for(i=1, gp[h][j]=0.;i<=nlstate;i++)
3449: gp[h][j] += prlim[i][i]*p3mat[i][j][h];
3450: }
3451: }
3452: /* This for computing probability of death (h=1 means
3453: computed over hstepm matrices product = hstepm*stepm months)
3454: as a weighted average of prlim.
3455: */
3456: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3457: for(i=1,gpp[j]=0.; i<= nlstate; i++)
3458: gpp[j] += prlim[i][i]*p3mat[i][j][1];
3459: }
3460: /* end probability of death */
3461:
3462: for(i=1; i<=npar; i++) /* Computes gradient x - delta */
3463: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3464: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3465: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3466:
3467: if (popbased==1) {
3468: if(mobilav ==0){
3469: for(i=1; i<=nlstate;i++)
3470: prlim[i][i]=probs[(int)age][i][ij];
3471: }else{ /* mobilav */
3472: for(i=1; i<=nlstate;i++)
3473: prlim[i][i]=mobaverage[(int)age][i][ij];
3474: }
3475: }
3476:
3477: for(j=1; j<= nlstate; j++){ /* Sum of wi * eij = e.j */
3478: for(h=0; h<=nhstepm; h++){
3479: for(i=1, gm[h][j]=0.;i<=nlstate;i++)
3480: gm[h][j] += prlim[i][i]*p3mat[i][j][h];
3481: }
3482: }
3483: /* This for computing probability of death (h=1 means
3484: computed over hstepm matrices product = hstepm*stepm months)
3485: as a weighted average of prlim.
3486: */
3487: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3488: for(i=1,gmp[j]=0.; i<= nlstate; i++)
3489: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3490: }
3491: /* end probability of death */
3492:
3493: for(j=1; j<= nlstate; j++) /* vareij */
3494: for(h=0; h<=nhstepm; h++){
3495: gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
3496: }
3497:
3498: for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
3499: gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
3500: }
3501:
3502: } /* End theta */
3503:
3504: trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
3505:
3506: for(h=0; h<=nhstepm; h++) /* veij */
3507: for(j=1; j<=nlstate;j++)
3508: for(theta=1; theta <=npar; theta++)
3509: trgradg[h][j][theta]=gradg[h][theta][j];
3510:
3511: for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
3512: for(theta=1; theta <=npar; theta++)
3513: trgradgp[j][theta]=gradgp[theta][j];
3514:
3515:
3516: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3517: for(i=1;i<=nlstate;i++)
3518: for(j=1;j<=nlstate;j++)
3519: vareij[i][j][(int)age] =0.;
3520:
3521: for(h=0;h<=nhstepm;h++){
3522: for(k=0;k<=nhstepm;k++){
3523: matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
3524: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
3525: for(i=1;i<=nlstate;i++)
3526: for(j=1;j<=nlstate;j++)
3527: vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
3528: }
3529: }
3530:
3531: /* pptj */
3532: matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
3533: matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
3534: for(j=nlstate+1;j<=nlstate+ndeath;j++)
3535: for(i=nlstate+1;i<=nlstate+ndeath;i++)
3536: varppt[j][i]=doldmp[j][i];
3537: /* end ppptj */
3538: /* x centered again */
3539: hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);
3540: prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
3541:
3542: if (popbased==1) {
3543: if(mobilav ==0){
3544: for(i=1; i<=nlstate;i++)
3545: prlim[i][i]=probs[(int)age][i][ij];
3546: }else{ /* mobilav */
3547: for(i=1; i<=nlstate;i++)
3548: prlim[i][i]=mobaverage[(int)age][i][ij];
3549: }
3550: }
3551:
3552: /* This for computing probability of death (h=1 means
3553: computed over hstepm (estepm) matrices product = hstepm*stepm months)
3554: as a weighted average of prlim.
3555: */
3556: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3557: for(i=1,gmp[j]=0.;i<= nlstate; i++)
3558: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3559: }
3560: /* end probability of death */
3561:
3562: fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
3563: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3564: fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
3565: for(i=1; i<=nlstate;i++){
3566: fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
3567: }
3568: }
3569: fprintf(ficresprobmorprev,"\n");
3570:
3571: fprintf(ficresvij,"%.0f ",age );
3572: for(i=1; i<=nlstate;i++)
3573: for(j=1; j<=nlstate;j++){
3574: fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
3575: }
3576: fprintf(ficresvij,"\n");
3577: free_matrix(gp,0,nhstepm,1,nlstate);
3578: free_matrix(gm,0,nhstepm,1,nlstate);
3579: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
3580: free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
3581: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3582: } /* End age */
3583: free_vector(gpp,nlstate+1,nlstate+ndeath);
3584: free_vector(gmp,nlstate+1,nlstate+ndeath);
3585: free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
3586: free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
3587: fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
3588: /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
3589: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
3590: /* fprintf(ficgp,"\n plot \"%s\" u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
3591: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
3592: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
3593: fprintf(ficgp,"\n plot \"%s\" u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
3594: fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)) t \"95\%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
3595: fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
3596: fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
3597: 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);
3598: /* 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);
3599: */
3600: /* fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
3601: fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
3602:
3603: free_vector(xp,1,npar);
3604: free_matrix(doldm,1,nlstate,1,nlstate);
3605: free_matrix(dnewm,1,nlstate,1,npar);
3606: free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3607: free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
3608: free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3609: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3610: fclose(ficresprobmorprev);
3611: fflush(ficgp);
3612: fflush(fichtm);
3613: } /* end varevsij */
3614:
3615: /************ Variance of prevlim ******************/
3616: 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[])
3617: {
3618: /* Variance of prevalence limit */
3619: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
3620: double **newm;
3621: double **dnewm,**doldm;
3622: int i, j, nhstepm, hstepm;
3623: int k, cptcode;
3624: double *xp;
3625: double *gp, *gm;
3626: double **gradg, **trgradg;
3627: double age,agelim;
3628: int theta;
3629:
3630: pstamp(ficresvpl);
3631: fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
3632: fprintf(ficresvpl,"# Age");
3633: for(i=1; i<=nlstate;i++)
3634: fprintf(ficresvpl," %1d-%1d",i,i);
3635: fprintf(ficresvpl,"\n");
3636:
3637: xp=vector(1,npar);
3638: dnewm=matrix(1,nlstate,1,npar);
3639: doldm=matrix(1,nlstate,1,nlstate);
3640:
3641: hstepm=1*YEARM; /* Every year of age */
3642: hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
3643: agelim = AGESUP;
3644: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3645: nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3646: if (stepm >= YEARM) hstepm=1;
3647: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
3648: gradg=matrix(1,npar,1,nlstate);
3649: gp=vector(1,nlstate);
3650: gm=vector(1,nlstate);
3651:
3652: for(theta=1; theta <=npar; theta++){
3653: for(i=1; i<=npar; i++){ /* Computes gradient */
3654: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3655: }
3656: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3657: for(i=1;i<=nlstate;i++)
3658: gp[i] = prlim[i][i];
3659:
3660: for(i=1; i<=npar; i++) /* Computes gradient */
3661: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3662: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3663: for(i=1;i<=nlstate;i++)
3664: gm[i] = prlim[i][i];
3665:
3666: for(i=1;i<=nlstate;i++)
3667: gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
3668: } /* End theta */
3669:
3670: trgradg =matrix(1,nlstate,1,npar);
3671:
3672: for(j=1; j<=nlstate;j++)
3673: for(theta=1; theta <=npar; theta++)
3674: trgradg[j][theta]=gradg[theta][j];
3675:
3676: for(i=1;i<=nlstate;i++)
3677: varpl[i][(int)age] =0.;
3678: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
3679: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
3680: for(i=1;i<=nlstate;i++)
3681: varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
3682:
3683: fprintf(ficresvpl,"%.0f ",age );
3684: for(i=1; i<=nlstate;i++)
3685: fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
3686: fprintf(ficresvpl,"\n");
3687: free_vector(gp,1,nlstate);
3688: free_vector(gm,1,nlstate);
3689: free_matrix(gradg,1,npar,1,nlstate);
3690: free_matrix(trgradg,1,nlstate,1,npar);
3691: } /* End age */
3692:
3693: free_vector(xp,1,npar);
3694: free_matrix(doldm,1,nlstate,1,npar);
3695: free_matrix(dnewm,1,nlstate,1,nlstate);
3696:
3697: }
3698:
3699: /************ Variance of one-step probabilities ******************/
3700: 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[])
3701: {
3702: int i, j=0, i1, k1, l1, t, tj;
3703: int k2, l2, j1, z1;
3704: int k=0,l, cptcode;
3705: int first=1, first1, first2;
3706: double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
3707: double **dnewm,**doldm;
3708: double *xp;
3709: double *gp, *gm;
3710: double **gradg, **trgradg;
3711: double **mu;
3712: double age,agelim, cov[NCOVMAX+1];
3713: double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
3714: int theta;
3715: char fileresprob[FILENAMELENGTH];
3716: char fileresprobcov[FILENAMELENGTH];
3717: char fileresprobcor[FILENAMELENGTH];
3718: double ***varpij;
3719:
3720: strcpy(fileresprob,"prob");
3721: strcat(fileresprob,fileres);
3722: if((ficresprob=fopen(fileresprob,"w"))==NULL) {
3723: printf("Problem with resultfile: %s\n", fileresprob);
3724: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
3725: }
3726: strcpy(fileresprobcov,"probcov");
3727: strcat(fileresprobcov,fileres);
3728: if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
3729: printf("Problem with resultfile: %s\n", fileresprobcov);
3730: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
3731: }
3732: strcpy(fileresprobcor,"probcor");
3733: strcat(fileresprobcor,fileres);
3734: if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
3735: printf("Problem with resultfile: %s\n", fileresprobcor);
3736: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
3737: }
3738: printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3739: fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3740: printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3741: fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3742: printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3743: fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3744: pstamp(ficresprob);
3745: fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
3746: fprintf(ficresprob,"# Age");
3747: pstamp(ficresprobcov);
3748: fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
3749: fprintf(ficresprobcov,"# Age");
3750: pstamp(ficresprobcor);
3751: fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
3752: fprintf(ficresprobcor,"# Age");
3753:
3754:
3755: for(i=1; i<=nlstate;i++)
3756: for(j=1; j<=(nlstate+ndeath);j++){
3757: fprintf(ficresprob," p%1d-%1d (SE)",i,j);
3758: fprintf(ficresprobcov," p%1d-%1d ",i,j);
3759: fprintf(ficresprobcor," p%1d-%1d ",i,j);
3760: }
3761: /* fprintf(ficresprob,"\n");
3762: fprintf(ficresprobcov,"\n");
3763: fprintf(ficresprobcor,"\n");
3764: */
3765: xp=vector(1,npar);
3766: dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3767: doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
3768: mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
3769: varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
3770: first=1;
3771: fprintf(ficgp,"\n# Routine varprob");
3772: fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
3773: fprintf(fichtm,"\n");
3774:
3775: fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
3776: fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
3777: file %s<br>\n",optionfilehtmcov);
3778: fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
3779: and drawn. It helps understanding how is the covariance between two incidences.\
3780: They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
3781: 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. \
3782: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
3783: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
3784: standard deviations wide on each axis. <br>\
3785: Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
3786: and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
3787: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
3788:
3789: cov[1]=1;
3790: /* tj=cptcoveff; */
3791: tj = (int) pow(2,cptcoveff);
3792: if (cptcovn<1) {tj=1;ncodemax[1]=1;}
3793: j1=0;
3794: for(j1=1; j1<=tj;j1++){
3795: /*for(i1=1; i1<=ncodemax[t];i1++){ */
3796: /*j1++;*/
3797: if (cptcovn>0) {
3798: fprintf(ficresprob, "\n#********** Variable ");
3799: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3800: fprintf(ficresprob, "**********\n#\n");
3801: fprintf(ficresprobcov, "\n#********** Variable ");
3802: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3803: fprintf(ficresprobcov, "**********\n#\n");
3804:
3805: fprintf(ficgp, "\n#********** Variable ");
3806: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3807: fprintf(ficgp, "**********\n#\n");
3808:
3809:
3810: fprintf(fichtmcov, "\n<hr size=\"2\" color=\"#EC5E5E\">********** Variable ");
3811: for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3812: fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
3813:
3814: fprintf(ficresprobcor, "\n#********** Variable ");
3815: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3816: fprintf(ficresprobcor, "**********\n#");
3817: }
3818:
3819: gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
3820: trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3821: gp=vector(1,(nlstate)*(nlstate+ndeath));
3822: gm=vector(1,(nlstate)*(nlstate+ndeath));
3823: for (age=bage; age<=fage; age ++){
3824: cov[2]=age;
3825: for (k=1; k<=cptcovn;k++) {
3826: cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
3827: * 1 1 1 1 1
3828: * 2 2 1 1 1
3829: * 3 1 2 1 1
3830: */
3831: /* nbcode[1][1]=0 nbcode[1][2]=1;*/
3832: }
3833: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
3834: for (k=1; k<=cptcovprod;k++)
3835: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
3836:
3837:
3838: for(theta=1; theta <=npar; theta++){
3839: for(i=1; i<=npar; i++)
3840: xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
3841:
3842: pmij(pmmij,cov,ncovmodel,xp,nlstate);
3843:
3844: k=0;
3845: for(i=1; i<= (nlstate); i++){
3846: for(j=1; j<=(nlstate+ndeath);j++){
3847: k=k+1;
3848: gp[k]=pmmij[i][j];
3849: }
3850: }
3851:
3852: for(i=1; i<=npar; i++)
3853: xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
3854:
3855: pmij(pmmij,cov,ncovmodel,xp,nlstate);
3856: k=0;
3857: for(i=1; i<=(nlstate); i++){
3858: for(j=1; j<=(nlstate+ndeath);j++){
3859: k=k+1;
3860: gm[k]=pmmij[i][j];
3861: }
3862: }
3863:
3864: for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
3865: gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];
3866: }
3867:
3868: for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
3869: for(theta=1; theta <=npar; theta++)
3870: trgradg[j][theta]=gradg[theta][j];
3871:
3872: matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
3873: matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
3874:
3875: pmij(pmmij,cov,ncovmodel,x,nlstate);
3876:
3877: k=0;
3878: for(i=1; i<=(nlstate); i++){
3879: for(j=1; j<=(nlstate+ndeath);j++){
3880: k=k+1;
3881: mu[k][(int) age]=pmmij[i][j];
3882: }
3883: }
3884: for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
3885: for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
3886: varpij[i][j][(int)age] = doldm[i][j];
3887:
3888: /*printf("\n%d ",(int)age);
3889: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
3890: printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
3891: fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
3892: }*/
3893:
3894: fprintf(ficresprob,"\n%d ",(int)age);
3895: fprintf(ficresprobcov,"\n%d ",(int)age);
3896: fprintf(ficresprobcor,"\n%d ",(int)age);
3897:
3898: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
3899: fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
3900: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
3901: fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
3902: fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
3903: }
3904: i=0;
3905: for (k=1; k<=(nlstate);k++){
3906: for (l=1; l<=(nlstate+ndeath);l++){
3907: i++;
3908: fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
3909: fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
3910: for (j=1; j<=i;j++){
3911: /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
3912: fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
3913: fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
3914: }
3915: }
3916: }/* end of loop for state */
3917: } /* end of loop for age */
3918: free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
3919: free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
3920: free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
3921: free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
3922:
3923: /* Confidence intervalle of pij */
3924: /*
3925: fprintf(ficgp,"\nunset parametric;unset label");
3926: fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
3927: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
3928: 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);
3929: fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
3930: fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
3931: fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
3932: */
3933:
3934: /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
3935: first1=1;first2=2;
3936: for (k2=1; k2<=(nlstate);k2++){
3937: for (l2=1; l2<=(nlstate+ndeath);l2++){
3938: if(l2==k2) continue;
3939: j=(k2-1)*(nlstate+ndeath)+l2;
3940: for (k1=1; k1<=(nlstate);k1++){
3941: for (l1=1; l1<=(nlstate+ndeath);l1++){
3942: if(l1==k1) continue;
3943: i=(k1-1)*(nlstate+ndeath)+l1;
3944: if(i<=j) continue;
3945: for (age=bage; age<=fage; age ++){
3946: if ((int)age %5==0){
3947: v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
3948: v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
3949: cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
3950: mu1=mu[i][(int) age]/stepm*YEARM ;
3951: mu2=mu[j][(int) age]/stepm*YEARM;
3952: c12=cv12/sqrt(v1*v2);
3953: /* Computing eigen value of matrix of covariance */
3954: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
3955: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
3956: if ((lc2 <0) || (lc1 <0) ){
3957: if(first2==1){
3958: first1=0;
3959: 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);
3960: }
3961: 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);
3962: /* lc1=fabs(lc1); */ /* If we want to have them positive */
3963: /* lc2=fabs(lc2); */
3964: }
3965:
3966: /* Eigen vectors */
3967: v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
3968: /*v21=sqrt(1.-v11*v11); *//* error */
3969: v21=(lc1-v1)/cv12*v11;
3970: v12=-v21;
3971: v22=v11;
3972: tnalp=v21/v11;
3973: if(first1==1){
3974: first1=0;
3975: 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);
3976: }
3977: 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);
3978: /*printf(fignu*/
3979: /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
3980: /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
3981: if(first==1){
3982: first=0;
3983: fprintf(ficgp,"\nset parametric;unset label");
3984: 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);
3985: fprintf(ficgp,"\nset ter png small size 320, 240");
3986: fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
3987: :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
3988: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
3989: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
3990: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
3991: fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
3992: fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
3993: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
3994: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
3995: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
3996: 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",\
3997: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
3998: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
3999: }else{
4000: first=0;
4001: fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
4002: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4003: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4004: 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",\
4005: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4006: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4007: }/* if first */
4008: } /* age mod 5 */
4009: } /* end loop age */
4010: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4011: first=1;
4012: } /*l12 */
4013: } /* k12 */
4014: } /*l1 */
4015: }/* k1 */
4016: /* } /* loop covariates */
4017: }
4018: free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
4019: free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
4020: free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4021: free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
4022: free_vector(xp,1,npar);
4023: fclose(ficresprob);
4024: fclose(ficresprobcov);
4025: fclose(ficresprobcor);
4026: fflush(ficgp);
4027: fflush(fichtmcov);
4028: }
4029:
4030:
4031: /******************* Printing html file ***********/
4032: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
4033: int lastpass, int stepm, int weightopt, char model[],\
4034: int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
4035: int popforecast, int estepm ,\
4036: double jprev1, double mprev1,double anprev1, \
4037: double jprev2, double mprev2,double anprev2){
4038: int jj1, k1, i1, cpt;
4039:
4040: fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
4041: <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
4042: </ul>");
4043: fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
4044: - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
4045: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
4046: fprintf(fichtm,"\
4047: - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
4048: stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
4049: fprintf(fichtm,"\
4050: - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
4051: subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
4052: fprintf(fichtm,"\
4053: - (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): \
4054: <a href=\"%s\">%s</a> <br>\n",
4055: estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
4056: fprintf(fichtm,"\
4057: - Population projections by age and states: \
4058: <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
4059:
4060: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
4061:
4062: m=pow(2,cptcoveff);
4063: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4064:
4065: jj1=0;
4066: for(k1=1; k1<=m;k1++){
4067: for(i1=1; i1<=ncodemax[k1];i1++){
4068: jj1++;
4069: if (cptcovn > 0) {
4070: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4071: for (cpt=1; cpt<=cptcoveff;cpt++)
4072: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4073: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4074: }
4075: /* Pij */
4076: 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> \
4077: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
4078: /* Quasi-incidences */
4079: fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
4080: 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> \
4081: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
4082: /* Period (stable) prevalence in each health state */
4083: for(cpt=1; cpt<=nlstate;cpt++){
4084: 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> \
4085: <img src=\"%s%d_%d.png\">",nlstate, cpt, subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
4086: }
4087: for(cpt=1; cpt<=nlstate;cpt++) {
4088: 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> \
4089: <img src=\"%s%d%d.png\">",cpt,nlstate,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
4090: }
4091: } /* end i1 */
4092: }/* End k1 */
4093: fprintf(fichtm,"</ul>");
4094:
4095:
4096: fprintf(fichtm,"\
4097: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
4098: - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
4099:
4100: fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4101: subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
4102: fprintf(fichtm,"\
4103: - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4104: subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
4105:
4106: fprintf(fichtm,"\
4107: - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4108: subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
4109: fprintf(fichtm,"\
4110: - 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): \
4111: <a href=\"%s\">%s</a> <br>\n</li>",
4112: estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
4113: fprintf(fichtm,"\
4114: - (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): \
4115: <a href=\"%s\">%s</a> <br>\n</li>",
4116: estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
4117: fprintf(fichtm,"\
4118: - 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",
4119: estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
4120: fprintf(fichtm,"\
4121: - 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",
4122: estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
4123: fprintf(fichtm,"\
4124: - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
4125: subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
4126:
4127: /* if(popforecast==1) fprintf(fichtm,"\n */
4128: /* - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
4129: /* - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
4130: /* <br>",fileres,fileres,fileres,fileres); */
4131: /* else */
4132: /* 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); */
4133: fflush(fichtm);
4134: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
4135:
4136: m=pow(2,cptcoveff);
4137: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4138:
4139: jj1=0;
4140: for(k1=1; k1<=m;k1++){
4141: for(i1=1; i1<=ncodemax[k1];i1++){
4142: jj1++;
4143: if (cptcovn > 0) {
4144: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4145: for (cpt=1; cpt<=cptcoveff;cpt++)
4146: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4147: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4148: }
4149: for(cpt=1; cpt<=nlstate;cpt++) {
4150: fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
4151: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
4152: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);
4153: }
4154: fprintf(fichtm,"\n<br>- Total life expectancy by age and \
4155: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
4156: true period expectancies (those weighted with period prevalences are also\
4157: drawn in addition to the population based expectancies computed using\
4158: observed and cahotic prevalences: %s%d.png<br>\
4159: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
4160: } /* end i1 */
4161: }/* End k1 */
4162: fprintf(fichtm,"</ul>");
4163: fflush(fichtm);
4164: }
4165:
4166: /******************* Gnuplot file **************/
4167: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4168:
4169: char dirfileres[132],optfileres[132];
4170: int m0,cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
4171: int ng=0;
4172: /* if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
4173: /* printf("Problem with file %s",optionfilegnuplot); */
4174: /* fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
4175: /* } */
4176:
4177: /*#ifdef windows */
4178: fprintf(ficgp,"cd \"%s\" \n",pathc);
4179: /*#endif */
4180: m=pow(2,cptcoveff);
4181:
4182: strcpy(dirfileres,optionfilefiname);
4183: strcpy(optfileres,"vpl");
4184: /* 1eme*/
4185: fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
4186: for (cpt=1; cpt<= nlstate ; cpt ++) {
4187: for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
4188: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
4189: fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
4190: fprintf(ficgp,"set xlabel \"Age\" \n\
4191: set ylabel \"Probability\" \n\
4192: set ter png small size 320, 240\n\
4193: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
4194:
4195: for (i=1; i<= nlstate ; i ++) {
4196: if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
4197: else fprintf(ficgp," \%%*lf (\%%*lf)");
4198: }
4199: 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);
4200: for (i=1; i<= nlstate ; i ++) {
4201: if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
4202: else fprintf(ficgp," \%%*lf (\%%*lf)");
4203: }
4204: 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);
4205: for (i=1; i<= nlstate ; i ++) {
4206: if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
4207: else fprintf(ficgp," \%%*lf (\%%*lf)");
4208: }
4209: 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));
4210: }
4211: }
4212: /*2 eme*/
4213: fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
4214: for (k1=1; k1<= m ; k1 ++) {
4215: fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
4216: fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
4217:
4218: for (i=1; i<= nlstate+1 ; i ++) {
4219: k=2*i;
4220: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4221: for (j=1; j<= nlstate+1 ; j ++) {
4222: if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
4223: else fprintf(ficgp," \%%*lf (\%%*lf)");
4224: }
4225: if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
4226: else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
4227: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4228: for (j=1; j<= nlstate+1 ; j ++) {
4229: if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
4230: else fprintf(ficgp," \%%*lf (\%%*lf)");
4231: }
4232: fprintf(ficgp,"\" t\"\" w l lt 0,");
4233: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4234: for (j=1; j<= nlstate+1 ; j ++) {
4235: if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
4236: else fprintf(ficgp," \%%*lf (\%%*lf)");
4237: }
4238: if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
4239: else fprintf(ficgp,"\" t\"\" w l lt 0,");
4240: }
4241: }
4242:
4243: /*3eme*/
4244:
4245: for (k1=1; k1<= m ; k1 ++) {
4246: for (cpt=1; cpt<= nlstate ; cpt ++) {
4247: /* k=2+nlstate*(2*cpt-2); */
4248: k=2+(nlstate+1)*(cpt-1);
4249: fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
4250: fprintf(ficgp,"set ter png small size 320, 240\n\
4251: 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);
4252: /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4253: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4254: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4255: fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4256: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4257: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4258:
4259: */
4260: for (i=1; i< nlstate ; i ++) {
4261: 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);
4262: /* 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);*/
4263:
4264: }
4265: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
4266: }
4267: }
4268:
4269: /* CV preval stable (period) */
4270: for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
4271: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
4272: k=3;
4273: fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
4274: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
4275: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
4276: set ter png small size 320, 240\n\
4277: unset log y\n\
4278: plot [%.f:%.f] ", ageminpar, agemaxpar);
4279: for (i=1; i<= nlstate ; i ++){
4280: if(i==1)
4281: fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
4282: else
4283: fprintf(ficgp,", '' ");
4284: l=(nlstate+ndeath)*(i-1)+1;
4285: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
4286: for (j=1; j<= (nlstate-1) ; j ++)
4287: fprintf(ficgp,"+$%d",k+l+j);
4288: fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
4289: } /* nlstate */
4290: fprintf(ficgp,"\n");
4291: } /* end cpt state*/
4292: } /* end covariate */
4293:
4294: /* proba elementaires */
4295: for(i=1,jk=1; i <=nlstate; i++){
4296: for(k=1; k <=(nlstate+ndeath); k++){
4297: if (k != i) {
4298: for(j=1; j <=ncovmodel; j++){
4299: fprintf(ficgp,"p%d=%f ",jk,p[jk]);
4300: jk++;
4301: fprintf(ficgp,"\n");
4302: }
4303: }
4304: }
4305: }
4306: /*goto avoid;*/
4307: for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
4308: for(jk=1; jk <=m; jk++) {
4309: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);
4310: if (ng==2)
4311: fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
4312: else
4313: fprintf(ficgp,"\nset title \"Probability\"\n");
4314: fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot [%.f:%.f] ",ageminpar,agemaxpar);
4315: i=1;
4316: for(k2=1; k2<=nlstate; k2++) {
4317: k3=i;
4318: for(k=1; k<=(nlstate+ndeath); k++) {
4319: if (k != k2){
4320: if(ng==2)
4321: fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
4322: else
4323: fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
4324: ij=1;/* To be checked else nbcode[0][0] wrong */
4325: for(j=3; j <=ncovmodel; j++) {
4326: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /\* Bug valgrind *\/ */
4327: /* /\*fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);*\/ */
4328: /* ij++; */
4329: /* } */
4330: /* else */
4331: fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4332: }
4333: fprintf(ficgp,")/(1");
4334:
4335: for(k1=1; k1 <=nlstate; k1++){
4336: fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
4337: ij=1;
4338: for(j=3; j <=ncovmodel; j++){
4339: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { */
4340: /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]); */
4341: /* ij++; */
4342: /* } */
4343: /* else */
4344: fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4345: }
4346: fprintf(ficgp,")");
4347: }
4348: fprintf(ficgp,") t \"p%d%d\" ", k2,k);
4349: if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
4350: i=i+ncovmodel;
4351: }
4352: } /* end k */
4353: } /* end k2 */
4354: } /* end jk */
4355: } /* end ng */
4356: avoid:
4357: fflush(ficgp);
4358: } /* end gnuplot */
4359:
4360:
4361: /*************** Moving average **************/
4362: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
4363:
4364: int i, cpt, cptcod;
4365: int modcovmax =1;
4366: int mobilavrange, mob;
4367: double age;
4368:
4369: modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
4370: a covariate has 2 modalities */
4371: if (cptcovn<1) modcovmax=1; /* At least 1 pass */
4372:
4373: if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
4374: if(mobilav==1) mobilavrange=5; /* default */
4375: else mobilavrange=mobilav;
4376: for (age=bage; age<=fage; age++)
4377: for (i=1; i<=nlstate;i++)
4378: for (cptcod=1;cptcod<=modcovmax;cptcod++)
4379: mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
4380: /* We keep the original values on the extreme ages bage, fage and for
4381: fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
4382: we use a 5 terms etc. until the borders are no more concerned.
4383: */
4384: for (mob=3;mob <=mobilavrange;mob=mob+2){
4385: for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
4386: for (i=1; i<=nlstate;i++){
4387: for (cptcod=1;cptcod<=modcovmax;cptcod++){
4388: mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
4389: for (cpt=1;cpt<=(mob-1)/2;cpt++){
4390: mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
4391: mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
4392: }
4393: mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
4394: }
4395: }
4396: }/* end age */
4397: }/* end mob */
4398: }else return -1;
4399: return 0;
4400: }/* End movingaverage */
4401:
4402:
4403: /************** Forecasting ******************/
4404: 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){
4405: /* proj1, year, month, day of starting projection
4406: agemin, agemax range of age
4407: dateprev1 dateprev2 range of dates during which prevalence is computed
4408: anproj2 year of en of projection (same day and month as proj1).
4409: */
4410: int yearp, stepsize, hstepm, nhstepm, j, k, c, cptcod, i, h, i1;
4411: int *popage;
4412: double agec; /* generic age */
4413: double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
4414: double *popeffectif,*popcount;
4415: double ***p3mat;
4416: double ***mobaverage;
4417: char fileresf[FILENAMELENGTH];
4418:
4419: agelim=AGESUP;
4420: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4421:
4422: strcpy(fileresf,"f");
4423: strcat(fileresf,fileres);
4424: if((ficresf=fopen(fileresf,"w"))==NULL) {
4425: printf("Problem with forecast resultfile: %s\n", fileresf);
4426: fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
4427: }
4428: printf("Computing forecasting: result on file '%s' \n", fileresf);
4429: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
4430:
4431: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4432:
4433: if (mobilav!=0) {
4434: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4435: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4436: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4437: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4438: }
4439: }
4440:
4441: stepsize=(int) (stepm+YEARM-1)/YEARM;
4442: if (stepm<=12) stepsize=1;
4443: if(estepm < stepm){
4444: printf ("Problem %d lower than %d\n",estepm, stepm);
4445: }
4446: else hstepm=estepm;
4447:
4448: hstepm=hstepm/stepm;
4449: yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp and
4450: fractional in yp1 */
4451: anprojmean=yp;
4452: yp2=modf((yp1*12),&yp);
4453: mprojmean=yp;
4454: yp1=modf((yp2*30.5),&yp);
4455: jprojmean=yp;
4456: if(jprojmean==0) jprojmean=1;
4457: if(mprojmean==0) jprojmean=1;
4458:
4459: i1=cptcoveff;
4460: if (cptcovn < 1){i1=1;}
4461:
4462: fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
4463:
4464: fprintf(ficresf,"#****** Routine prevforecast **\n");
4465:
4466: /* if (h==(int)(YEARM*yearp)){ */
4467: for(cptcov=1, k=0;cptcov<=i1;cptcov++){
4468: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4469: k=k+1;
4470: fprintf(ficresf,"\n#******");
4471: for(j=1;j<=cptcoveff;j++) {
4472: 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]]);
4473: }
4474: fprintf(ficresf,"******\n");
4475: fprintf(ficresf,"# Covariate valuofcovar yearproj age");
4476: for(j=1; j<=nlstate+ndeath;j++){
4477: for(i=1; i<=nlstate;i++)
4478: fprintf(ficresf," p%d%d",i,j);
4479: fprintf(ficresf," p.%d",j);
4480: }
4481: for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
4482: fprintf(ficresf,"\n");
4483: fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);
4484:
4485: for (agec=fage; agec>=(ageminpar-1); agec--){
4486: nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
4487: nhstepm = nhstepm/hstepm;
4488: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4489: oldm=oldms;savm=savms;
4490: hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
4491:
4492: for (h=0; h<=nhstepm; h++){
4493: if (h*hstepm/YEARM*stepm ==yearp) {
4494: fprintf(ficresf,"\n");
4495: for(j=1;j<=cptcoveff;j++)
4496: fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4497: fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
4498: }
4499: for(j=1; j<=nlstate+ndeath;j++) {
4500: ppij=0.;
4501: for(i=1; i<=nlstate;i++) {
4502: if (mobilav==1)
4503: ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
4504: else {
4505: ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
4506: }
4507: if (h*hstepm/YEARM*stepm== yearp) {
4508: fprintf(ficresf," %.3f", p3mat[i][j][h]);
4509: }
4510: } /* end i */
4511: if (h*hstepm/YEARM*stepm==yearp) {
4512: fprintf(ficresf," %.3f", ppij);
4513: }
4514: }/* end j */
4515: } /* end h */
4516: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4517: } /* end agec */
4518: } /* end yearp */
4519: } /* end cptcod */
4520: } /* end cptcov */
4521:
4522: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4523:
4524: fclose(ficresf);
4525: }
4526:
4527: /************** Forecasting *****not tested NB*************/
4528: 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){
4529:
4530: int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
4531: int *popage;
4532: double calagedatem, agelim, kk1, kk2;
4533: double *popeffectif,*popcount;
4534: double ***p3mat,***tabpop,***tabpopprev;
4535: double ***mobaverage;
4536: char filerespop[FILENAMELENGTH];
4537:
4538: tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4539: tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4540: agelim=AGESUP;
4541: calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
4542:
4543: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4544:
4545:
4546: strcpy(filerespop,"pop");
4547: strcat(filerespop,fileres);
4548: if((ficrespop=fopen(filerespop,"w"))==NULL) {
4549: printf("Problem with forecast resultfile: %s\n", filerespop);
4550: fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
4551: }
4552: printf("Computing forecasting: result on file '%s' \n", filerespop);
4553: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
4554:
4555: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4556:
4557: if (mobilav!=0) {
4558: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4559: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4560: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4561: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4562: }
4563: }
4564:
4565: stepsize=(int) (stepm+YEARM-1)/YEARM;
4566: if (stepm<=12) stepsize=1;
4567:
4568: agelim=AGESUP;
4569:
4570: hstepm=1;
4571: hstepm=hstepm/stepm;
4572:
4573: if (popforecast==1) {
4574: if((ficpop=fopen(popfile,"r"))==NULL) {
4575: printf("Problem with population file : %s\n",popfile);exit(0);
4576: fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
4577: }
4578: popage=ivector(0,AGESUP);
4579: popeffectif=vector(0,AGESUP);
4580: popcount=vector(0,AGESUP);
4581:
4582: i=1;
4583: while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
4584:
4585: imx=i;
4586: for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
4587: }
4588:
4589: for(cptcov=1,k=0;cptcov<=i2;cptcov++){
4590: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4591: k=k+1;
4592: fprintf(ficrespop,"\n#******");
4593: for(j=1;j<=cptcoveff;j++) {
4594: fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4595: }
4596: fprintf(ficrespop,"******\n");
4597: fprintf(ficrespop,"# Age");
4598: for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
4599: if (popforecast==1) fprintf(ficrespop," [Population]");
4600:
4601: for (cpt=0; cpt<=0;cpt++) {
4602: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4603:
4604: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4605: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4606: nhstepm = nhstepm/hstepm;
4607:
4608: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4609: oldm=oldms;savm=savms;
4610: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4611:
4612: for (h=0; h<=nhstepm; h++){
4613: if (h==(int) (calagedatem+YEARM*cpt)) {
4614: fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4615: }
4616: for(j=1; j<=nlstate+ndeath;j++) {
4617: kk1=0.;kk2=0;
4618: for(i=1; i<=nlstate;i++) {
4619: if (mobilav==1)
4620: kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
4621: else {
4622: kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
4623: }
4624: }
4625: if (h==(int)(calagedatem+12*cpt)){
4626: tabpop[(int)(agedeb)][j][cptcod]=kk1;
4627: /*fprintf(ficrespop," %.3f", kk1);
4628: if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
4629: }
4630: }
4631: for(i=1; i<=nlstate;i++){
4632: kk1=0.;
4633: for(j=1; j<=nlstate;j++){
4634: kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
4635: }
4636: tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
4637: }
4638:
4639: if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
4640: fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
4641: }
4642: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4643: }
4644: }
4645:
4646: /******/
4647:
4648: for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
4649: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4650: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4651: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4652: nhstepm = nhstepm/hstepm;
4653:
4654: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4655: oldm=oldms;savm=savms;
4656: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4657: for (h=0; h<=nhstepm; h++){
4658: if (h==(int) (calagedatem+YEARM*cpt)) {
4659: fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4660: }
4661: for(j=1; j<=nlstate+ndeath;j++) {
4662: kk1=0.;kk2=0;
4663: for(i=1; i<=nlstate;i++) {
4664: kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];
4665: }
4666: if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);
4667: }
4668: }
4669: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4670: }
4671: }
4672: }
4673: }
4674:
4675: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4676:
4677: if (popforecast==1) {
4678: free_ivector(popage,0,AGESUP);
4679: free_vector(popeffectif,0,AGESUP);
4680: free_vector(popcount,0,AGESUP);
4681: }
4682: free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4683: free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4684: fclose(ficrespop);
4685: } /* End of popforecast */
4686:
4687: int fileappend(FILE *fichier, char *optionfich)
4688: {
4689: if((fichier=fopen(optionfich,"a"))==NULL) {
4690: printf("Problem with file: %s\n", optionfich);
4691: fprintf(ficlog,"Problem with file: %s\n", optionfich);
4692: return (0);
4693: }
4694: fflush(fichier);
4695: return (1);
4696: }
4697:
4698:
4699: /**************** function prwizard **********************/
4700: void prwizard(int ncovmodel, int nlstate, int ndeath, char model[], FILE *ficparo)
4701: {
4702:
4703: /* Wizard to print covariance matrix template */
4704:
4705: char ca[32], cb[32], cc[32];
4706: int i,j, k, l, li, lj, lk, ll, jj, npar, itimes;
4707: int numlinepar;
4708:
4709: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4710: fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4711: for(i=1; i <=nlstate; i++){
4712: jj=0;
4713: for(j=1; j <=nlstate+ndeath; j++){
4714: if(j==i) continue;
4715: jj++;
4716: /*ca[0]= k+'a'-1;ca[1]='\0';*/
4717: printf("%1d%1d",i,j);
4718: fprintf(ficparo,"%1d%1d",i,j);
4719: for(k=1; k<=ncovmodel;k++){
4720: /* printf(" %lf",param[i][j][k]); */
4721: /* fprintf(ficparo," %lf",param[i][j][k]); */
4722: printf(" 0.");
4723: fprintf(ficparo," 0.");
4724: }
4725: printf("\n");
4726: fprintf(ficparo,"\n");
4727: }
4728: }
4729: printf("# Scales (for hessian or gradient estimation)\n");
4730: fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
4731: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
4732: for(i=1; i <=nlstate; i++){
4733: jj=0;
4734: for(j=1; j <=nlstate+ndeath; j++){
4735: if(j==i) continue;
4736: jj++;
4737: fprintf(ficparo,"%1d%1d",i,j);
4738: printf("%1d%1d",i,j);
4739: fflush(stdout);
4740: for(k=1; k<=ncovmodel;k++){
4741: /* printf(" %le",delti3[i][j][k]); */
4742: /* fprintf(ficparo," %le",delti3[i][j][k]); */
4743: printf(" 0.");
4744: fprintf(ficparo," 0.");
4745: }
4746: numlinepar++;
4747: printf("\n");
4748: fprintf(ficparo,"\n");
4749: }
4750: }
4751: printf("# Covariance matrix\n");
4752: /* # 121 Var(a12)\n\ */
4753: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4754: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
4755: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
4756: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
4757: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
4758: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
4759: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4760: fflush(stdout);
4761: fprintf(ficparo,"# Covariance matrix\n");
4762: /* # 121 Var(a12)\n\ */
4763: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4764: /* # ...\n\ */
4765: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4766:
4767: for(itimes=1;itimes<=2;itimes++){
4768: jj=0;
4769: for(i=1; i <=nlstate; i++){
4770: for(j=1; j <=nlstate+ndeath; j++){
4771: if(j==i) continue;
4772: for(k=1; k<=ncovmodel;k++){
4773: jj++;
4774: ca[0]= k+'a'-1;ca[1]='\0';
4775: if(itimes==1){
4776: printf("#%1d%1d%d",i,j,k);
4777: fprintf(ficparo,"#%1d%1d%d",i,j,k);
4778: }else{
4779: printf("%1d%1d%d",i,j,k);
4780: fprintf(ficparo,"%1d%1d%d",i,j,k);
4781: /* printf(" %.5le",matcov[i][j]); */
4782: }
4783: ll=0;
4784: for(li=1;li <=nlstate; li++){
4785: for(lj=1;lj <=nlstate+ndeath; lj++){
4786: if(lj==li) continue;
4787: for(lk=1;lk<=ncovmodel;lk++){
4788: ll++;
4789: if(ll<=jj){
4790: cb[0]= lk +'a'-1;cb[1]='\0';
4791: if(ll<jj){
4792: if(itimes==1){
4793: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4794: fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4795: }else{
4796: printf(" 0.");
4797: fprintf(ficparo," 0.");
4798: }
4799: }else{
4800: if(itimes==1){
4801: printf(" Var(%s%1d%1d)",ca,i,j);
4802: fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
4803: }else{
4804: printf(" 0.");
4805: fprintf(ficparo," 0.");
4806: }
4807: }
4808: }
4809: } /* end lk */
4810: } /* end lj */
4811: } /* end li */
4812: printf("\n");
4813: fprintf(ficparo,"\n");
4814: numlinepar++;
4815: } /* end k*/
4816: } /*end j */
4817: } /* end i */
4818: } /* end itimes */
4819:
4820: } /* end of prwizard */
4821: /******************* Gompertz Likelihood ******************************/
4822: double gompertz(double x[])
4823: {
4824: double A,B,L=0.0,sump=0.,num=0.;
4825: int i,n=0; /* n is the size of the sample */
4826:
4827: for (i=0;i<=imx-1 ; i++) {
4828: sump=sump+weight[i];
4829: /* sump=sump+1;*/
4830: num=num+1;
4831: }
4832:
4833:
4834: /* for (i=0; i<=imx; i++)
4835: 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]);*/
4836:
4837: for (i=1;i<=imx ; i++)
4838: {
4839: if (cens[i] == 1 && wav[i]>1)
4840: A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
4841:
4842: if (cens[i] == 0 && wav[i]>1)
4843: A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
4844: +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);
4845:
4846: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
4847: if (wav[i] > 1 ) { /* ??? */
4848: L=L+A*weight[i];
4849: /* 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]);*/
4850: }
4851: }
4852:
4853: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
4854:
4855: return -2*L*num/sump;
4856: }
4857:
4858: #ifdef GSL
4859: /******************* Gompertz_f Likelihood ******************************/
4860: double gompertz_f(const gsl_vector *v, void *params)
4861: {
4862: double A,B,LL=0.0,sump=0.,num=0.;
4863: double *x= (double *) v->data;
4864: int i,n=0; /* n is the size of the sample */
4865:
4866: for (i=0;i<=imx-1 ; i++) {
4867: sump=sump+weight[i];
4868: /* sump=sump+1;*/
4869: num=num+1;
4870: }
4871:
4872:
4873: /* for (i=0; i<=imx; i++)
4874: 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]);*/
4875: printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
4876: for (i=1;i<=imx ; i++)
4877: {
4878: if (cens[i] == 1 && wav[i]>1)
4879: A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
4880:
4881: if (cens[i] == 0 && wav[i]>1)
4882: A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
4883: +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);
4884:
4885: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
4886: if (wav[i] > 1 ) { /* ??? */
4887: LL=LL+A*weight[i];
4888: /* 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]);*/
4889: }
4890: }
4891:
4892: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
4893: printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
4894:
4895: return -2*LL*num/sump;
4896: }
4897: #endif
4898:
4899: /******************* Printing html file ***********/
4900: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
4901: int lastpass, int stepm, int weightopt, char model[],\
4902: int imx, double p[],double **matcov,double agemortsup){
4903: int i,k;
4904:
4905: fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
4906: fprintf(fichtm," mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
4907: for (i=1;i<=2;i++)
4908: 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]));
4909: fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
4910: fprintf(fichtm,"</ul>");
4911:
4912: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
4913:
4914: 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>");
4915:
4916: for (k=agegomp;k<(agemortsup-2);k++)
4917: 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]);
4918:
4919:
4920: fflush(fichtm);
4921: }
4922:
4923: /******************* Gnuplot file **************/
4924: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4925:
4926: char dirfileres[132],optfileres[132];
4927: int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;
4928: int ng;
4929:
4930:
4931: /*#ifdef windows */
4932: fprintf(ficgp,"cd \"%s\" \n",pathc);
4933: /*#endif */
4934:
4935:
4936: strcpy(dirfileres,optionfilefiname);
4937: strcpy(optfileres,"vpl");
4938: fprintf(ficgp,"set out \"graphmort.png\"\n ");
4939: fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
4940: fprintf(ficgp, "set ter png small size 320, 240\n set log y\n");
4941: /* fprintf(ficgp, "set size 0.65,0.65\n"); */
4942: fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
4943:
4944: }
4945:
4946: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
4947: {
4948:
4949: /*-------- data file ----------*/
4950: FILE *fic;
4951: char dummy[]=" ";
4952: int i, j, n;
4953: int linei, month, year,iout;
4954: char line[MAXLINE], linetmp[MAXLINE];
4955: char stra[80], strb[80];
4956: char *stratrunc;
4957: int lstra;
4958:
4959:
4960: if((fic=fopen(datafile,"r"))==NULL) {
4961: printf("Problem while opening datafile: %s\n", datafile);return 1;
4962: fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
4963: }
4964:
4965: i=1;
4966: linei=0;
4967: while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
4968: linei=linei+1;
4969: for(j=strlen(line); j>=0;j--){ /* Untabifies line */
4970: if(line[j] == '\t')
4971: line[j] = ' ';
4972: }
4973: for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
4974: ;
4975: };
4976: line[j+1]=0; /* Trims blanks at end of line */
4977: if(line[0]=='#'){
4978: fprintf(ficlog,"Comment line\n%s\n",line);
4979: printf("Comment line\n%s\n",line);
4980: continue;
4981: }
4982: trimbb(linetmp,line); /* Trims multiple blanks in line */
4983: for (j=0; line[j]!='\0';j++){
4984: line[j]=linetmp[j];
4985: }
4986:
4987:
4988: for (j=maxwav;j>=1;j--){
4989: cutv(stra, strb, line, ' ');
4990: if(strb[0]=='.') { /* Missing status */
4991: lval=-1;
4992: }else{
4993: errno=0;
4994: lval=strtol(strb,&endptr,10);
4995: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
4996: if( strb[0]=='\0' || (*endptr != '\0')){
4997: 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);
4998: 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);
4999: return 1;
5000: }
5001: }
5002: s[j][i]=lval;
5003:
5004: strcpy(line,stra);
5005: cutv(stra, strb,line,' ');
5006: if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
5007: }
5008: else if(iout=sscanf(strb,"%s.",dummy) != 0){
5009: month=99;
5010: year=9999;
5011: }else{
5012: 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);
5013: 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);
5014: return 1;
5015: }
5016: anint[j][i]= (double) year;
5017: mint[j][i]= (double)month;
5018: strcpy(line,stra);
5019: } /* ENd Waves */
5020:
5021: cutv(stra, strb,line,' ');
5022: if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
5023: }
5024: else if(iout=sscanf(strb,"%s.",dummy) != 0){
5025: month=99;
5026: year=9999;
5027: }else{
5028: 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);
5029: 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);
5030: return 1;
5031: }
5032: andc[i]=(double) year;
5033: moisdc[i]=(double) month;
5034: strcpy(line,stra);
5035:
5036: cutv(stra, strb,line,' ');
5037: if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
5038: }
5039: else if(iout=sscanf(strb,"%s.", dummy) != 0){
5040: month=99;
5041: year=9999;
5042: }else{
5043: 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);
5044: 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);
5045: return 1;
5046: }
5047: if (year==9999) {
5048: 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);
5049: 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);
5050: return 1;
5051:
5052: }
5053: annais[i]=(double)(year);
5054: moisnais[i]=(double)(month);
5055: strcpy(line,stra);
5056:
5057: cutv(stra, strb,line,' ');
5058: errno=0;
5059: dval=strtod(strb,&endptr);
5060: if( strb[0]=='\0' || (*endptr != '\0')){
5061: printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight. Exiting.\n",dval, i,line,linei);
5062: 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);
5063: fflush(ficlog);
5064: return 1;
5065: }
5066: weight[i]=dval;
5067: strcpy(line,stra);
5068:
5069: for (j=ncovcol;j>=1;j--){
5070: cutv(stra, strb,line,' ');
5071: if(strb[0]=='.') { /* Missing status */
5072: lval=-1;
5073: }else{
5074: errno=0;
5075: lval=strtol(strb,&endptr,10);
5076: if( strb[0]=='\0' || (*endptr != '\0')){
5077: 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);
5078: 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);
5079: return 1;
5080: }
5081: }
5082: if(lval <-1 || lval >1){
5083: printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
5084: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5085: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5086: For example, for multinomial values like 1, 2 and 3,\n \
5087: build V1=0 V2=0 for the reference value (1),\n \
5088: V1=1 V2=0 for (2) \n \
5089: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5090: output of IMaCh is often meaningless.\n \
5091: Exiting.\n",lval,linei, i,line,j);
5092: fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
5093: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5094: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5095: For example, for multinomial values like 1, 2 and 3,\n \
5096: build V1=0 V2=0 for the reference value (1),\n \
5097: V1=1 V2=0 for (2) \n \
5098: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5099: output of IMaCh is often meaningless.\n \
5100: Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
5101: return 1;
5102: }
5103: covar[j][i]=(double)(lval);
5104: strcpy(line,stra);
5105: }
5106: lstra=strlen(stra);
5107:
5108: if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
5109: stratrunc = &(stra[lstra-9]);
5110: num[i]=atol(stratrunc);
5111: }
5112: else
5113: num[i]=atol(stra);
5114: /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
5115: 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;}*/
5116:
5117: i=i+1;
5118: } /* End loop reading data */
5119:
5120: *imax=i-1; /* Number of individuals */
5121: fclose(fic);
5122:
5123: return (0);
5124: endread:
5125: printf("Exiting readdata: ");
5126: fclose(fic);
5127: return (1);
5128:
5129:
5130:
5131: }
5132: void removespace(char *str) {
5133: char *p1 = str, *p2 = str;
5134: do
5135: while (*p2 == ' ')
5136: p2++;
5137: while (*p1++ = *p2++);
5138: }
5139:
5140: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
5141: * Model V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age
5142: * - cptcovt total number of covariates of the model nbocc(+)+1 = 8
5143: * - cptcovn or number of covariates k of the models excluding age*products =6
5144: * - cptcovage number of covariates with age*products =2
5145: * - cptcovs number of simple covariates
5146: * - 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
5147: * which is a new column after the 9 (ncovcol) variables.
5148: * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
5149: * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
5150: * Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
5151: * - Tvard[k] p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
5152: */
5153: {
5154: int i, j, k, ks;
5155: int i1, j1, k1, k2;
5156: char modelsav[80];
5157: char stra[80], strb[80], strc[80], strd[80],stre[80];
5158:
5159: /*removespace(model);*/
5160: if (strlen(model) >1){ /* If there is at least 1 covariate */
5161: j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
5162: j=nbocc(model,'+'); /**< j=Number of '+' */
5163: j1=nbocc(model,'*'); /**< j1=Number of '*' */
5164: cptcovs=j+1-j1; /**< Number of simple covariates V1+V2*age+V3 +V3*V4=> V1 + V3 =2 */
5165: cptcovt= j+1; /* Number of total covariates in the model V1 + V2*age+ V3 + V3*V4=> 4*/
5166: /* including age products which are counted in cptcovage.
5167: /* but the covariates which are products must be treated separately: ncovn=4- 2=2 (V1+V3). */
5168: cptcovprod=j1; /**< Number of products V1*V2 +v3*age = 2 */
5169: cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1 */
5170: strcpy(modelsav,model);
5171: if (strstr(model,"AGE") !=0){
5172: printf("Error. AGE must be in lower case 'age' model=%s ",model);
5173: fprintf(ficlog,"Error. AGE must be in lower case model=%s ",model);fflush(ficlog);
5174: return 1;
5175: }
5176: if (strstr(model,"v") !=0){
5177: printf("Error. 'v' must be in upper case 'V' model=%s ",model);
5178: fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
5179: return 1;
5180: }
5181:
5182: /* Design
5183: * V1 V2 V3 V4 V5 V6 V7 V8 V9 Weight
5184: * < ncovcol=8 >
5185: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
5186: * k= 1 2 3 4 5 6 7 8
5187: * cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
5188: * covar[k,i], value of kth covariate if not including age for individual i:
5189: * covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
5190: * Tvar[k] # of the kth covariate: Tvar[1]=2 Tvar[4]=3 Tvar[8]=8
5191: * if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and
5192: * Tage[++cptcovage]=k
5193: * if products, new covar are created after ncovcol with k1
5194: * Tvar[k]=ncovcol+k1; # of the kth covariate product: Tvar[5]=ncovcol+1=10 Tvar[6]=ncovcol+1=11
5195: * Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
5196: * 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
5197: * Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
5198: * Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
5199: * V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
5200: * < ncovcol=8 >
5201: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 d1 d1 d2 d2
5202: * k= 1 2 3 4 5 6 7 8 9 10 11 12
5203: * Tvar[k]= 2 1 3 3 10 11 8 8 5 6 7 8
5204: * p Tvar[1]@12={2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5205: * p Tprod[1]@2={ 6, 5}
5206: *p Tvard[1][1]@4= {7, 8, 5, 6}
5207: * covar[k][i]= V2 V1 ? V3 V5*V6? V7*V8? ? V8
5208: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
5209: *How to reorganize?
5210: * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
5211: * Tvars {2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5212: * {2, 1, 4, 8, 5, 6, 3, 7}
5213: * Struct []
5214: */
5215:
5216: /* This loop fills the array Tvar from the string 'model'.*/
5217: /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
5218: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 */
5219: /* k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
5220: /* k=3 V4 Tvar[k=3]= 4 (from V4) */
5221: /* k=2 V1 Tvar[k=2]= 1 (from V1) */
5222: /* k=1 Tvar[1]=2 (from V2) */
5223: /* k=5 Tvar[5] */
5224: /* for (k=1; k<=cptcovn;k++) { */
5225: /* cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
5226: /* } */
5227: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
5228: /*
5229: * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
5230: for(k=cptcovt; k>=1;k--) /**< Number of covariates */
5231: Tvar[k]=0;
5232: cptcovage=0;
5233: for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
5234: cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+'
5235: modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */
5236: if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
5237: /* printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
5238: /*scanf("%d",i);*/
5239: if (strchr(strb,'*')) { /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
5240: cutl(strc,strd,strb,'*'); /**< strd*strc Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
5241: if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
5242: /* covar is not filled and then is empty */
5243: cptcovprod--;
5244: cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
5245: Tvar[k]=atoi(stre); /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2 */
5246: cptcovage++; /* Sums the number of covariates which include age as a product */
5247: Tage[cptcovage]=k; /* Tage[1] = 4 */
5248: /*printf("stre=%s ", stre);*/
5249: } else if (strcmp(strd,"age")==0) { /* or age*Vn */
5250: cptcovprod--;
5251: cutl(stre,strb,strc,'V');
5252: Tvar[k]=atoi(stre);
5253: cptcovage++;
5254: Tage[cptcovage]=k;
5255: } else { /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2 strb=V3*V2*/
5256: /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
5257: cptcovn++;
5258: cptcovprodnoage++;k1++;
5259: cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
5260: Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
5261: because this model-covariate is a construction we invent a new column
5262: ncovcol + k1
5263: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
5264: Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
5265: cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
5266: Tprod[k1]=k; /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 */
5267: Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
5268: Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
5269: k2=k2+2;
5270: Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
5271: Tvar[cptcovt+k2+1]=Tvard[k1][2]; /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
5272: for (i=1; i<=lastobs;i++){
5273: /* Computes the new covariate which is a product of
5274: covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
5275: covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
5276: }
5277: } /* End age is not in the model */
5278: } /* End if model includes a product */
5279: else { /* no more sum */
5280: /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
5281: /* scanf("%d",i);*/
5282: cutl(strd,strc,strb,'V');
5283: ks++; /**< Number of simple covariates */
5284: cptcovn++;
5285: Tvar[k]=atoi(strd);
5286: }
5287: strcpy(modelsav,stra); /* modelsav=V2+V1+V4 stra=V2+V1+V4 */
5288: /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
5289: scanf("%d",i);*/
5290: } /* end of loop + */
5291: } /* end model */
5292:
5293: /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
5294: If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
5295:
5296: /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
5297: printf("cptcovprod=%d ", cptcovprod);
5298: fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
5299:
5300: scanf("%d ",i);*/
5301:
5302:
5303: return (0); /* with covar[new additional covariate if product] and Tage if age */
5304: endread:
5305: printf("Exiting decodemodel: ");
5306: return (1);
5307: }
5308:
5309: calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
5310: {
5311: int i, m;
5312:
5313: for (i=1; i<=imx; i++) {
5314: for(m=2; (m<= maxwav); m++) {
5315: if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
5316: anint[m][i]=9999;
5317: s[m][i]=-1;
5318: }
5319: if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
5320: *nberr++;
5321: 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);
5322: 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);
5323: s[m][i]=-1;
5324: }
5325: if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
5326: *nberr++;
5327: 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]);
5328: 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]);
5329: s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
5330: }
5331: }
5332: }
5333:
5334: for (i=1; i<=imx; i++) {
5335: agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
5336: for(m=firstpass; (m<= lastpass); m++){
5337: if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
5338: if (s[m][i] >= nlstate+1) {
5339: if(agedc[i]>0)
5340: if((int)moisdc[i]!=99 && (int)andc[i]!=9999)
5341: agev[m][i]=agedc[i];
5342: /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
5343: else {
5344: if ((int)andc[i]!=9999){
5345: nbwarn++;
5346: printf("Warning negative age at death: %ld line:%d\n",num[i],i);
5347: fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
5348: agev[m][i]=-1;
5349: }
5350: }
5351: }
5352: else if(s[m][i] !=9){ /* Standard case, age in fractional
5353: years but with the precision of a month */
5354: agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
5355: if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
5356: agev[m][i]=1;
5357: else if(agev[m][i] < *agemin){
5358: *agemin=agev[m][i];
5359: printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
5360: }
5361: else if(agev[m][i] >*agemax){
5362: *agemax=agev[m][i];
5363: /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
5364: }
5365: /*agev[m][i]=anint[m][i]-annais[i];*/
5366: /* agev[m][i] = age[i]+2*m;*/
5367: }
5368: else { /* =9 */
5369: agev[m][i]=1;
5370: s[m][i]=-1;
5371: }
5372: }
5373: else /*= 0 Unknown */
5374: agev[m][i]=1;
5375: }
5376:
5377: }
5378: for (i=1; i<=imx; i++) {
5379: for(m=firstpass; (m<=lastpass); m++){
5380: if (s[m][i] > (nlstate+ndeath)) {
5381: *nberr++;
5382: 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);
5383: 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);
5384: return 1;
5385: }
5386: }
5387: }
5388:
5389: /*for (i=1; i<=imx; i++){
5390: for (m=firstpass; (m<lastpass); m++){
5391: printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
5392: }
5393:
5394: }*/
5395:
5396:
5397: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
5398: fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
5399:
5400: return (0);
5401: endread:
5402: printf("Exiting calandcheckages: ");
5403: return (1);
5404: }
5405:
5406:
5407: /***********************************************/
5408: /**************** Main Program *****************/
5409: /***********************************************/
5410:
5411: int main(int argc, char *argv[])
5412: {
5413: #ifdef GSL
5414: const gsl_multimin_fminimizer_type *T;
5415: size_t iteri = 0, it;
5416: int rval = GSL_CONTINUE;
5417: int status = GSL_SUCCESS;
5418: double ssval;
5419: #endif
5420: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
5421: int i,j, k, n=MAXN,iter,m,size=100,cptcode, cptcod;
5422: int linei, month, year,iout;
5423: int jj, ll, li, lj, lk, imk;
5424: int numlinepar=0; /* Current linenumber of parameter file */
5425: int itimes;
5426: int NDIM=2;
5427: int vpopbased=0;
5428:
5429: char ca[32], cb[32], cc[32];
5430: /* FILE *fichtm; *//* Html File */
5431: /* FILE *ficgp;*/ /*Gnuplot File */
5432: struct stat info;
5433: double agedeb, agefin,hf;
5434: double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
5435:
5436: double fret;
5437: double **xi,tmp,delta;
5438:
5439: double dum; /* Dummy variable */
5440: double ***p3mat;
5441: double ***mobaverage;
5442: int *indx;
5443: char line[MAXLINE], linepar[MAXLINE];
5444: char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
5445: char pathr[MAXLINE], pathimach[MAXLINE];
5446: char **bp, *tok, *val; /* pathtot */
5447: int firstobs=1, lastobs=10;
5448: int sdeb, sfin; /* Status at beginning and end */
5449: int c, h , cpt,l;
5450: int ju,jl, mi;
5451: int i1,j1, jk,aa,bb, stepsize, ij;
5452: int jnais,jdc,jint4,jint1,jint2,jint3,*tab;
5453: int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
5454: int mobilav=0,popforecast=0;
5455: int hstepm, nhstepm;
5456: int agemortsup;
5457: float sumlpop=0.;
5458: double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
5459: double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
5460:
5461: double bage, fage, age, agelim, agebase;
5462: double ftolpl=FTOL;
5463: double **prlim;
5464: double ***param; /* Matrix of parameters */
5465: double *p;
5466: double **matcov; /* Matrix of covariance */
5467: double ***delti3; /* Scale */
5468: double *delti; /* Scale */
5469: double ***eij, ***vareij;
5470: double **varpl; /* Variances of prevalence limits by age */
5471: double *epj, vepp;
5472: double kk1, kk2;
5473: double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
5474: double **ximort;
5475: char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
5476: int *dcwave;
5477:
5478: char z[1]="c", occ;
5479:
5480: /*char *strt;*/
5481: char strtend[80];
5482:
5483: long total_usecs;
5484:
5485: /* setlocale (LC_ALL, ""); */
5486: /* bindtextdomain (PACKAGE, LOCALEDIR); */
5487: /* textdomain (PACKAGE); */
5488: /* setlocale (LC_CTYPE, ""); */
5489: /* setlocale (LC_MESSAGES, ""); */
5490:
5491: /* gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
5492: rstart_time = time(NULL);
5493: /* (void) gettimeofday(&start_time,&tzp);*/
5494: start_time = *localtime(&rstart_time);
5495: curr_time=start_time;
5496: /*tml = *localtime(&start_time.tm_sec);*/
5497: /* strcpy(strstart,asctime(&tml)); */
5498: strcpy(strstart,asctime(&start_time));
5499:
5500: /* printf("Localtime (at start)=%s",strstart); */
5501: /* tp.tm_sec = tp.tm_sec +86400; */
5502: /* tm = *localtime(&start_time.tm_sec); */
5503: /* tmg.tm_year=tmg.tm_year +dsign*dyear; */
5504: /* tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
5505: /* tmg.tm_hour=tmg.tm_hour + 1; */
5506: /* tp.tm_sec = mktime(&tmg); */
5507: /* strt=asctime(&tmg); */
5508: /* printf("Time(after) =%s",strstart); */
5509: /* (void) time (&time_value);
5510: * printf("time=%d,t-=%d\n",time_value,time_value-86400);
5511: * tm = *localtime(&time_value);
5512: * strstart=asctime(&tm);
5513: * printf("tim_value=%d,asctime=%s\n",time_value,strstart);
5514: */
5515:
5516: nberr=0; /* Number of errors and warnings */
5517: nbwarn=0;
5518: getcwd(pathcd, size);
5519:
5520: printf("\n%s\n%s",version,fullversion);
5521: if(argc <=1){
5522: printf("\nEnter the parameter file name: ");
5523: fgets(pathr,FILENAMELENGTH,stdin);
5524: i=strlen(pathr);
5525: if(pathr[i-1]=='\n')
5526: pathr[i-1]='\0';
5527: i=strlen(pathr);
5528: if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
5529: pathr[i-1]='\0';
5530: for (tok = pathr; tok != NULL; ){
5531: printf("Pathr |%s|\n",pathr);
5532: while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
5533: printf("val= |%s| pathr=%s\n",val,pathr);
5534: strcpy (pathtot, val);
5535: if(pathr[0] == '\0') break; /* Dirty */
5536: }
5537: }
5538: else{
5539: strcpy(pathtot,argv[1]);
5540: }
5541: /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
5542: /*cygwin_split_path(pathtot,path,optionfile);
5543: printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
5544: /* cutv(path,optionfile,pathtot,'\\');*/
5545:
5546: /* Split argv[0], imach program to get pathimach */
5547: printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
5548: split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
5549: printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
5550: /* strcpy(pathimach,argv[0]); */
5551: /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
5552: split(pathtot,path,optionfile,optionfilext,optionfilefiname);
5553: printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
5554: chdir(path); /* Can be a relative path */
5555: if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
5556: printf("Current directory %s!\n",pathcd);
5557: strcpy(command,"mkdir ");
5558: strcat(command,optionfilefiname);
5559: if((outcmd=system(command)) != 0){
5560: printf("Problem creating directory or it already exists %s%s, err=%d\n",path,optionfilefiname,outcmd);
5561: /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
5562: /* fclose(ficlog); */
5563: /* exit(1); */
5564: }
5565: /* if((imk=mkdir(optionfilefiname))<0){ */
5566: /* perror("mkdir"); */
5567: /* } */
5568:
5569: /*-------- arguments in the command line --------*/
5570:
5571: /* Log file */
5572: strcat(filelog, optionfilefiname);
5573: strcat(filelog,".log"); /* */
5574: if((ficlog=fopen(filelog,"w"))==NULL) {
5575: printf("Problem with logfile %s\n",filelog);
5576: goto end;
5577: }
5578: fprintf(ficlog,"Log filename:%s\n",filelog);
5579: fprintf(ficlog,"\n%s\n%s",version,fullversion);
5580: fprintf(ficlog,"\nEnter the parameter file name: \n");
5581: fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
5582: path=%s \n\
5583: optionfile=%s\n\
5584: optionfilext=%s\n\
5585: optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
5586:
5587: printf("Local time (at start):%s",strstart);
5588: fprintf(ficlog,"Local time (at start): %s",strstart);
5589: fflush(ficlog);
5590: /* (void) gettimeofday(&curr_time,&tzp); */
5591: /* printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
5592:
5593: /* */
5594: strcpy(fileres,"r");
5595: strcat(fileres, optionfilefiname);
5596: strcat(fileres,".txt"); /* Other files have txt extension */
5597:
5598: /*---------arguments file --------*/
5599:
5600: if((ficpar=fopen(optionfile,"r"))==NULL) {
5601: printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
5602: fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
5603: fflush(ficlog);
5604: /* goto end; */
5605: exit(70);
5606: }
5607:
5608:
5609:
5610: strcpy(filereso,"o");
5611: strcat(filereso,fileres);
5612: if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
5613: printf("Problem with Output resultfile: %s\n", filereso);
5614: fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
5615: fflush(ficlog);
5616: goto end;
5617: }
5618:
5619: /* Reads comments: lines beginning with '#' */
5620: numlinepar=0;
5621: while((c=getc(ficpar))=='#' && c!= EOF){
5622: ungetc(c,ficpar);
5623: fgets(line, MAXLINE, ficpar);
5624: numlinepar++;
5625: fputs(line,stdout);
5626: fputs(line,ficparo);
5627: fputs(line,ficlog);
5628: }
5629: ungetc(c,ficpar);
5630:
5631: 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);
5632: numlinepar++;
5633: 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);
5634: 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);
5635: 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);
5636: fflush(ficlog);
5637: while((c=getc(ficpar))=='#' && c!= EOF){
5638: ungetc(c,ficpar);
5639: fgets(line, MAXLINE, ficpar);
5640: numlinepar++;
5641: fputs(line, stdout);
5642: //puts(line);
5643: fputs(line,ficparo);
5644: fputs(line,ficlog);
5645: }
5646: ungetc(c,ficpar);
5647:
5648:
5649: covar=matrix(0,NCOVMAX,1,n); /**< used in readdata */
5650: cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
5651: /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
5652: v1+v2*age+v2*v3 makes cptcovn = 3
5653: */
5654: if (strlen(model)>1)
5655: 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*/
5656: else
5657: ncovmodel=2;
5658: nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
5659: nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
5660: npar= nforce*ncovmodel; /* Number of parameters like aij*/
5661: if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
5662: 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);
5663: 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);
5664: fflush(stdout);
5665: fclose (ficlog);
5666: goto end;
5667: }
5668: delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5669: delti=delti3[1][1];
5670: /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
5671: if(mle==-1){ /* Print a wizard for help writing covariance matrix */
5672: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
5673: printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
5674: fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
5675: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
5676: fclose (ficparo);
5677: fclose (ficlog);
5678: goto end;
5679: exit(0);
5680: }
5681: else if(mle==-3) {
5682: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
5683: printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
5684: fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
5685: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5686: matcov=matrix(1,npar,1,npar);
5687: }
5688: else{
5689: /* Read guessed parameters */
5690: /* Reads comments: lines beginning with '#' */
5691: while((c=getc(ficpar))=='#' && c!= EOF){
5692: ungetc(c,ficpar);
5693: fgets(line, MAXLINE, ficpar);
5694: numlinepar++;
5695: fputs(line,stdout);
5696: fputs(line,ficparo);
5697: fputs(line,ficlog);
5698: }
5699: ungetc(c,ficpar);
5700:
5701: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5702: for(i=1; i <=nlstate; i++){
5703: j=0;
5704: for(jj=1; jj <=nlstate+ndeath; jj++){
5705: if(jj==i) continue;
5706: j++;
5707: fscanf(ficpar,"%1d%1d",&i1,&j1);
5708: if ((i1 != i) && (j1 != j)){
5709: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
5710: It might be a problem of design; if ncovcol and the model are correct\n \
5711: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
5712: exit(1);
5713: }
5714: fprintf(ficparo,"%1d%1d",i1,j1);
5715: if(mle==1)
5716: printf("%1d%1d",i,j);
5717: fprintf(ficlog,"%1d%1d",i,j);
5718: for(k=1; k<=ncovmodel;k++){
5719: fscanf(ficpar," %lf",¶m[i][j][k]);
5720: if(mle==1){
5721: printf(" %lf",param[i][j][k]);
5722: fprintf(ficlog," %lf",param[i][j][k]);
5723: }
5724: else
5725: fprintf(ficlog," %lf",param[i][j][k]);
5726: fprintf(ficparo," %lf",param[i][j][k]);
5727: }
5728: fscanf(ficpar,"\n");
5729: numlinepar++;
5730: if(mle==1)
5731: printf("\n");
5732: fprintf(ficlog,"\n");
5733: fprintf(ficparo,"\n");
5734: }
5735: }
5736: fflush(ficlog);
5737:
5738: /* Reads scales values */
5739: p=param[1][1];
5740:
5741: /* Reads comments: lines beginning with '#' */
5742: while((c=getc(ficpar))=='#' && c!= EOF){
5743: ungetc(c,ficpar);
5744: fgets(line, MAXLINE, ficpar);
5745: numlinepar++;
5746: fputs(line,stdout);
5747: fputs(line,ficparo);
5748: fputs(line,ficlog);
5749: }
5750: ungetc(c,ficpar);
5751:
5752: for(i=1; i <=nlstate; i++){
5753: for(j=1; j <=nlstate+ndeath-1; j++){
5754: fscanf(ficpar,"%1d%1d",&i1,&j1);
5755: if ((i1-i)*(j1-j)!=0){
5756: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
5757: exit(1);
5758: }
5759: printf("%1d%1d",i,j);
5760: fprintf(ficparo,"%1d%1d",i1,j1);
5761: fprintf(ficlog,"%1d%1d",i1,j1);
5762: for(k=1; k<=ncovmodel;k++){
5763: fscanf(ficpar,"%le",&delti3[i][j][k]);
5764: printf(" %le",delti3[i][j][k]);
5765: fprintf(ficparo," %le",delti3[i][j][k]);
5766: fprintf(ficlog," %le",delti3[i][j][k]);
5767: }
5768: fscanf(ficpar,"\n");
5769: numlinepar++;
5770: printf("\n");
5771: fprintf(ficparo,"\n");
5772: fprintf(ficlog,"\n");
5773: }
5774: }
5775: fflush(ficlog);
5776:
5777: /* Reads covariance matrix */
5778: delti=delti3[1][1];
5779:
5780:
5781: /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
5782:
5783: /* Reads comments: lines beginning with '#' */
5784: while((c=getc(ficpar))=='#' && c!= EOF){
5785: ungetc(c,ficpar);
5786: fgets(line, MAXLINE, ficpar);
5787: numlinepar++;
5788: fputs(line,stdout);
5789: fputs(line,ficparo);
5790: fputs(line,ficlog);
5791: }
5792: ungetc(c,ficpar);
5793:
5794: matcov=matrix(1,npar,1,npar);
5795: for(i=1; i <=npar; i++)
5796: for(j=1; j <=npar; j++) matcov[i][j]=0.;
5797:
5798: for(i=1; i <=npar; i++){
5799: fscanf(ficpar,"%s",str);
5800: if(mle==1)
5801: printf("%s",str);
5802: fprintf(ficlog,"%s",str);
5803: fprintf(ficparo,"%s",str);
5804: for(j=1; j <=i; j++){
5805: fscanf(ficpar," %le",&matcov[i][j]);
5806: if(mle==1){
5807: printf(" %.5le",matcov[i][j]);
5808: }
5809: fprintf(ficlog," %.5le",matcov[i][j]);
5810: fprintf(ficparo," %.5le",matcov[i][j]);
5811: }
5812: fscanf(ficpar,"\n");
5813: numlinepar++;
5814: if(mle==1)
5815: printf("\n");
5816: fprintf(ficlog,"\n");
5817: fprintf(ficparo,"\n");
5818: }
5819: for(i=1; i <=npar; i++)
5820: for(j=i+1;j<=npar;j++)
5821: matcov[i][j]=matcov[j][i];
5822:
5823: if(mle==1)
5824: printf("\n");
5825: fprintf(ficlog,"\n");
5826:
5827: fflush(ficlog);
5828:
5829: /*-------- Rewriting parameter file ----------*/
5830: strcpy(rfileres,"r"); /* "Rparameterfile */
5831: strcat(rfileres,optionfilefiname); /* Parameter file first name*/
5832: strcat(rfileres,"."); /* */
5833: strcat(rfileres,optionfilext); /* Other files have txt extension */
5834: if((ficres =fopen(rfileres,"w"))==NULL) {
5835: printf("Problem writing new parameter file: %s\n", fileres);goto end;
5836: fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
5837: }
5838: fprintf(ficres,"#%s\n",version);
5839: } /* End of mle != -3 */
5840:
5841:
5842: n= lastobs;
5843: num=lvector(1,n);
5844: moisnais=vector(1,n);
5845: annais=vector(1,n);
5846: moisdc=vector(1,n);
5847: andc=vector(1,n);
5848: agedc=vector(1,n);
5849: cod=ivector(1,n);
5850: weight=vector(1,n);
5851: for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
5852: mint=matrix(1,maxwav,1,n);
5853: anint=matrix(1,maxwav,1,n);
5854: s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */
5855: tab=ivector(1,NCOVMAX);
5856: ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
5857:
5858: /* Reads data from file datafile */
5859: if (readdata(datafile, firstobs, lastobs, &imx)==1)
5860: goto end;
5861:
5862: /* Calculation of the number of parameters from char model */
5863: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4
5864: k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
5865: k=3 V4 Tvar[k=3]= 4 (from V4)
5866: k=2 V1 Tvar[k=2]= 1 (from V1)
5867: k=1 Tvar[1]=2 (from V2)
5868: */
5869: Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
5870: /* V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs).
5871: For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4,
5872: Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
5873: */
5874: /* For model-covariate k tells which data-covariate to use but
5875: because this model-covariate is a construction we invent a new column
5876: ncovcol + k1
5877: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
5878: Tvar[3=V1*V4]=4+1 etc */
5879: Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
5880: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
5881: if V2+V1+V1*V4+age*V3+V3*V2 TProd[k1=2]=5 (V3*V2)
5882: */
5883: Tvaraff=ivector(1,NCOVMAX); /* Unclear */
5884: 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
5885: * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd.
5886: * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
5887: Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
5888: 4 covariates (3 plus signs)
5889: Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
5890: */
5891:
5892: if(decodemodel(model, lastobs) == 1)
5893: goto end;
5894:
5895: if((double)(lastobs-imx)/(double)imx > 1.10){
5896: nbwarn++;
5897: 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);
5898: 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);
5899: }
5900: /* if(mle==1){*/
5901: if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
5902: for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
5903: }
5904:
5905: /*-calculation of age at interview from date of interview and age at death -*/
5906: agev=matrix(1,maxwav,1,imx);
5907:
5908: if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
5909: goto end;
5910:
5911:
5912: agegomp=(int)agemin;
5913: free_vector(moisnais,1,n);
5914: free_vector(annais,1,n);
5915: /* free_matrix(mint,1,maxwav,1,n);
5916: free_matrix(anint,1,maxwav,1,n);*/
5917: free_vector(moisdc,1,n);
5918: free_vector(andc,1,n);
5919: /* */
5920:
5921: wav=ivector(1,imx);
5922: dh=imatrix(1,lastpass-firstpass+1,1,imx);
5923: bh=imatrix(1,lastpass-firstpass+1,1,imx);
5924: mw=imatrix(1,lastpass-firstpass+1,1,imx);
5925:
5926: /* Concatenates waves */
5927: concatwav(wav, dh, bh, mw, s, agedc, agev, firstpass, lastpass, imx, nlstate, stepm);
5928: /* */
5929:
5930: /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
5931:
5932: nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
5933: ncodemax[1]=1;
5934: Ndum =ivector(-1,NCOVMAX);
5935: if (ncovmodel > 2)
5936: tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
5937:
5938: codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
5939: /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
5940: h=0;
5941:
5942:
5943: /*if (cptcovn > 0) */
5944:
5945:
5946: m=pow(2,cptcoveff);
5947:
5948: for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
5949: 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 */
5950: for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
5951: for(cpt=1; cpt <=pow(2,k-1); cpt++){ /* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 */
5952: h++;
5953: if (h>m)
5954: h=1;
5955: /**< codtab(h,k) k = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
5956: * h 1 2 3 4
5957: *______________________________
5958: * 1 i=1 1 i=1 1 i=1 1 i=1 1
5959: * 2 2 1 1 1
5960: * 3 i=2 1 2 1 1
5961: * 4 2 2 1 1
5962: * 5 i=3 1 i=2 1 2 1
5963: * 6 2 1 2 1
5964: * 7 i=4 1 2 2 1
5965: * 8 2 2 2 1
5966: * 9 i=5 1 i=3 1 i=2 1 1
5967: * 10 2 1 1 1
5968: * 11 i=6 1 2 1 1
5969: * 12 2 2 1 1
5970: * 13 i=7 1 i=4 1 2 1
5971: * 14 2 1 2 1
5972: * 15 i=8 1 2 2 1
5973: * 16 2 2 2 1
5974: */
5975: codtab[h][k]=j;
5976: /*codtab[h][Tvar[k]]=j;*/
5977: 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]]);
5978: }
5979: }
5980: }
5981: }
5982: /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
5983: codtab[1][2]=1;codtab[2][2]=2; */
5984: /* for(i=1; i <=m ;i++){
5985: for(k=1; k <=cptcovn; k++){
5986: printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
5987: }
5988: printf("\n");
5989: }
5990: scanf("%d",i);*/
5991:
5992: free_ivector(Ndum,-1,NCOVMAX);
5993:
5994:
5995:
5996: /*------------ gnuplot -------------*/
5997: strcpy(optionfilegnuplot,optionfilefiname);
5998: if(mle==-3)
5999: strcat(optionfilegnuplot,"-mort");
6000: strcat(optionfilegnuplot,".gp");
6001:
6002: if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
6003: printf("Problem with file %s",optionfilegnuplot);
6004: }
6005: else{
6006: fprintf(ficgp,"\n# %s\n", version);
6007: fprintf(ficgp,"# %s\n", optionfilegnuplot);
6008: //fprintf(ficgp,"set missing 'NaNq'\n");
6009: fprintf(ficgp,"set datafile missing 'NaNq'\n");
6010: }
6011: /* fclose(ficgp);*/
6012: /*--------- index.htm --------*/
6013:
6014: strcpy(optionfilehtm,optionfilefiname); /* Main html file */
6015: if(mle==-3)
6016: strcat(optionfilehtm,"-mort");
6017: strcat(optionfilehtm,".htm");
6018: if((fichtm=fopen(optionfilehtm,"w"))==NULL) {
6019: printf("Problem with %s \n",optionfilehtm);
6020: exit(0);
6021: }
6022:
6023: strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
6024: strcat(optionfilehtmcov,"-cov.htm");
6025: if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL) {
6026: printf("Problem with %s \n",optionfilehtmcov), exit(0);
6027: }
6028: else{
6029: fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6030: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6031: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
6032: optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
6033: }
6034:
6035: fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6036: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6037: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
6038: \n\
6039: <hr size=\"2\" color=\"#EC5E5E\">\
6040: <ul><li><h4>Parameter files</h4>\n\
6041: - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
6042: - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
6043: - Log file of the run: <a href=\"%s\">%s</a><br>\n\
6044: - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
6045: - Date and time at start: %s</ul>\n",\
6046: optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
6047: optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
6048: fileres,fileres,\
6049: filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
6050: fflush(fichtm);
6051:
6052: strcpy(pathr,path);
6053: strcat(pathr,optionfilefiname);
6054: chdir(optionfilefiname); /* Move to directory named optionfile */
6055:
6056: /* Calculates basic frequencies. Computes observed prevalence at single age
6057: and prints on file fileres'p'. */
6058: freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
6059:
6060: fprintf(fichtm,"\n");
6061: fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
6062: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
6063: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
6064: imx,agemin,agemax,jmin,jmax,jmean);
6065: pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6066: oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6067: newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6068: savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6069: oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
6070:
6071:
6072: /* For Powell, parameters are in a vector p[] starting at p[1]
6073: so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
6074: p=param[1][1]; /* *(*(*(param +1)+1)+0) */
6075:
6076: globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
6077:
6078: if (mle==-3){
6079: ximort=matrix(1,NDIM,1,NDIM);
6080: /* ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
6081: cens=ivector(1,n);
6082: ageexmed=vector(1,n);
6083: agecens=vector(1,n);
6084: dcwave=ivector(1,n);
6085:
6086: for (i=1; i<=imx; i++){
6087: dcwave[i]=-1;
6088: for (m=firstpass; m<=lastpass; m++)
6089: if (s[m][i]>nlstate) {
6090: dcwave[i]=m;
6091: /* printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
6092: break;
6093: }
6094: }
6095:
6096: for (i=1; i<=imx; i++) {
6097: if (wav[i]>0){
6098: ageexmed[i]=agev[mw[1][i]][i];
6099: j=wav[i];
6100: agecens[i]=1.;
6101:
6102: if (ageexmed[i]> 1 && wav[i] > 0){
6103: agecens[i]=agev[mw[j][i]][i];
6104: cens[i]= 1;
6105: }else if (ageexmed[i]< 1)
6106: cens[i]= -1;
6107: if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
6108: cens[i]=0 ;
6109: }
6110: else cens[i]=-1;
6111: }
6112:
6113: for (i=1;i<=NDIM;i++) {
6114: for (j=1;j<=NDIM;j++)
6115: ximort[i][j]=(i == j ? 1.0 : 0.0);
6116: }
6117:
6118: /*p[1]=0.0268; p[NDIM]=0.083;*/
6119: /*printf("%lf %lf", p[1], p[2]);*/
6120:
6121:
6122: #ifdef GSL
6123: printf("GSL optimization\n"); fprintf(ficlog,"Powell\n");
6124: #else
6125: printf("Powell\n"); fprintf(ficlog,"Powell\n");
6126: #endif
6127: strcpy(filerespow,"pow-mort");
6128: strcat(filerespow,fileres);
6129: if((ficrespow=fopen(filerespow,"w"))==NULL) {
6130: printf("Problem with resultfile: %s\n", filerespow);
6131: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
6132: }
6133: #ifdef GSL
6134: fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
6135: #else
6136: fprintf(ficrespow,"# Powell\n# iter -2*LL");
6137: #endif
6138: /* for (i=1;i<=nlstate;i++)
6139: for(j=1;j<=nlstate+ndeath;j++)
6140: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
6141: */
6142: fprintf(ficrespow,"\n");
6143: #ifdef GSL
6144: /* gsl starts here */
6145: T = gsl_multimin_fminimizer_nmsimplex;
6146: gsl_multimin_fminimizer *sfm = NULL;
6147: gsl_vector *ss, *x;
6148: gsl_multimin_function minex_func;
6149:
6150: /* Initial vertex size vector */
6151: ss = gsl_vector_alloc (NDIM);
6152:
6153: if (ss == NULL){
6154: GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
6155: }
6156: /* Set all step sizes to 1 */
6157: gsl_vector_set_all (ss, 0.001);
6158:
6159: /* Starting point */
6160:
6161: x = gsl_vector_alloc (NDIM);
6162:
6163: if (x == NULL){
6164: gsl_vector_free(ss);
6165: GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
6166: }
6167:
6168: /* Initialize method and iterate */
6169: /* p[1]=0.0268; p[NDIM]=0.083; */
6170: /* gsl_vector_set(x, 0, 0.0268); */
6171: /* gsl_vector_set(x, 1, 0.083); */
6172: gsl_vector_set(x, 0, p[1]);
6173: gsl_vector_set(x, 1, p[2]);
6174:
6175: minex_func.f = &gompertz_f;
6176: minex_func.n = NDIM;
6177: minex_func.params = (void *)&p; /* ??? */
6178:
6179: sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
6180: gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
6181:
6182: printf("Iterations beginning .....\n\n");
6183: printf("Iter. # Intercept Slope -Log Likelihood Simplex size\n");
6184:
6185: iteri=0;
6186: while (rval == GSL_CONTINUE){
6187: iteri++;
6188: status = gsl_multimin_fminimizer_iterate(sfm);
6189:
6190: if (status) printf("error: %s\n", gsl_strerror (status));
6191: fflush(0);
6192:
6193: if (status)
6194: break;
6195:
6196: rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
6197: ssval = gsl_multimin_fminimizer_size (sfm);
6198:
6199: if (rval == GSL_SUCCESS)
6200: printf ("converged to a local maximum at\n");
6201:
6202: printf("%5d ", iteri);
6203: for (it = 0; it < NDIM; it++){
6204: printf ("%10.5f ", gsl_vector_get (sfm->x, it));
6205: }
6206: printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
6207: }
6208:
6209: printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
6210:
6211: gsl_vector_free(x); /* initial values */
6212: gsl_vector_free(ss); /* inital step size */
6213: for (it=0; it<NDIM; it++){
6214: p[it+1]=gsl_vector_get(sfm->x,it);
6215: fprintf(ficrespow," %.12lf", p[it]);
6216: }
6217: gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1) */
6218: #endif
6219: #ifdef POWELL
6220: powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
6221: #endif
6222: fclose(ficrespow);
6223:
6224: hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);
6225:
6226: for(i=1; i <=NDIM; i++)
6227: for(j=i+1;j<=NDIM;j++)
6228: matcov[i][j]=matcov[j][i];
6229:
6230: printf("\nCovariance matrix\n ");
6231: for(i=1; i <=NDIM; i++) {
6232: for(j=1;j<=NDIM;j++){
6233: printf("%f ",matcov[i][j]);
6234: }
6235: printf("\n ");
6236: }
6237:
6238: printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
6239: for (i=1;i<=NDIM;i++)
6240: printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
6241:
6242: lsurv=vector(1,AGESUP);
6243: lpop=vector(1,AGESUP);
6244: tpop=vector(1,AGESUP);
6245: lsurv[agegomp]=100000;
6246:
6247: for (k=agegomp;k<=AGESUP;k++) {
6248: agemortsup=k;
6249: if (p[1]*exp(p[2]*(k-agegomp))>1) break;
6250: }
6251:
6252: for (k=agegomp;k<agemortsup;k++)
6253: lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
6254:
6255: for (k=agegomp;k<agemortsup;k++){
6256: lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
6257: sumlpop=sumlpop+lpop[k];
6258: }
6259:
6260: tpop[agegomp]=sumlpop;
6261: for (k=agegomp;k<(agemortsup-3);k++){
6262: /* tpop[k+1]=2;*/
6263: tpop[k+1]=tpop[k]-lpop[k];
6264: }
6265:
6266:
6267: printf("\nAge lx qx dx Lx Tx e(x)\n");
6268: for (k=agegomp;k<(agemortsup-2);k++)
6269: 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]);
6270:
6271:
6272: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6273: printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6274:
6275: printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
6276: stepm, weightopt,\
6277: model,imx,p,matcov,agemortsup);
6278:
6279: free_vector(lsurv,1,AGESUP);
6280: free_vector(lpop,1,AGESUP);
6281: free_vector(tpop,1,AGESUP);
6282: #ifdef GSL
6283: free_ivector(cens,1,n);
6284: free_vector(agecens,1,n);
6285: free_ivector(dcwave,1,n);
6286: free_matrix(ximort,1,NDIM,1,NDIM);
6287: #endif
6288: } /* Endof if mle==-3 */
6289:
6290: else{ /* For mle >=1 */
6291: globpr=0;/* debug */
6292: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
6293: printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6294: for (k=1; k<=npar;k++)
6295: printf(" %d %8.5f",k,p[k]);
6296: printf("\n");
6297: globpr=1; /* to print the contributions */
6298: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
6299: printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6300: for (k=1; k<=npar;k++)
6301: printf(" %d %8.5f",k,p[k]);
6302: printf("\n");
6303: if(mle>=1){ /* Could be 1 or 2 */
6304: mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
6305: }
6306:
6307: /*--------- results files --------------*/
6308: 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);
6309:
6310:
6311: fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6312: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6313: fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6314: for(i=1,jk=1; i <=nlstate; i++){
6315: for(k=1; k <=(nlstate+ndeath); k++){
6316: if (k != i) {
6317: printf("%d%d ",i,k);
6318: fprintf(ficlog,"%d%d ",i,k);
6319: fprintf(ficres,"%1d%1d ",i,k);
6320: for(j=1; j <=ncovmodel; j++){
6321: printf("%lf ",p[jk]);
6322: fprintf(ficlog,"%lf ",p[jk]);
6323: fprintf(ficres,"%lf ",p[jk]);
6324: jk++;
6325: }
6326: printf("\n");
6327: fprintf(ficlog,"\n");
6328: fprintf(ficres,"\n");
6329: }
6330: }
6331: }
6332: if(mle!=0){
6333: /* Computing hessian and covariance matrix */
6334: ftolhess=ftol; /* Usually correct */
6335: hesscov(matcov, p, npar, delti, ftolhess, func);
6336: }
6337: fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
6338: printf("# Scales (for hessian or gradient estimation)\n");
6339: fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
6340: for(i=1,jk=1; i <=nlstate; i++){
6341: for(j=1; j <=nlstate+ndeath; j++){
6342: if (j!=i) {
6343: fprintf(ficres,"%1d%1d",i,j);
6344: printf("%1d%1d",i,j);
6345: fprintf(ficlog,"%1d%1d",i,j);
6346: for(k=1; k<=ncovmodel;k++){
6347: printf(" %.5e",delti[jk]);
6348: fprintf(ficlog," %.5e",delti[jk]);
6349: fprintf(ficres," %.5e",delti[jk]);
6350: jk++;
6351: }
6352: printf("\n");
6353: fprintf(ficlog,"\n");
6354: fprintf(ficres,"\n");
6355: }
6356: }
6357: }
6358:
6359: 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");
6360: if(mle>=1)
6361: 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");
6362: 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");
6363: /* # 121 Var(a12)\n\ */
6364: /* # 122 Cov(b12,a12) Var(b12)\n\ */
6365: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
6366: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
6367: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
6368: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
6369: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
6370: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
6371:
6372:
6373: /* Just to have a covariance matrix which will be more understandable
6374: even is we still don't want to manage dictionary of variables
6375: */
6376: for(itimes=1;itimes<=2;itimes++){
6377: jj=0;
6378: for(i=1; i <=nlstate; i++){
6379: for(j=1; j <=nlstate+ndeath; j++){
6380: if(j==i) continue;
6381: for(k=1; k<=ncovmodel;k++){
6382: jj++;
6383: ca[0]= k+'a'-1;ca[1]='\0';
6384: if(itimes==1){
6385: if(mle>=1)
6386: printf("#%1d%1d%d",i,j,k);
6387: fprintf(ficlog,"#%1d%1d%d",i,j,k);
6388: fprintf(ficres,"#%1d%1d%d",i,j,k);
6389: }else{
6390: if(mle>=1)
6391: printf("%1d%1d%d",i,j,k);
6392: fprintf(ficlog,"%1d%1d%d",i,j,k);
6393: fprintf(ficres,"%1d%1d%d",i,j,k);
6394: }
6395: ll=0;
6396: for(li=1;li <=nlstate; li++){
6397: for(lj=1;lj <=nlstate+ndeath; lj++){
6398: if(lj==li) continue;
6399: for(lk=1;lk<=ncovmodel;lk++){
6400: ll++;
6401: if(ll<=jj){
6402: cb[0]= lk +'a'-1;cb[1]='\0';
6403: if(ll<jj){
6404: if(itimes==1){
6405: if(mle>=1)
6406: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6407: fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6408: fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6409: }else{
6410: if(mle>=1)
6411: printf(" %.5e",matcov[jj][ll]);
6412: fprintf(ficlog," %.5e",matcov[jj][ll]);
6413: fprintf(ficres," %.5e",matcov[jj][ll]);
6414: }
6415: }else{
6416: if(itimes==1){
6417: if(mle>=1)
6418: printf(" Var(%s%1d%1d)",ca,i,j);
6419: fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
6420: fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
6421: }else{
6422: if(mle>=1)
6423: printf(" %.5e",matcov[jj][ll]);
6424: fprintf(ficlog," %.5e",matcov[jj][ll]);
6425: fprintf(ficres," %.5e",matcov[jj][ll]);
6426: }
6427: }
6428: }
6429: } /* end lk */
6430: } /* end lj */
6431: } /* end li */
6432: if(mle>=1)
6433: printf("\n");
6434: fprintf(ficlog,"\n");
6435: fprintf(ficres,"\n");
6436: numlinepar++;
6437: } /* end k*/
6438: } /*end j */
6439: } /* end i */
6440: } /* end itimes */
6441:
6442: fflush(ficlog);
6443: fflush(ficres);
6444:
6445: while((c=getc(ficpar))=='#' && c!= EOF){
6446: ungetc(c,ficpar);
6447: fgets(line, MAXLINE, ficpar);
6448: fputs(line,stdout);
6449: fputs(line,ficparo);
6450: }
6451: ungetc(c,ficpar);
6452:
6453: estepm=0;
6454: fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
6455: if (estepm==0 || estepm < stepm) estepm=stepm;
6456: if (fage <= 2) {
6457: bage = ageminpar;
6458: fage = agemaxpar;
6459: }
6460:
6461: fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
6462: fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6463: fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6464:
6465: while((c=getc(ficpar))=='#' && c!= EOF){
6466: ungetc(c,ficpar);
6467: fgets(line, MAXLINE, ficpar);
6468: fputs(line,stdout);
6469: fputs(line,ficparo);
6470: }
6471: ungetc(c,ficpar);
6472:
6473: 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);
6474: 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);
6475: 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);
6476: printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
6477: 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);
6478:
6479: while((c=getc(ficpar))=='#' && c!= EOF){
6480: ungetc(c,ficpar);
6481: fgets(line, MAXLINE, ficpar);
6482: fputs(line,stdout);
6483: fputs(line,ficparo);
6484: }
6485: ungetc(c,ficpar);
6486:
6487:
6488: dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
6489: dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
6490:
6491: fscanf(ficpar,"pop_based=%d\n",&popbased);
6492: fprintf(ficparo,"pop_based=%d\n",popbased);
6493: fprintf(ficres,"pop_based=%d\n",popbased);
6494:
6495: while((c=getc(ficpar))=='#' && c!= EOF){
6496: ungetc(c,ficpar);
6497: fgets(line, MAXLINE, ficpar);
6498: fputs(line,stdout);
6499: fputs(line,ficparo);
6500: }
6501: ungetc(c,ficpar);
6502:
6503: 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);
6504: 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);
6505: 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);
6506: 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);
6507: 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);
6508: /* day and month of proj2 are not used but only year anproj2.*/
6509:
6510:
6511:
6512: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
6513: /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
6514:
6515: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6516: printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6517:
6518: printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
6519: model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
6520: jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
6521:
6522: /*------------ free_vector -------------*/
6523: /* chdir(path); */
6524:
6525: free_ivector(wav,1,imx);
6526: free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
6527: free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
6528: free_imatrix(mw,1,lastpass-firstpass+1,1,imx);
6529: free_lvector(num,1,n);
6530: free_vector(agedc,1,n);
6531: /*free_matrix(covar,0,NCOVMAX,1,n);*/
6532: /*free_matrix(covar,1,NCOVMAX,1,n);*/
6533: fclose(ficparo);
6534: fclose(ficres);
6535:
6536:
6537: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
6538: #include "prevlim.h" /* Use ficrespl, ficlog */
6539: fclose(ficrespl);
6540:
6541: #ifdef FREEEXIT2
6542: #include "freeexit2.h"
6543: #endif
6544:
6545: /*------------- h Pij x at various ages ------------*/
6546: #include "hpijx.h"
6547: fclose(ficrespij);
6548:
6549: /*-------------- Variance of one-step probabilities---*/
6550: k=1;
6551: varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
6552:
6553:
6554: probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
6555: for(i=1;i<=AGESUP;i++)
6556: for(j=1;j<=NCOVMAX;j++)
6557: for(k=1;k<=NCOVMAX;k++)
6558: probs[i][j][k]=0.;
6559:
6560: /*---------- Forecasting ------------------*/
6561: /*if((stepm == 1) && (strcmp(model,".")==0)){*/
6562: if(prevfcast==1){
6563: /* if(stepm ==1){*/
6564: prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
6565: /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
6566: /* } */
6567: /* else{ */
6568: /* erreur=108; */
6569: /* 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); */
6570: /* 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); */
6571: /* } */
6572: }
6573:
6574:
6575: /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
6576:
6577: prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
6578: /* 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",\
6579: ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
6580: */
6581:
6582: if (mobilav!=0) {
6583: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
6584: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
6585: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
6586: printf(" Error in movingaverage mobilav=%d\n",mobilav);
6587: }
6588: }
6589:
6590:
6591: /*---------- Health expectancies, no variances ------------*/
6592:
6593: strcpy(filerese,"e");
6594: strcat(filerese,fileres);
6595: if((ficreseij=fopen(filerese,"w"))==NULL) {
6596: printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
6597: fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
6598: }
6599: printf("Computing Health Expectancies: result on file '%s' \n", filerese);
6600: fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
6601: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6602: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6603:
6604: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6605: fprintf(ficreseij,"\n#****** ");
6606: for(j=1;j<=cptcoveff;j++) {
6607: fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6608: }
6609: fprintf(ficreseij,"******\n");
6610:
6611: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6612: oldm=oldms;savm=savms;
6613: evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);
6614:
6615: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
6616: /*}*/
6617: }
6618: fclose(ficreseij);
6619:
6620:
6621: /*---------- Health expectancies and variances ------------*/
6622:
6623:
6624: strcpy(filerest,"t");
6625: strcat(filerest,fileres);
6626: if((ficrest=fopen(filerest,"w"))==NULL) {
6627: printf("Problem with total LE resultfile: %s\n", filerest);goto end;
6628: fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
6629: }
6630: printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
6631: fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
6632:
6633:
6634: strcpy(fileresstde,"stde");
6635: strcat(fileresstde,fileres);
6636: if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
6637: printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
6638: fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
6639: }
6640: printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
6641: fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
6642:
6643: strcpy(filerescve,"cve");
6644: strcat(filerescve,fileres);
6645: if((ficrescveij=fopen(filerescve,"w"))==NULL) {
6646: printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
6647: fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
6648: }
6649: printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
6650: fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
6651:
6652: strcpy(fileresv,"v");
6653: strcat(fileresv,fileres);
6654: if((ficresvij=fopen(fileresv,"w"))==NULL) {
6655: printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
6656: fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
6657: }
6658: printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
6659: fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
6660:
6661: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6662: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6663:
6664: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6665: fprintf(ficrest,"\n#****** ");
6666: for(j=1;j<=cptcoveff;j++)
6667: fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6668: fprintf(ficrest,"******\n");
6669:
6670: fprintf(ficresstdeij,"\n#****** ");
6671: fprintf(ficrescveij,"\n#****** ");
6672: for(j=1;j<=cptcoveff;j++) {
6673: fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6674: fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6675: }
6676: fprintf(ficresstdeij,"******\n");
6677: fprintf(ficrescveij,"******\n");
6678:
6679: fprintf(ficresvij,"\n#****** ");
6680: for(j=1;j<=cptcoveff;j++)
6681: fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6682: fprintf(ficresvij,"******\n");
6683:
6684: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6685: oldm=oldms;savm=savms;
6686: cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
6687: /*
6688: */
6689: /* goto endfree; */
6690:
6691: vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6692: pstamp(ficrest);
6693:
6694:
6695: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
6696: oldm=oldms;savm=savms; /* Segmentation fault */
6697: cptcod= 0; /* To be deleted */
6698: 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 */
6699: 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 ");
6700: if(vpopbased==1)
6701: 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);
6702: else
6703: fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
6704: fprintf(ficrest,"# Age e.. (std) ");
6705: for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
6706: fprintf(ficrest,"\n");
6707:
6708: epj=vector(1,nlstate+1);
6709: for(age=bage; age <=fage ;age++){
6710: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
6711: if (vpopbased==1) {
6712: if(mobilav ==0){
6713: for(i=1; i<=nlstate;i++)
6714: prlim[i][i]=probs[(int)age][i][k];
6715: }else{ /* mobilav */
6716: for(i=1; i<=nlstate;i++)
6717: prlim[i][i]=mobaverage[(int)age][i][k];
6718: }
6719: }
6720:
6721: fprintf(ficrest," %4.0f",age);
6722: for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
6723: for(i=1, epj[j]=0.;i <=nlstate;i++) {
6724: epj[j] += prlim[i][i]*eij[i][j][(int)age];
6725: /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
6726: }
6727: epj[nlstate+1] +=epj[j];
6728: }
6729:
6730: for(i=1, vepp=0.;i <=nlstate;i++)
6731: for(j=1;j <=nlstate;j++)
6732: vepp += vareij[i][j][(int)age];
6733: fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
6734: for(j=1;j <=nlstate;j++){
6735: fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
6736: }
6737: fprintf(ficrest,"\n");
6738: }
6739: }
6740: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
6741: free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
6742: free_vector(epj,1,nlstate+1);
6743: /*}*/
6744: }
6745: free_vector(weight,1,n);
6746: free_imatrix(Tvard,1,NCOVMAX,1,2);
6747: free_imatrix(s,1,maxwav+1,1,n);
6748: free_matrix(anint,1,maxwav,1,n);
6749: free_matrix(mint,1,maxwav,1,n);
6750: free_ivector(cod,1,n);
6751: free_ivector(tab,1,NCOVMAX);
6752: fclose(ficresstdeij);
6753: fclose(ficrescveij);
6754: fclose(ficresvij);
6755: fclose(ficrest);
6756: fclose(ficpar);
6757:
6758: /*------- Variance of period (stable) prevalence------*/
6759:
6760: strcpy(fileresvpl,"vpl");
6761: strcat(fileresvpl,fileres);
6762: if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
6763: printf("Problem with variance of period (stable) prevalence resultfile: %s\n", fileresvpl);
6764: exit(0);
6765: }
6766: printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
6767:
6768: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6769: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6770:
6771: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6772: fprintf(ficresvpl,"\n#****** ");
6773: for(j=1;j<=cptcoveff;j++)
6774: fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6775: fprintf(ficresvpl,"******\n");
6776:
6777: varpl=matrix(1,nlstate,(int) bage, (int) fage);
6778: oldm=oldms;savm=savms;
6779: varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
6780: free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
6781: /*}*/
6782: }
6783:
6784: fclose(ficresvpl);
6785:
6786: /*---------- End : free ----------------*/
6787: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
6788: free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
6789: } /* mle==-3 arrives here for freeing */
6790: endfree:
6791: free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
6792: free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
6793: free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
6794: free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
6795: free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
6796: free_matrix(covar,0,NCOVMAX,1,n);
6797: free_matrix(matcov,1,npar,1,npar);
6798: /*free_vector(delti,1,npar);*/
6799: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
6800: free_matrix(agev,1,maxwav,1,imx);
6801: free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
6802:
6803: free_ivector(ncodemax,1,NCOVMAX);
6804: free_ivector(Tvar,1,NCOVMAX);
6805: free_ivector(Tprod,1,NCOVMAX);
6806: free_ivector(Tvaraff,1,NCOVMAX);
6807: free_ivector(Tage,1,NCOVMAX);
6808:
6809: free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
6810: free_imatrix(codtab,1,100,1,10);
6811: fflush(fichtm);
6812: fflush(ficgp);
6813:
6814:
6815: if((nberr >0) || (nbwarn>0)){
6816: printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
6817: fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
6818: }else{
6819: printf("End of Imach\n");
6820: fprintf(ficlog,"End of Imach\n");
6821: }
6822: printf("See log file on %s\n",filelog);
6823: /* gettimeofday(&end_time, (struct timezone*)0);*/ /* after time */
6824: /*(void) gettimeofday(&end_time,&tzp);*/
6825: rend_time = time(NULL);
6826: end_time = *localtime(&rend_time);
6827: /* tml = *localtime(&end_time.tm_sec); */
6828: strcpy(strtend,asctime(&end_time));
6829: printf("Local time at start %s\nLocal time at end %s",strstart, strtend);
6830: fprintf(ficlog,"Local time at start %s\nLocal time at end %s\n",strstart, strtend);
6831: printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
6832:
6833: printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
6834: fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
6835: fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
6836: /* printf("Total time was %d uSec.\n", total_usecs);*/
6837: /* if(fileappend(fichtm,optionfilehtm)){ */
6838: fprintf(fichtm,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
6839: fclose(fichtm);
6840: fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
6841: fclose(fichtmcov);
6842: fclose(ficgp);
6843: fclose(ficlog);
6844: /*------ End -----------*/
6845:
6846:
6847: printf("Before Current directory %s!\n",pathcd);
6848: if(chdir(pathcd) != 0)
6849: printf("Can't move to directory %s!\n",path);
6850: if(getcwd(pathcd,MAXLINE) > 0)
6851: printf("Current directory %s!\n",pathcd);
6852: /*strcat(plotcmd,CHARSEPARATOR);*/
6853: sprintf(plotcmd,"gnuplot");
6854: #ifdef _WIN32
6855: sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
6856: #endif
6857: if(!stat(plotcmd,&info)){
6858: printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
6859: if(!stat(getenv("GNUPLOTBIN"),&info)){
6860: printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
6861: }else
6862: strcpy(pplotcmd,plotcmd);
6863: #ifdef __unix
6864: strcpy(plotcmd,GNUPLOTPROGRAM);
6865: if(!stat(plotcmd,&info)){
6866: printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
6867: }else
6868: strcpy(pplotcmd,plotcmd);
6869: #endif
6870: }else
6871: strcpy(pplotcmd,plotcmd);
6872:
6873: sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
6874: printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
6875:
6876: if((outcmd=system(plotcmd)) != 0){
6877: printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
6878: printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
6879: sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
6880: if((outcmd=system(plotcmd)) != 0)
6881: printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
6882: }
6883: printf(" Successful, please wait...");
6884: while (z[0] != 'q') {
6885: /* chdir(path); */
6886: printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
6887: scanf("%s",z);
6888: /* if (z[0] == 'c') system("./imach"); */
6889: if (z[0] == 'e') {
6890: #ifdef __APPLE__
6891: sprintf(pplotcmd, "open %s", optionfilehtm);
6892: #elif __linux
6893: sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
6894: #else
6895: sprintf(pplotcmd, "%s", optionfilehtm);
6896: #endif
6897: printf("Starting browser with: %s",pplotcmd);fflush(stdout);
6898: system(pplotcmd);
6899: }
6900: else if (z[0] == 'g') system(plotcmd);
6901: else if (z[0] == 'q') exit(0);
6902: }
6903: end:
6904: while (z[0] != 'q') {
6905: printf("\nType q for exiting: ");
6906: scanf("%s",z);
6907: }
6908: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>