1: /* $Id: imach.c,v 1.166 2014/12/22 11:40:47 brouard Exp $
2: $State: Exp $
3: $Log: imach.c,v $
4: Revision 1.166 2014/12/22 11:40:47 brouard
5: *** empty log message ***
6:
7: Revision 1.165 2014/12/16 11:20:36 brouard
8: Summary: After compiling on Visual C
9:
10: * imach.c (Module): Merging 1.61 to 1.162
11:
12: Revision 1.164 2014/12/16 10:52:11 brouard
13: Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
14:
15: * imach.c (Module): Merging 1.61 to 1.162
16:
17: Revision 1.163 2014/12/16 10:30:11 brouard
18: * imach.c (Module): Merging 1.61 to 1.162
19:
20: Revision 1.162 2014/09/25 11:43:39 brouard
21: Summary: temporary backup 0.99!
22:
23: Revision 1.1 2014/09/16 11:06:58 brouard
24: Summary: With some code (wrong) for nlopt
25:
26: Author:
27:
28: Revision 1.161 2014/09/15 20:41:41 brouard
29: Summary: Problem with macro SQR on Intel compiler
30:
31: Revision 1.160 2014/09/02 09:24:05 brouard
32: *** empty log message ***
33:
34: Revision 1.159 2014/09/01 10:34:10 brouard
35: Summary: WIN32
36: Author: Brouard
37:
38: Revision 1.158 2014/08/27 17:11:51 brouard
39: *** empty log message ***
40:
41: Revision 1.157 2014/08/27 16:26:55 brouard
42: Summary: Preparing windows Visual studio version
43: Author: Brouard
44:
45: In order to compile on Visual studio, time.h is now correct and time_t
46: and tm struct should be used. difftime should be used but sometimes I
47: just make the differences in raw time format (time(&now).
48: Trying to suppress #ifdef LINUX
49: Add xdg-open for __linux in order to open default browser.
50:
51: Revision 1.156 2014/08/25 20:10:10 brouard
52: *** empty log message ***
53:
54: Revision 1.155 2014/08/25 18:32:34 brouard
55: Summary: New compile, minor changes
56: Author: Brouard
57:
58: Revision 1.154 2014/06/20 17:32:08 brouard
59: Summary: Outputs now all graphs of convergence to period prevalence
60:
61: Revision 1.153 2014/06/20 16:45:46 brouard
62: Summary: If 3 live state, convergence to period prevalence on same graph
63: Author: Brouard
64:
65: Revision 1.152 2014/06/18 17:54:09 brouard
66: Summary: open browser, use gnuplot on same dir than imach if not found in the path
67:
68: Revision 1.151 2014/06/18 16:43:30 brouard
69: *** empty log message ***
70:
71: Revision 1.150 2014/06/18 16:42:35 brouard
72: Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
73: Author: brouard
74:
75: Revision 1.149 2014/06/18 15:51:14 brouard
76: Summary: Some fixes in parameter files errors
77: Author: Nicolas Brouard
78:
79: Revision 1.148 2014/06/17 17:38:48 brouard
80: Summary: Nothing new
81: Author: Brouard
82:
83: Just a new packaging for OS/X version 0.98nS
84:
85: Revision 1.147 2014/06/16 10:33:11 brouard
86: *** empty log message ***
87:
88: Revision 1.146 2014/06/16 10:20:28 brouard
89: Summary: Merge
90: Author: Brouard
91:
92: Merge, before building revised version.
93:
94: Revision 1.145 2014/06/10 21:23:15 brouard
95: Summary: Debugging with valgrind
96: Author: Nicolas Brouard
97:
98: Lot of changes in order to output the results with some covariates
99: After the Edimburgh REVES conference 2014, it seems mandatory to
100: improve the code.
101: No more memory valgrind error but a lot has to be done in order to
102: continue the work of splitting the code into subroutines.
103: Also, decodemodel has been improved. Tricode is still not
104: optimal. nbcode should be improved. Documentation has been added in
105: the source code.
106:
107: Revision 1.143 2014/01/26 09:45:38 brouard
108: Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
109:
110: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
111: (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
112:
113: Revision 1.142 2014/01/26 03:57:36 brouard
114: Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
115:
116: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
117:
118: Revision 1.141 2014/01/26 02:42:01 brouard
119: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
120:
121: Revision 1.140 2011/09/02 10:37:54 brouard
122: Summary: times.h is ok with mingw32 now.
123:
124: Revision 1.139 2010/06/14 07:50:17 brouard
125: After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
126: I remember having already fixed agemin agemax which are pointers now but not cvs saved.
127:
128: Revision 1.138 2010/04/30 18:19:40 brouard
129: *** empty log message ***
130:
131: Revision 1.137 2010/04/29 18:11:38 brouard
132: (Module): Checking covariates for more complex models
133: than V1+V2. A lot of change to be done. Unstable.
134:
135: Revision 1.136 2010/04/26 20:30:53 brouard
136: (Module): merging some libgsl code. Fixing computation
137: of likelione (using inter/intrapolation if mle = 0) in order to
138: get same likelihood as if mle=1.
139: Some cleaning of code and comments added.
140:
141: Revision 1.135 2009/10/29 15:33:14 brouard
142: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
143:
144: Revision 1.134 2009/10/29 13:18:53 brouard
145: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
146:
147: Revision 1.133 2009/07/06 10:21:25 brouard
148: just nforces
149:
150: Revision 1.132 2009/07/06 08:22:05 brouard
151: Many tings
152:
153: Revision 1.131 2009/06/20 16:22:47 brouard
154: Some dimensions resccaled
155:
156: Revision 1.130 2009/05/26 06:44:34 brouard
157: (Module): Max Covariate is now set to 20 instead of 8. A
158: lot of cleaning with variables initialized to 0. Trying to make
159: V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
160:
161: Revision 1.129 2007/08/31 13:49:27 lievre
162: Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
163:
164: Revision 1.128 2006/06/30 13:02:05 brouard
165: (Module): Clarifications on computing e.j
166:
167: Revision 1.127 2006/04/28 18:11:50 brouard
168: (Module): Yes the sum of survivors was wrong since
169: imach-114 because nhstepm was no more computed in the age
170: loop. Now we define nhstepma in the age loop.
171: (Module): In order to speed up (in case of numerous covariates) we
172: compute health expectancies (without variances) in a first step
173: and then all the health expectancies with variances or standard
174: deviation (needs data from the Hessian matrices) which slows the
175: computation.
176: In the future we should be able to stop the program is only health
177: expectancies and graph are needed without standard deviations.
178:
179: Revision 1.126 2006/04/28 17:23:28 brouard
180: (Module): Yes the sum of survivors was wrong since
181: imach-114 because nhstepm was no more computed in the age
182: loop. Now we define nhstepma in the age loop.
183: Version 0.98h
184:
185: Revision 1.125 2006/04/04 15:20:31 lievre
186: Errors in calculation of health expectancies. Age was not initialized.
187: Forecasting file added.
188:
189: Revision 1.124 2006/03/22 17:13:53 lievre
190: Parameters are printed with %lf instead of %f (more numbers after the comma).
191: The log-likelihood is printed in the log file
192:
193: Revision 1.123 2006/03/20 10:52:43 brouard
194: * imach.c (Module): <title> changed, corresponds to .htm file
195: name. <head> headers where missing.
196:
197: * imach.c (Module): Weights can have a decimal point as for
198: English (a comma might work with a correct LC_NUMERIC environment,
199: otherwise the weight is truncated).
200: Modification of warning when the covariates values are not 0 or
201: 1.
202: Version 0.98g
203:
204: Revision 1.122 2006/03/20 09:45:41 brouard
205: (Module): Weights can have a decimal point as for
206: English (a comma might work with a correct LC_NUMERIC environment,
207: otherwise the weight is truncated).
208: Modification of warning when the covariates values are not 0 or
209: 1.
210: Version 0.98g
211:
212: Revision 1.121 2006/03/16 17:45:01 lievre
213: * imach.c (Module): Comments concerning covariates added
214:
215: * imach.c (Module): refinements in the computation of lli if
216: status=-2 in order to have more reliable computation if stepm is
217: not 1 month. Version 0.98f
218:
219: Revision 1.120 2006/03/16 15:10:38 lievre
220: (Module): refinements in the computation of lli if
221: status=-2 in order to have more reliable computation if stepm is
222: not 1 month. Version 0.98f
223:
224: Revision 1.119 2006/03/15 17:42:26 brouard
225: (Module): Bug if status = -2, the loglikelihood was
226: computed as likelihood omitting the logarithm. Version O.98e
227:
228: Revision 1.118 2006/03/14 18:20:07 brouard
229: (Module): varevsij Comments added explaining the second
230: table of variances if popbased=1 .
231: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
232: (Module): Function pstamp added
233: (Module): Version 0.98d
234:
235: Revision 1.117 2006/03/14 17:16:22 brouard
236: (Module): varevsij Comments added explaining the second
237: table of variances if popbased=1 .
238: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
239: (Module): Function pstamp added
240: (Module): Version 0.98d
241:
242: Revision 1.116 2006/03/06 10:29:27 brouard
243: (Module): Variance-covariance wrong links and
244: varian-covariance of ej. is needed (Saito).
245:
246: Revision 1.115 2006/02/27 12:17:45 brouard
247: (Module): One freematrix added in mlikeli! 0.98c
248:
249: Revision 1.114 2006/02/26 12:57:58 brouard
250: (Module): Some improvements in processing parameter
251: filename with strsep.
252:
253: Revision 1.113 2006/02/24 14:20:24 brouard
254: (Module): Memory leaks checks with valgrind and:
255: datafile was not closed, some imatrix were not freed and on matrix
256: allocation too.
257:
258: Revision 1.112 2006/01/30 09:55:26 brouard
259: (Module): Back to gnuplot.exe instead of wgnuplot.exe
260:
261: Revision 1.111 2006/01/25 20:38:18 brouard
262: (Module): Lots of cleaning and bugs added (Gompertz)
263: (Module): Comments can be added in data file. Missing date values
264: can be a simple dot '.'.
265:
266: Revision 1.110 2006/01/25 00:51:50 brouard
267: (Module): Lots of cleaning and bugs added (Gompertz)
268:
269: Revision 1.109 2006/01/24 19:37:15 brouard
270: (Module): Comments (lines starting with a #) are allowed in data.
271:
272: Revision 1.108 2006/01/19 18:05:42 lievre
273: Gnuplot problem appeared...
274: To be fixed
275:
276: Revision 1.107 2006/01/19 16:20:37 brouard
277: Test existence of gnuplot in imach path
278:
279: Revision 1.106 2006/01/19 13:24:36 brouard
280: Some cleaning and links added in html output
281:
282: Revision 1.105 2006/01/05 20:23:19 lievre
283: *** empty log message ***
284:
285: Revision 1.104 2005/09/30 16:11:43 lievre
286: (Module): sump fixed, loop imx fixed, and simplifications.
287: (Module): If the status is missing at the last wave but we know
288: that the person is alive, then we can code his/her status as -2
289: (instead of missing=-1 in earlier versions) and his/her
290: contributions to the likelihood is 1 - Prob of dying from last
291: health status (= 1-p13= p11+p12 in the easiest case of somebody in
292: the healthy state at last known wave). Version is 0.98
293:
294: Revision 1.103 2005/09/30 15:54:49 lievre
295: (Module): sump fixed, loop imx fixed, and simplifications.
296:
297: Revision 1.102 2004/09/15 17:31:30 brouard
298: Add the possibility to read data file including tab characters.
299:
300: Revision 1.101 2004/09/15 10:38:38 brouard
301: Fix on curr_time
302:
303: Revision 1.100 2004/07/12 18:29:06 brouard
304: Add version for Mac OS X. Just define UNIX in Makefile
305:
306: Revision 1.99 2004/06/05 08:57:40 brouard
307: *** empty log message ***
308:
309: Revision 1.98 2004/05/16 15:05:56 brouard
310: New version 0.97 . First attempt to estimate force of mortality
311: directly from the data i.e. without the need of knowing the health
312: state at each age, but using a Gompertz model: log u =a + b*age .
313: This is the basic analysis of mortality and should be done before any
314: other analysis, in order to test if the mortality estimated from the
315: cross-longitudinal survey is different from the mortality estimated
316: from other sources like vital statistic data.
317:
318: The same imach parameter file can be used but the option for mle should be -3.
319:
320: Agnès, who wrote this part of the code, tried to keep most of the
321: former routines in order to include the new code within the former code.
322:
323: The output is very simple: only an estimate of the intercept and of
324: the slope with 95% confident intervals.
325:
326: Current limitations:
327: A) Even if you enter covariates, i.e. with the
328: model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
329: B) There is no computation of Life Expectancy nor Life Table.
330:
331: Revision 1.97 2004/02/20 13:25:42 lievre
332: Version 0.96d. Population forecasting command line is (temporarily)
333: suppressed.
334:
335: Revision 1.96 2003/07/15 15:38:55 brouard
336: * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
337: rewritten within the same printf. Workaround: many printfs.
338:
339: Revision 1.95 2003/07/08 07:54:34 brouard
340: * imach.c (Repository):
341: (Repository): Using imachwizard code to output a more meaningful covariance
342: matrix (cov(a12,c31) instead of numbers.
343:
344: Revision 1.94 2003/06/27 13:00:02 brouard
345: Just cleaning
346:
347: Revision 1.93 2003/06/25 16:33:55 brouard
348: (Module): On windows (cygwin) function asctime_r doesn't
349: exist so I changed back to asctime which exists.
350: (Module): Version 0.96b
351:
352: Revision 1.92 2003/06/25 16:30:45 brouard
353: (Module): On windows (cygwin) function asctime_r doesn't
354: exist so I changed back to asctime which exists.
355:
356: Revision 1.91 2003/06/25 15:30:29 brouard
357: * imach.c (Repository): Duplicated warning errors corrected.
358: (Repository): Elapsed time after each iteration is now output. It
359: helps to forecast when convergence will be reached. Elapsed time
360: is stamped in powell. We created a new html file for the graphs
361: concerning matrix of covariance. It has extension -cov.htm.
362:
363: Revision 1.90 2003/06/24 12:34:15 brouard
364: (Module): Some bugs corrected for windows. Also, when
365: mle=-1 a template is output in file "or"mypar.txt with the design
366: of the covariance matrix to be input.
367:
368: Revision 1.89 2003/06/24 12:30:52 brouard
369: (Module): Some bugs corrected for windows. Also, when
370: mle=-1 a template is output in file "or"mypar.txt with the design
371: of the covariance matrix to be input.
372:
373: Revision 1.88 2003/06/23 17:54:56 brouard
374: * 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.
375:
376: Revision 1.87 2003/06/18 12:26:01 brouard
377: Version 0.96
378:
379: Revision 1.86 2003/06/17 20:04:08 brouard
380: (Module): Change position of html and gnuplot routines and added
381: routine fileappend.
382:
383: Revision 1.85 2003/06/17 13:12:43 brouard
384: * imach.c (Repository): Check when date of death was earlier that
385: current date of interview. It may happen when the death was just
386: prior to the death. In this case, dh was negative and likelihood
387: was wrong (infinity). We still send an "Error" but patch by
388: assuming that the date of death was just one stepm after the
389: interview.
390: (Repository): Because some people have very long ID (first column)
391: we changed int to long in num[] and we added a new lvector for
392: memory allocation. But we also truncated to 8 characters (left
393: truncation)
394: (Repository): No more line truncation errors.
395:
396: Revision 1.84 2003/06/13 21:44:43 brouard
397: * imach.c (Repository): Replace "freqsummary" at a correct
398: place. It differs from routine "prevalence" which may be called
399: many times. Probs is memory consuming and must be used with
400: parcimony.
401: Version 0.95a3 (should output exactly the same maximization than 0.8a2)
402:
403: Revision 1.83 2003/06/10 13:39:11 lievre
404: *** empty log message ***
405:
406: Revision 1.82 2003/06/05 15:57:20 brouard
407: Add log in imach.c and fullversion number is now printed.
408:
409: */
410: /*
411: Interpolated Markov Chain
412:
413: Short summary of the programme:
414:
415: This program computes Healthy Life Expectancies from
416: cross-longitudinal data. Cross-longitudinal data consist in: -1- a
417: first survey ("cross") where individuals from different ages are
418: interviewed on their health status or degree of disability (in the
419: case of a health survey which is our main interest) -2- at least a
420: second wave of interviews ("longitudinal") which measure each change
421: (if any) in individual health status. Health expectancies are
422: computed from the time spent in each health state according to a
423: model. More health states you consider, more time is necessary to reach the
424: Maximum Likelihood of the parameters involved in the model. The
425: simplest model is the multinomial logistic model where pij is the
426: probability to be observed in state j at the second wave
427: conditional to be observed in state i at the first wave. Therefore
428: the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
429: 'age' is age and 'sex' is a covariate. If you want to have a more
430: complex model than "constant and age", you should modify the program
431: where the markup *Covariates have to be included here again* invites
432: you to do it. More covariates you add, slower the
433: convergence.
434:
435: The advantage of this computer programme, compared to a simple
436: multinomial logistic model, is clear when the delay between waves is not
437: identical for each individual. Also, if a individual missed an
438: intermediate interview, the information is lost, but taken into
439: account using an interpolation or extrapolation.
440:
441: hPijx is the probability to be observed in state i at age x+h
442: conditional to the observed state i at age x. The delay 'h' can be
443: split into an exact number (nh*stepm) of unobserved intermediate
444: states. This elementary transition (by month, quarter,
445: semester or year) is modelled as a multinomial logistic. The hPx
446: matrix is simply the matrix product of nh*stepm elementary matrices
447: and the contribution of each individual to the likelihood is simply
448: hPijx.
449:
450: Also this programme outputs the covariance matrix of the parameters but also
451: of the life expectancies. It also computes the period (stable) prevalence.
452:
453: Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
454: Institut national d'études démographiques, Paris.
455: This software have been partly granted by Euro-REVES, a concerted action
456: from the European Union.
457: It is copyrighted identically to a GNU software product, ie programme and
458: software can be distributed freely for non commercial use. Latest version
459: can be accessed at http://euroreves.ined.fr/imach .
460:
461: Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
462: or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
463:
464: **********************************************************************/
465: /*
466: main
467: read parameterfile
468: read datafile
469: concatwav
470: freqsummary
471: if (mle >= 1)
472: mlikeli
473: print results files
474: if mle==1
475: computes hessian
476: read end of parameter file: agemin, agemax, bage, fage, estepm
477: begin-prev-date,...
478: open gnuplot file
479: open html file
480: period (stable) prevalence | pl_nom 1-1 2-2 etc by covariate
481: for age prevalim() | #****** V1=0 V2=1 V3=1 V4=0 ******
482: | 65 1 0 2 1 3 1 4 0 0.96326 0.03674
483: freexexit2 possible for memory heap.
484:
485: h Pij x | pij_nom ficrestpij
486: # Cov Agex agex+h hpijx with i,j= 1-1 1-2 1-3 2-1 2-2 2-3
487: 1 85 85 1.00000 0.00000 0.00000 0.00000 1.00000 0.00000
488: 1 85 86 0.68299 0.22291 0.09410 0.71093 0.00000 0.28907
489:
490: 1 65 99 0.00364 0.00322 0.99314 0.00350 0.00310 0.99340
491: 1 65 100 0.00214 0.00204 0.99581 0.00206 0.00196 0.99597
492: variance of p one-step probabilities varprob | prob_nom ficresprob #One-step probabilities and stand. devi in ()
493: Standard deviation of one-step probabilities | probcor_nom ficresprobcor #One-step probabilities and correlation matrix
494: Matrix of variance covariance of one-step probabilities | probcov_nom ficresprobcov #One-step probabilities and covariance matrix
495:
496: forecasting if prevfcast==1 prevforecast call prevalence()
497: health expectancies
498: Variance-covariance of DFLE
499: prevalence()
500: movingaverage()
501: varevsij()
502: if popbased==1 varevsij(,popbased)
503: total life expectancies
504: Variance of period (stable) prevalence
505: end
506: */
507:
508: #define POWELL /* Instead of NLOPT */
509:
510: #include <math.h>
511: #include <stdio.h>
512: #include <stdlib.h>
513: #include <string.h>
514:
515: #ifdef _WIN32
516: #include <io.h>
517: #else
518: #include <unistd.h>
519: #endif
520:
521: #include <limits.h>
522: #include <sys/types.h>
523: #include <sys/stat.h>
524: #include <errno.h>
525: /* extern int errno; */
526:
527: /* #ifdef LINUX */
528: /* #include <time.h> */
529: /* #include "timeval.h" */
530: /* #else */
531: /* #include <sys/time.h> */
532: /* #endif */
533:
534: #include <time.h>
535:
536: #ifdef GSL
537: #include <gsl/gsl_errno.h>
538: #include <gsl/gsl_multimin.h>
539: #endif
540:
541: #ifdef NLOPT
542: #include <nlopt.h>
543: typedef struct {
544: double (* function)(double [] );
545: } myfunc_data ;
546: #endif
547:
548: /* #include <libintl.h> */
549: /* #define _(String) gettext (String) */
550:
551: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
552:
553: #define GNUPLOTPROGRAM "gnuplot"
554: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
555: #define FILENAMELENGTH 132
556:
557: #define GLOCK_ERROR_NOPATH -1 /* empty path */
558: #define GLOCK_ERROR_GETCWD -2 /* cannot get cwd */
559:
560: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
561: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
562:
563: #define NINTERVMAX 8
564: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
565: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
566: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
567: #define codtabm(h,k) 1 & (h-1) >> (k-1) ;
568: #define MAXN 20000
569: #define YEARM 12. /**< Number of months per year */
570: #define AGESUP 130
571: #define AGEBASE 40
572: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
573: #ifdef _WIN32
574: #define DIRSEPARATOR '\\'
575: #define CHARSEPARATOR "\\"
576: #define ODIRSEPARATOR '/'
577: #else
578: #define DIRSEPARATOR '/'
579: #define CHARSEPARATOR "/"
580: #define ODIRSEPARATOR '\\'
581: #endif
582:
583: /* $Id: imach.c,v 1.166 2014/12/22 11:40:47 brouard Exp $ */
584: /* $State: Exp $ */
585:
586: 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)";
587: char fullversion[]="$Revision: 1.166 $ $Date: 2014/12/22 11:40:47 $";
588: char strstart[80];
589: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
590: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings */
591: int nvar=0, nforce=0; /* Number of variables, number of forces */
592: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
593: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
594: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
595: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
596: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
597: int cptcovprodnoage=0; /**< Number of covariate products without age */
598: int cptcoveff=0; /* Total number of covariates to vary for printing results */
599: int cptcov=0; /* Working variable */
600: int npar=NPARMAX;
601: int nlstate=2; /* Number of live states */
602: int ndeath=1; /* Number of dead states */
603: int ncovmodel=0, ncovcol=0; /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
604: int popbased=0;
605:
606: int *wav; /* Number of waves for this individuual 0 is possible */
607: int maxwav=0; /* Maxim number of waves */
608: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
609: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */
610: int gipmx=0, gsw=0; /* Global variables on the number of contributions
611: to the likelihood and the sum of weights (done by funcone)*/
612: int mle=1, weightopt=0;
613: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
614: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
615: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
616: * wave mi and wave mi+1 is not an exact multiple of stepm. */
617: int countcallfunc=0; /* Count the number of calls to func */
618: double jmean=1; /* Mean space between 2 waves */
619: double **matprod2(); /* test */
620: double **oldm, **newm, **savm; /* Working pointers to matrices */
621: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
622: /*FILE *fic ; */ /* Used in readdata only */
623: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
624: FILE *ficlog, *ficrespow;
625: int globpr=0; /* Global variable for printing or not */
626: double fretone; /* Only one call to likelihood */
627: long ipmx=0; /* Number of contributions */
628: double sw; /* Sum of weights */
629: char filerespow[FILENAMELENGTH];
630: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
631: FILE *ficresilk;
632: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
633: FILE *ficresprobmorprev;
634: FILE *fichtm, *fichtmcov; /* Html File */
635: FILE *ficreseij;
636: char filerese[FILENAMELENGTH];
637: FILE *ficresstdeij;
638: char fileresstde[FILENAMELENGTH];
639: FILE *ficrescveij;
640: char filerescve[FILENAMELENGTH];
641: FILE *ficresvij;
642: char fileresv[FILENAMELENGTH];
643: FILE *ficresvpl;
644: char fileresvpl[FILENAMELENGTH];
645: char title[MAXLINE];
646: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH], filerespl[FILENAMELENGTH];
647: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
648: char tmpout[FILENAMELENGTH], tmpout2[FILENAMELENGTH];
649: char command[FILENAMELENGTH];
650: int outcmd=0;
651:
652: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
653:
654: char filelog[FILENAMELENGTH]; /* Log file */
655: char filerest[FILENAMELENGTH];
656: char fileregp[FILENAMELENGTH];
657: char popfile[FILENAMELENGTH];
658:
659: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
660:
661: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
662: /* struct timezone tzp; */
663: /* extern int gettimeofday(); */
664: struct tm tml, *gmtime(), *localtime();
665:
666: extern time_t time();
667:
668: struct tm start_time, end_time, curr_time, last_time, forecast_time;
669: time_t rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
670: struct tm tm;
671:
672: char strcurr[80], strfor[80];
673:
674: char *endptr;
675: long lval;
676: double dval;
677:
678: #define NR_END 1
679: #define FREE_ARG char*
680: #define FTOL 1.0e-10
681:
682: #define NRANSI
683: #define ITMAX 200
684:
685: #define TOL 2.0e-4
686:
687: #define CGOLD 0.3819660
688: #define ZEPS 1.0e-10
689: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
690:
691: #define GOLD 1.618034
692: #define GLIMIT 100.0
693: #define TINY 1.0e-20
694:
695: static double maxarg1,maxarg2;
696: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
697: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
698:
699: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
700: #define rint(a) floor(a+0.5)
701: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
702: /* #define mytinydouble 1.0e-16 */
703: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
704: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
705: /* static double dsqrarg; */
706: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
707: static double sqrarg;
708: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
709: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
710: int agegomp= AGEGOMP;
711:
712: int imx;
713: int stepm=1;
714: /* Stepm, step in month: minimum step interpolation*/
715:
716: int estepm;
717: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
718:
719: int m,nb;
720: long *num;
721: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
722: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
723: double **pmmij, ***probs;
724: double *ageexmed,*agecens;
725: double dateintmean=0;
726:
727: double *weight;
728: int **s; /* Status */
729: double *agedc;
730: double **covar; /**< covar[j,i], value of jth covariate for individual i,
731: * covar=matrix(0,NCOVMAX,1,n);
732: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; */
733: double idx;
734: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
735: int *Ndum; /** Freq of modality (tricode */
736: int **codtab; /**< codtab=imatrix(1,100,1,10); */
737: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
738: double *lsurv, *lpop, *tpop;
739:
740: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
741: double ftolhess; /**< Tolerance for computing hessian */
742:
743: /**************** split *************************/
744: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
745: {
746: /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
747: the name of the file (name), its extension only (ext) and its first part of the name (finame)
748: */
749: char *ss; /* pointer */
750: int l1, l2; /* length counters */
751:
752: l1 = strlen(path ); /* length of path */
753: if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
754: ss= strrchr( path, DIRSEPARATOR ); /* find last / */
755: if ( ss == NULL ) { /* no directory, so determine current directory */
756: strcpy( name, path ); /* we got the fullname name because no directory */
757: /*if(strrchr(path, ODIRSEPARATOR )==NULL)
758: printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
759: /* get current working directory */
760: /* extern char* getcwd ( char *buf , int len);*/
761: if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
762: return( GLOCK_ERROR_GETCWD );
763: }
764: /* got dirc from getcwd*/
765: printf(" DIRC = %s \n",dirc);
766: } else { /* strip direcotry from path */
767: ss++; /* after this, the filename */
768: l2 = strlen( ss ); /* length of filename */
769: if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
770: strcpy( name, ss ); /* save file name */
771: strncpy( dirc, path, l1 - l2 ); /* now the directory */
772: dirc[l1-l2] = 0; /* add zero */
773: printf(" DIRC2 = %s \n",dirc);
774: }
775: /* We add a separator at the end of dirc if not exists */
776: l1 = strlen( dirc ); /* length of directory */
777: if( dirc[l1-1] != DIRSEPARATOR ){
778: dirc[l1] = DIRSEPARATOR;
779: dirc[l1+1] = 0;
780: printf(" DIRC3 = %s \n",dirc);
781: }
782: ss = strrchr( name, '.' ); /* find last / */
783: if (ss >0){
784: ss++;
785: strcpy(ext,ss); /* save extension */
786: l1= strlen( name);
787: l2= strlen(ss)+1;
788: strncpy( finame, name, l1-l2);
789: finame[l1-l2]= 0;
790: }
791:
792: return( 0 ); /* we're done */
793: }
794:
795:
796: /******************************************/
797:
798: void replace_back_to_slash(char *s, char*t)
799: {
800: int i;
801: int lg=0;
802: i=0;
803: lg=strlen(t);
804: for(i=0; i<= lg; i++) {
805: (s[i] = t[i]);
806: if (t[i]== '\\') s[i]='/';
807: }
808: }
809:
810: char *trimbb(char *out, char *in)
811: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
812: char *s;
813: s=out;
814: while (*in != '\0'){
815: while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
816: in++;
817: }
818: *out++ = *in++;
819: }
820: *out='\0';
821: return s;
822: }
823:
824: char *cutl(char *blocc, char *alocc, char *in, char occ)
825: {
826: /* cuts string in into blocc and alocc where blocc ends before first occurence of char 'occ'
827: and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
828: gives blocc="abcdef2ghi" and alocc="j".
829: If occ is not found blocc is null and alocc is equal to in. Returns blocc
830: */
831: char *s, *t;
832: t=in;s=in;
833: while ((*in != occ) && (*in != '\0')){
834: *alocc++ = *in++;
835: }
836: if( *in == occ){
837: *(alocc)='\0';
838: s=++in;
839: }
840:
841: if (s == t) {/* occ not found */
842: *(alocc-(in-s))='\0';
843: in=s;
844: }
845: while ( *in != '\0'){
846: *blocc++ = *in++;
847: }
848:
849: *blocc='\0';
850: return t;
851: }
852: char *cutv(char *blocc, char *alocc, char *in, char occ)
853: {
854: /* cuts string in into blocc and alocc where blocc ends before last occurence of char 'occ'
855: and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
856: gives blocc="abcdef2ghi" and alocc="j".
857: If occ is not found blocc is null and alocc is equal to in. Returns alocc
858: */
859: char *s, *t;
860: t=in;s=in;
861: while (*in != '\0'){
862: while( *in == occ){
863: *blocc++ = *in++;
864: s=in;
865: }
866: *blocc++ = *in++;
867: }
868: if (s == t) /* occ not found */
869: *(blocc-(in-s))='\0';
870: else
871: *(blocc-(in-s)-1)='\0';
872: in=s;
873: while ( *in != '\0'){
874: *alocc++ = *in++;
875: }
876:
877: *alocc='\0';
878: return s;
879: }
880:
881: int nbocc(char *s, char occ)
882: {
883: int i,j=0;
884: int lg=20;
885: i=0;
886: lg=strlen(s);
887: for(i=0; i<= lg; i++) {
888: if (s[i] == occ ) j++;
889: }
890: return j;
891: }
892:
893: /* void cutv(char *u,char *v, char*t, char occ) */
894: /* { */
895: /* /\* cuts string t into u and v where u ends before last occurence of char 'occ' */
896: /* and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
897: /* gives u="abcdef2ghi" and v="j" *\/ */
898: /* int i,lg,j,p=0; */
899: /* i=0; */
900: /* lg=strlen(t); */
901: /* for(j=0; j<=lg-1; j++) { */
902: /* if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
903: /* } */
904:
905: /* for(j=0; j<p; j++) { */
906: /* (u[j] = t[j]); */
907: /* } */
908: /* u[p]='\0'; */
909:
910: /* for(j=0; j<= lg; j++) { */
911: /* if (j>=(p+1))(v[j-p-1] = t[j]); */
912: /* } */
913: /* } */
914:
915: #ifdef _WIN32
916: char * strsep(char **pp, const char *delim)
917: {
918: char *p, *q;
919:
920: if ((p = *pp) == NULL)
921: return 0;
922: if ((q = strpbrk (p, delim)) != NULL)
923: {
924: *pp = q + 1;
925: *q = '\0';
926: }
927: else
928: *pp = 0;
929: return p;
930: }
931: #endif
932:
933: /********************** nrerror ********************/
934:
935: void nrerror(char error_text[])
936: {
937: fprintf(stderr,"ERREUR ...\n");
938: fprintf(stderr,"%s\n",error_text);
939: exit(EXIT_FAILURE);
940: }
941: /*********************** vector *******************/
942: double *vector(int nl, int nh)
943: {
944: double *v;
945: v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
946: if (!v) nrerror("allocation failure in vector");
947: return v-nl+NR_END;
948: }
949:
950: /************************ free vector ******************/
951: void free_vector(double*v, int nl, int nh)
952: {
953: free((FREE_ARG)(v+nl-NR_END));
954: }
955:
956: /************************ivector *******************************/
957: int *ivector(long nl,long nh)
958: {
959: int *v;
960: v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
961: if (!v) nrerror("allocation failure in ivector");
962: return v-nl+NR_END;
963: }
964:
965: /******************free ivector **************************/
966: void free_ivector(int *v, long nl, long nh)
967: {
968: free((FREE_ARG)(v+nl-NR_END));
969: }
970:
971: /************************lvector *******************************/
972: long *lvector(long nl,long nh)
973: {
974: long *v;
975: v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
976: if (!v) nrerror("allocation failure in ivector");
977: return v-nl+NR_END;
978: }
979:
980: /******************free lvector **************************/
981: void free_lvector(long *v, long nl, long nh)
982: {
983: free((FREE_ARG)(v+nl-NR_END));
984: }
985:
986: /******************* imatrix *******************************/
987: int **imatrix(long nrl, long nrh, long ncl, long nch)
988: /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
989: {
990: long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
991: int **m;
992:
993: /* allocate pointers to rows */
994: m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
995: if (!m) nrerror("allocation failure 1 in matrix()");
996: m += NR_END;
997: m -= nrl;
998:
999:
1000: /* allocate rows and set pointers to them */
1001: m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
1002: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1003: m[nrl] += NR_END;
1004: m[nrl] -= ncl;
1005:
1006: for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
1007:
1008: /* return pointer to array of pointers to rows */
1009: return m;
1010: }
1011:
1012: /****************** free_imatrix *************************/
1013: void free_imatrix(m,nrl,nrh,ncl,nch)
1014: int **m;
1015: long nch,ncl,nrh,nrl;
1016: /* free an int matrix allocated by imatrix() */
1017: {
1018: free((FREE_ARG) (m[nrl]+ncl-NR_END));
1019: free((FREE_ARG) (m+nrl-NR_END));
1020: }
1021:
1022: /******************* matrix *******************************/
1023: double **matrix(long nrl, long nrh, long ncl, long nch)
1024: {
1025: long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
1026: double **m;
1027:
1028: m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1029: if (!m) nrerror("allocation failure 1 in matrix()");
1030: m += NR_END;
1031: m -= nrl;
1032:
1033: m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1034: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1035: m[nrl] += NR_END;
1036: m[nrl] -= ncl;
1037:
1038: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1039: return m;
1040: /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
1041: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
1042: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1043: */
1044: }
1045:
1046: /*************************free matrix ************************/
1047: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
1048: {
1049: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1050: free((FREE_ARG)(m+nrl-NR_END));
1051: }
1052:
1053: /******************* ma3x *******************************/
1054: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
1055: {
1056: long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
1057: double ***m;
1058:
1059: m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1060: if (!m) nrerror("allocation failure 1 in matrix()");
1061: m += NR_END;
1062: m -= nrl;
1063:
1064: m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1065: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1066: m[nrl] += NR_END;
1067: m[nrl] -= ncl;
1068:
1069: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1070:
1071: m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
1072: if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
1073: m[nrl][ncl] += NR_END;
1074: m[nrl][ncl] -= nll;
1075: for (j=ncl+1; j<=nch; j++)
1076: m[nrl][j]=m[nrl][j-1]+nlay;
1077:
1078: for (i=nrl+1; i<=nrh; i++) {
1079: m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
1080: for (j=ncl+1; j<=nch; j++)
1081: m[i][j]=m[i][j-1]+nlay;
1082: }
1083: return m;
1084: /* gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
1085: &(m[i][j][k]) <=> *((*(m+i) + j)+k)
1086: */
1087: }
1088:
1089: /*************************free ma3x ************************/
1090: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
1091: {
1092: free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
1093: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1094: free((FREE_ARG)(m+nrl-NR_END));
1095: }
1096:
1097: /*************** function subdirf ***********/
1098: char *subdirf(char fileres[])
1099: {
1100: /* Caution optionfilefiname is hidden */
1101: strcpy(tmpout,optionfilefiname);
1102: strcat(tmpout,"/"); /* Add to the right */
1103: strcat(tmpout,fileres);
1104: return tmpout;
1105: }
1106:
1107: /*************** function subdirf2 ***********/
1108: char *subdirf2(char fileres[], char *preop)
1109: {
1110:
1111: /* Caution optionfilefiname is hidden */
1112: strcpy(tmpout,optionfilefiname);
1113: strcat(tmpout,"/");
1114: strcat(tmpout,preop);
1115: strcat(tmpout,fileres);
1116: return tmpout;
1117: }
1118:
1119: /*************** function subdirf3 ***********/
1120: char *subdirf3(char fileres[], char *preop, char *preop2)
1121: {
1122:
1123: /* Caution optionfilefiname is hidden */
1124: strcpy(tmpout,optionfilefiname);
1125: strcat(tmpout,"/");
1126: strcat(tmpout,preop);
1127: strcat(tmpout,preop2);
1128: strcat(tmpout,fileres);
1129: return tmpout;
1130: }
1131:
1132: char *asc_diff_time(long time_sec, char ascdiff[])
1133: {
1134: long sec_left, days, hours, minutes;
1135: days = (time_sec) / (60*60*24);
1136: sec_left = (time_sec) % (60*60*24);
1137: hours = (sec_left) / (60*60) ;
1138: sec_left = (sec_left) %(60*60);
1139: minutes = (sec_left) /60;
1140: sec_left = (sec_left) % (60);
1141: sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);
1142: return ascdiff;
1143: }
1144:
1145: /***************** f1dim *************************/
1146: extern int ncom;
1147: extern double *pcom,*xicom;
1148: extern double (*nrfunc)(double []);
1149:
1150: double f1dim(double x)
1151: {
1152: int j;
1153: double f;
1154: double *xt;
1155:
1156: xt=vector(1,ncom);
1157: for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
1158: f=(*nrfunc)(xt);
1159: free_vector(xt,1,ncom);
1160: return f;
1161: }
1162:
1163: /*****************brent *************************/
1164: double brent(double ax, double bx, double cx, double (*f)(double), double tol, double *xmin)
1165: {
1166: int iter;
1167: double a,b,d,etemp;
1168: double fu=0,fv,fw,fx;
1169: double ftemp=0.;
1170: double p,q,r,tol1,tol2,u,v,w,x,xm;
1171: double e=0.0;
1172:
1173: a=(ax < cx ? ax : cx);
1174: b=(ax > cx ? ax : cx);
1175: x=w=v=bx;
1176: fw=fv=fx=(*f)(x);
1177: for (iter=1;iter<=ITMAX;iter++) {
1178: xm=0.5*(a+b);
1179: tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
1180: /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
1181: printf(".");fflush(stdout);
1182: fprintf(ficlog,".");fflush(ficlog);
1183: #ifdef DEBUGBRENT
1184: 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);
1185: 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);
1186: /* if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
1187: #endif
1188: if (fabs(x-xm) <= (tol2-0.5*(b-a))){
1189: *xmin=x;
1190: return fx;
1191: }
1192: ftemp=fu;
1193: if (fabs(e) > tol1) {
1194: r=(x-w)*(fx-fv);
1195: q=(x-v)*(fx-fw);
1196: p=(x-v)*q-(x-w)*r;
1197: q=2.0*(q-r);
1198: if (q > 0.0) p = -p;
1199: q=fabs(q);
1200: etemp=e;
1201: e=d;
1202: if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
1203: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1204: else {
1205: d=p/q;
1206: u=x+d;
1207: if (u-a < tol2 || b-u < tol2)
1208: d=SIGN(tol1,xm-x);
1209: }
1210: } else {
1211: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1212: }
1213: u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
1214: fu=(*f)(u);
1215: if (fu <= fx) {
1216: if (u >= x) a=x; else b=x;
1217: SHFT(v,w,x,u)
1218: SHFT(fv,fw,fx,fu)
1219: } else {
1220: if (u < x) a=u; else b=u;
1221: if (fu <= fw || w == x) {
1222: v=w;
1223: w=u;
1224: fv=fw;
1225: fw=fu;
1226: } else if (fu <= fv || v == x || v == w) {
1227: v=u;
1228: fv=fu;
1229: }
1230: }
1231: }
1232: nrerror("Too many iterations in brent");
1233: *xmin=x;
1234: return fx;
1235: }
1236:
1237: /****************** mnbrak ***********************/
1238:
1239: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
1240: double (*func)(double))
1241: {
1242: double ulim,u,r,q, dum;
1243: double fu;
1244:
1245: *fa=(*func)(*ax);
1246: *fb=(*func)(*bx);
1247: if (*fb > *fa) {
1248: SHFT(dum,*ax,*bx,dum)
1249: SHFT(dum,*fb,*fa,dum)
1250: }
1251: *cx=(*bx)+GOLD*(*bx-*ax);
1252: *fc=(*func)(*cx);
1253: while (*fb > *fc) { /* Declining fa, fb, fc */
1254: r=(*bx-*ax)*(*fb-*fc);
1255: q=(*bx-*cx)*(*fb-*fa);
1256: u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
1257: (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscisse of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
1258: ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscisse where function can be evaluated */
1259: if ((*bx-u)*(u-*cx) > 0.0) { /* if u between b and c */
1260: fu=(*func)(u);
1261: #ifdef DEBUG
1262: /* f(x)=A(x-u)**2+f(u) */
1263: double A, fparabu;
1264: A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
1265: fparabu= *fa - A*(*ax-u)*(*ax-u);
1266: 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);
1267: 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);
1268: #endif
1269: } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1270: fu=(*func)(u);
1271: if (fu < *fc) {
1272: SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
1273: SHFT(*fb,*fc,fu,(*func)(u))
1274: }
1275: } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1276: u=ulim;
1277: fu=(*func)(u);
1278: } else {
1279: u=(*cx)+GOLD*(*cx-*bx);
1280: fu=(*func)(u);
1281: }
1282: SHFT(*ax,*bx,*cx,u)
1283: SHFT(*fa,*fb,*fc,fu)
1284: }
1285: }
1286:
1287: /*************** linmin ************************/
1288: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
1289: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
1290: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
1291: the value of func at the returned location p . This is actually all accomplished by calling the
1292: routines mnbrak and brent .*/
1293: int ncom;
1294: double *pcom,*xicom;
1295: double (*nrfunc)(double []);
1296:
1297: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
1298: {
1299: double brent(double ax, double bx, double cx,
1300: double (*f)(double), double tol, double *xmin);
1301: double f1dim(double x);
1302: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
1303: double *fc, double (*func)(double));
1304: int j;
1305: double xx,xmin,bx,ax;
1306: double fx,fb,fa;
1307:
1308: ncom=n;
1309: pcom=vector(1,n);
1310: xicom=vector(1,n);
1311: nrfunc=func;
1312: for (j=1;j<=n;j++) {
1313: pcom[j]=p[j];
1314: xicom[j]=xi[j];
1315: }
1316: ax=0.0;
1317: xx=1.0;
1318: mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Find a bracket a,x,b in direction n=xi ie xicom */
1319: *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Find a minimum P+lambda n in that direction (lambdamin), with TOL between abscisses */
1320: #ifdef DEBUG
1321: printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1322: fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1323: #endif
1324: for (j=1;j<=n;j++) {
1325: xi[j] *= xmin;
1326: p[j] += xi[j];
1327: }
1328: free_vector(xicom,1,n);
1329: free_vector(pcom,1,n);
1330: }
1331:
1332:
1333: /*************** powell ************************/
1334: /*
1335: Minimization of a function func of n variables. Input consists of an initial starting point
1336: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
1337: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
1338: such that failure to decrease by more than this amount on one iteration signals doneness. On
1339: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
1340: function value at p , and iter is the number of iterations taken. The routine linmin is used.
1341: */
1342: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
1343: double (*func)(double []))
1344: {
1345: void linmin(double p[], double xi[], int n, double *fret,
1346: double (*func)(double []));
1347: int i,ibig,j;
1348: double del,t,*pt,*ptt,*xit;
1349: double fp,fptt;
1350: double *xits;
1351: int niterf, itmp;
1352:
1353: pt=vector(1,n);
1354: ptt=vector(1,n);
1355: xit=vector(1,n);
1356: xits=vector(1,n);
1357: *fret=(*func)(p);
1358: for (j=1;j<=n;j++) pt[j]=p[j];
1359: rcurr_time = time(NULL);
1360: for (*iter=1;;++(*iter)) {
1361: fp=(*fret);
1362: ibig=0;
1363: del=0.0;
1364: rlast_time=rcurr_time;
1365: /* (void) gettimeofday(&curr_time,&tzp); */
1366: rcurr_time = time(NULL);
1367: curr_time = *localtime(&rcurr_time);
1368: printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
1369: fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1370: /* fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1371: for (i=1;i<=n;i++) {
1372: printf(" %d %.12f",i, p[i]);
1373: fprintf(ficlog," %d %.12lf",i, p[i]);
1374: fprintf(ficrespow," %.12lf", p[i]);
1375: }
1376: printf("\n");
1377: fprintf(ficlog,"\n");
1378: fprintf(ficrespow,"\n");fflush(ficrespow);
1379: if(*iter <=3){
1380: tml = *localtime(&rcurr_time);
1381: strcpy(strcurr,asctime(&tml));
1382: rforecast_time=rcurr_time;
1383: itmp = strlen(strcurr);
1384: if(strcurr[itmp-1]=='\n') /* Windows outputs with a new line */
1385: strcurr[itmp-1]='\0';
1386: printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1387: fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1388: for(niterf=10;niterf<=30;niterf+=10){
1389: rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
1390: forecast_time = *localtime(&rforecast_time);
1391: strcpy(strfor,asctime(&forecast_time));
1392: itmp = strlen(strfor);
1393: if(strfor[itmp-1]=='\n')
1394: strfor[itmp-1]='\0';
1395: 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);
1396: 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);
1397: }
1398: }
1399: for (i=1;i<=n;i++) {
1400: for (j=1;j<=n;j++) xit[j]=xi[j][i];
1401: fptt=(*fret);
1402: #ifdef DEBUG
1403: printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1404: fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1405: #endif
1406: printf("%d",i);fflush(stdout);
1407: fprintf(ficlog,"%d",i);fflush(ficlog);
1408: linmin(p,xit,n,fret,func);
1409: if (fabs(fptt-(*fret)) > del) {
1410: del=fabs(fptt-(*fret));
1411: ibig=i;
1412: }
1413: #ifdef DEBUG
1414: printf("%d %.12e",i,(*fret));
1415: fprintf(ficlog,"%d %.12e",i,(*fret));
1416: for (j=1;j<=n;j++) {
1417: xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
1418: printf(" x(%d)=%.12e",j,xit[j]);
1419: fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1420: }
1421: for(j=1;j<=n;j++) {
1422: printf(" p(%d)=%.12e",j,p[j]);
1423: fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1424: }
1425: printf("\n");
1426: fprintf(ficlog,"\n");
1427: #endif
1428: } /* end i */
1429: if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
1430: #ifdef DEBUG
1431: int k[2],l;
1432: k[0]=1;
1433: k[1]=-1;
1434: printf("Max: %.12e",(*func)(p));
1435: fprintf(ficlog,"Max: %.12e",(*func)(p));
1436: for (j=1;j<=n;j++) {
1437: printf(" %.12e",p[j]);
1438: fprintf(ficlog," %.12e",p[j]);
1439: }
1440: printf("\n");
1441: fprintf(ficlog,"\n");
1442: for(l=0;l<=1;l++) {
1443: for (j=1;j<=n;j++) {
1444: ptt[j]=p[j]+(p[j]-pt[j])*k[l];
1445: printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1446: fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1447: }
1448: printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1449: fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1450: }
1451: #endif
1452:
1453:
1454: free_vector(xit,1,n);
1455: free_vector(xits,1,n);
1456: free_vector(ptt,1,n);
1457: free_vector(pt,1,n);
1458: return;
1459: }
1460: if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
1461: for (j=1;j<=n;j++) { /* Computes an extrapolated point */
1462: ptt[j]=2.0*p[j]-pt[j];
1463: xit[j]=p[j]-pt[j];
1464: pt[j]=p[j];
1465: }
1466: fptt=(*func)(ptt);
1467: if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1468: /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1469: /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1470: /* Let f"(x2) be the 2nd derivative equal everywhere. */
1471: /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
1472: /* will reach at f3 = fm + h^2/2 f"m ; f" = (f1 -2f2 +f3 ) / h**2 */
1473: /* f1-f3 = delta(2h) = 2 h**2 f'' = 2(f1- 2f2 +f3) */
1474: /* Thus we compare delta(2h) with observed f1-f3 */
1475: /* or best gain on one ancient line 'del' with total */
1476: /* gain f1-f2 = f1 - f2 - 'del' with del */
1477: /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1478:
1479: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del);
1480: t= t- del*SQR(fp-fptt);
1481: printf("t1= %.12lf, t2= %.12lf, t=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t);
1482: 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);
1483: #ifdef DEBUG
1484: printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1485: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1486: fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1487: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1488: 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);
1489: 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);
1490: #endif
1491: if (t < 0.0) { /* Then we use it for last direction */
1492: linmin(p,xit,n,fret,func); /* computes mean on the extrapolated direction.*/
1493: for (j=1;j<=n;j++) {
1494: xi[j][ibig]=xi[j][n]; /* Replace the direction with biggest decrease by n */
1495: xi[j][n]=xit[j]; /* and nth direction by the extrapolated */
1496: }
1497: printf("Gaining to use average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1498: fprintf(ficlog,"Gaining to use average direction of P0 P%d instead of biggest increase direction :\n",n,ibig);
1499:
1500: #ifdef DEBUG
1501: printf("Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1502: fprintf(ficlog,"Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1503: for(j=1;j<=n;j++){
1504: printf(" %.12e",xit[j]);
1505: fprintf(ficlog," %.12e",xit[j]);
1506: }
1507: printf("\n");
1508: fprintf(ficlog,"\n");
1509: #endif
1510: } /* end of t negative */
1511: } /* end if (fptt < fp) */
1512: }
1513: }
1514:
1515: /**** Prevalence limit (stable or period prevalence) ****************/
1516:
1517: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
1518: {
1519: /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1520: matrix by transitions matrix until convergence is reached */
1521:
1522: int i, ii,j,k;
1523: double min, max, maxmin, maxmax,sumnew=0.;
1524: /* double **matprod2(); */ /* test */
1525: double **out, cov[NCOVMAX+1], **pmij();
1526: double **newm;
1527: double agefin, delaymax=50 ; /* Max number of years to converge */
1528:
1529: for (ii=1;ii<=nlstate+ndeath;ii++)
1530: for (j=1;j<=nlstate+ndeath;j++){
1531: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1532: }
1533:
1534: cov[1]=1.;
1535:
1536: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1537: for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1538: newm=savm;
1539: /* Covariates have to be included here again */
1540: cov[2]=agefin;
1541:
1542: for (k=1; k<=cptcovn;k++) {
1543: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1544: /*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]]);*/
1545: }
1546: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1547: /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
1548: /* cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]] * nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]]; */
1549:
1550: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
1551: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
1552: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1553: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1554: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1555: out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1556:
1557: savm=oldm;
1558: oldm=newm;
1559: maxmax=0.;
1560: for(j=1;j<=nlstate;j++){
1561: min=1.;
1562: max=0.;
1563: for(i=1; i<=nlstate; i++) {
1564: sumnew=0;
1565: for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
1566: prlim[i][j]= newm[i][j]/(1-sumnew);
1567: /*printf(" prevalim i=%d, j=%d, prmlim[%d][%d]=%f, agefin=%d \n", i, j, i, j, prlim[i][j],(int)agefin);*/
1568: max=FMAX(max,prlim[i][j]);
1569: min=FMIN(min,prlim[i][j]);
1570: }
1571: maxmin=max-min;
1572: maxmax=FMAX(maxmax,maxmin);
1573: }
1574: if(maxmax < ftolpl){
1575: return prlim;
1576: }
1577: }
1578: }
1579:
1580: /*************** transition probabilities ***************/
1581:
1582: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1583: {
1584: /* According to parameters values stored in x and the covariate's values stored in cov,
1585: computes the probability to be observed in state j being in state i by appying the
1586: model to the ncovmodel covariates (including constant and age).
1587: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
1588: and, according on how parameters are entered, the position of the coefficient xij(nc) of the
1589: ncth covariate in the global vector x is given by the formula:
1590: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
1591: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
1592: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
1593: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1594: Outputs ps[i][j] the probability to be observed in j being in j according to
1595: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1596: */
1597: double s1, lnpijopii;
1598: /*double t34;*/
1599: int i,j, nc, ii, jj;
1600:
1601: for(i=1; i<= nlstate; i++){
1602: for(j=1; j<i;j++){
1603: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1604: /*lnpijopii += param[i][j][nc]*cov[nc];*/
1605: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
1606: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1607: }
1608: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1609: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1610: }
1611: for(j=i+1; j<=nlstate+ndeath;j++){
1612: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1613: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
1614: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
1615: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1616: }
1617: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1618: }
1619: }
1620:
1621: for(i=1; i<= nlstate; i++){
1622: s1=0;
1623: for(j=1; j<i; j++){
1624: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1625: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1626: }
1627: for(j=i+1; j<=nlstate+ndeath; j++){
1628: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1629: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1630: }
1631: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1632: ps[i][i]=1./(s1+1.);
1633: /* Computing other pijs */
1634: for(j=1; j<i; j++)
1635: ps[i][j]= exp(ps[i][j])*ps[i][i];
1636: for(j=i+1; j<=nlstate+ndeath; j++)
1637: ps[i][j]= exp(ps[i][j])*ps[i][i];
1638: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
1639: } /* end i */
1640:
1641: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
1642: for(jj=1; jj<= nlstate+ndeath; jj++){
1643: ps[ii][jj]=0;
1644: ps[ii][ii]=1;
1645: }
1646: }
1647:
1648:
1649: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
1650: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */
1651: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
1652: /* } */
1653: /* printf("\n "); */
1654: /* } */
1655: /* printf("\n ");printf("%lf ",cov[2]);*/
1656: /*
1657: for(i=1; i<= npar; i++) printf("%f ",x[i]);
1658: goto end;*/
1659: return ps;
1660: }
1661:
1662: /**************** Product of 2 matrices ******************/
1663:
1664: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1665: {
1666: /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
1667: b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
1668: /* in, b, out are matrice of pointers which should have been initialized
1669: before: only the contents of out is modified. The function returns
1670: a pointer to pointers identical to out */
1671: int i, j, k;
1672: for(i=nrl; i<= nrh; i++)
1673: for(k=ncolol; k<=ncoloh; k++){
1674: out[i][k]=0.;
1675: for(j=ncl; j<=nch; j++)
1676: out[i][k] +=in[i][j]*b[j][k];
1677: }
1678: return out;
1679: }
1680:
1681:
1682: /************* Higher Matrix Product ***************/
1683:
1684: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
1685: {
1686: /* Computes the transition matrix starting at age 'age' over
1687: 'nhstepm*hstepm*stepm' months (i.e. until
1688: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
1689: nhstepm*hstepm matrices.
1690: Output is stored in matrix po[i][j][h] for h every 'hstepm' step
1691: (typically every 2 years instead of every month which is too big
1692: for the memory).
1693: Model is determined by parameters x and covariates have to be
1694: included manually here.
1695:
1696: */
1697:
1698: int i, j, d, h, k;
1699: double **out, cov[NCOVMAX+1];
1700: double **newm;
1701:
1702: /* Hstepm could be zero and should return the unit matrix */
1703: for (i=1;i<=nlstate+ndeath;i++)
1704: for (j=1;j<=nlstate+ndeath;j++){
1705: oldm[i][j]=(i==j ? 1.0 : 0.0);
1706: po[i][j][0]=(i==j ? 1.0 : 0.0);
1707: }
1708: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1709: for(h=1; h <=nhstepm; h++){
1710: for(d=1; d <=hstepm; d++){
1711: newm=savm;
1712: /* Covariates have to be included here again */
1713: cov[1]=1.;
1714: cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
1715: for (k=1; k<=cptcovn;k++)
1716: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1717: for (k=1; k<=cptcovage;k++)
1718: cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
1719: for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1720: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
1721:
1722:
1723: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
1724: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1725: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
1726: pmij(pmmij,cov,ncovmodel,x,nlstate));
1727: savm=oldm;
1728: oldm=newm;
1729: }
1730: for(i=1; i<=nlstate+ndeath; i++)
1731: for(j=1;j<=nlstate+ndeath;j++) {
1732: po[i][j][h]=newm[i][j];
1733: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1734: }
1735: /*printf("h=%d ",h);*/
1736: } /* end h */
1737: /* printf("\n H=%d \n",h); */
1738: return po;
1739: }
1740:
1741: #ifdef NLOPT
1742: double myfunc(unsigned n, const double *p1, double *grad, void *pd){
1743: double fret;
1744: double *xt;
1745: int j;
1746: myfunc_data *d2 = (myfunc_data *) pd;
1747: /* xt = (p1-1); */
1748: xt=vector(1,n);
1749: for (j=1;j<=n;j++) xt[j]=p1[j-1]; /* xt[1]=p1[0] */
1750:
1751: fret=(d2->function)(xt); /* p xt[1]@8 is fine */
1752: /* fret=(*func)(xt); /\* p xt[1]@8 is fine *\/ */
1753: printf("Function = %.12lf ",fret);
1754: for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]);
1755: printf("\n");
1756: free_vector(xt,1,n);
1757: return fret;
1758: }
1759: #endif
1760:
1761: /*************** log-likelihood *************/
1762: double func( double *x)
1763: {
1764: int i, ii, j, k, mi, d, kk;
1765: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1766: double **out;
1767: double sw; /* Sum of weights */
1768: double lli; /* Individual log likelihood */
1769: int s1, s2;
1770: double bbh, survp;
1771: long ipmx;
1772: /*extern weight */
1773: /* We are differentiating ll according to initial status */
1774: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
1775: /*for(i=1;i<imx;i++)
1776: printf(" %d\n",s[4][i]);
1777: */
1778:
1779: ++countcallfunc;
1780:
1781: cov[1]=1.;
1782:
1783: for(k=1; k<=nlstate; k++) ll[k]=0.;
1784:
1785: if(mle==1){
1786: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1787: /* Computes the values of the ncovmodel covariates of the model
1788: depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
1789: Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
1790: to be observed in j being in i according to the model.
1791: */
1792: for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1793: cov[2+k]=covar[Tvar[k]][i];
1794: }
1795: /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4]
1796: is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]
1797: has been calculated etc */
1798: for(mi=1; mi<= wav[i]-1; mi++){
1799: for (ii=1;ii<=nlstate+ndeath;ii++)
1800: for (j=1;j<=nlstate+ndeath;j++){
1801: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1802: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1803: }
1804: for(d=0; d<dh[mi][i]; d++){
1805: newm=savm;
1806: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1807: for (kk=1; kk<=cptcovage;kk++) {
1808: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; /* Tage[kk] gives the data-covariate associated with age */
1809: }
1810: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1811: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1812: savm=oldm;
1813: oldm=newm;
1814: } /* end mult */
1815:
1816: /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
1817: /* But now since version 0.9 we anticipate for bias at large stepm.
1818: * If stepm is larger than one month (smallest stepm) and if the exact delay
1819: * (in months) between two waves is not a multiple of stepm, we rounded to
1820: * the nearest (and in case of equal distance, to the lowest) interval but now
1821: * we keep into memory the bias bh[mi][i] and also the previous matrix product
1822: * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
1823: * probability in order to take into account the bias as a fraction of the way
1824: * from savm to out if bh is negative or even beyond if bh is positive. bh varies
1825: * -stepm/2 to stepm/2 .
1826: * For stepm=1 the results are the same as for previous versions of Imach.
1827: * For stepm > 1 the results are less biased than in previous versions.
1828: */
1829: s1=s[mw[mi][i]][i];
1830: s2=s[mw[mi+1][i]][i];
1831: bbh=(double)bh[mi][i]/(double)stepm;
1832: /* bias bh is positive if real duration
1833: * is higher than the multiple of stepm and negative otherwise.
1834: */
1835: /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
1836: if( s2 > nlstate){
1837: /* i.e. if s2 is a death state and if the date of death is known
1838: then the contribution to the likelihood is the probability to
1839: die between last step unit time and current step unit time,
1840: which is also equal to probability to die before dh
1841: minus probability to die before dh-stepm .
1842: In version up to 0.92 likelihood was computed
1843: as if date of death was unknown. Death was treated as any other
1844: health state: the date of the interview describes the actual state
1845: and not the date of a change in health state. The former idea was
1846: to consider that at each interview the state was recorded
1847: (healthy, disable or death) and IMaCh was corrected; but when we
1848: introduced the exact date of death then we should have modified
1849: the contribution of an exact death to the likelihood. This new
1850: contribution is smaller and very dependent of the step unit
1851: stepm. It is no more the probability to die between last interview
1852: and month of death but the probability to survive from last
1853: interview up to one month before death multiplied by the
1854: probability to die within a month. Thanks to Chris
1855: Jackson for correcting this bug. Former versions increased
1856: mortality artificially. The bad side is that we add another loop
1857: which slows down the processing. The difference can be up to 10%
1858: lower mortality.
1859: */
1860: lli=log(out[s1][s2] - savm[s1][s2]);
1861:
1862:
1863: } else if (s2==-2) {
1864: for (j=1,survp=0. ; j<=nlstate; j++)
1865: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1866: /*survp += out[s1][j]; */
1867: lli= log(survp);
1868: }
1869:
1870: else if (s2==-4) {
1871: for (j=3,survp=0. ; j<=nlstate; j++)
1872: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1873: lli= log(survp);
1874: }
1875:
1876: else if (s2==-5) {
1877: for (j=1,survp=0. ; j<=2; j++)
1878: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1879: lli= log(survp);
1880: }
1881:
1882: else{
1883: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1884: /* 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 */
1885: }
1886: /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
1887: /*if(lli ==000.0)*/
1888: /*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); */
1889: ipmx +=1;
1890: sw += weight[i];
1891: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1892: } /* end of wave */
1893: } /* end of individual */
1894: } else if(mle==2){
1895: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1896: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1897: for(mi=1; mi<= wav[i]-1; mi++){
1898: for (ii=1;ii<=nlstate+ndeath;ii++)
1899: for (j=1;j<=nlstate+ndeath;j++){
1900: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1901: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1902: }
1903: for(d=0; d<=dh[mi][i]; d++){
1904: newm=savm;
1905: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1906: for (kk=1; kk<=cptcovage;kk++) {
1907: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1908: }
1909: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1910: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1911: savm=oldm;
1912: oldm=newm;
1913: } /* end mult */
1914:
1915: s1=s[mw[mi][i]][i];
1916: s2=s[mw[mi+1][i]][i];
1917: bbh=(double)bh[mi][i]/(double)stepm;
1918: 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 */
1919: ipmx +=1;
1920: sw += weight[i];
1921: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1922: } /* end of wave */
1923: } /* end of individual */
1924: } else if(mle==3){ /* exponential inter-extrapolation */
1925: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1926: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1927: for(mi=1; mi<= wav[i]-1; mi++){
1928: for (ii=1;ii<=nlstate+ndeath;ii++)
1929: for (j=1;j<=nlstate+ndeath;j++){
1930: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1931: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1932: }
1933: for(d=0; d<dh[mi][i]; d++){
1934: newm=savm;
1935: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1936: for (kk=1; kk<=cptcovage;kk++) {
1937: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1938: }
1939: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1940: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1941: savm=oldm;
1942: oldm=newm;
1943: } /* end mult */
1944:
1945: s1=s[mw[mi][i]][i];
1946: s2=s[mw[mi+1][i]][i];
1947: bbh=(double)bh[mi][i]/(double)stepm;
1948: 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 */
1949: ipmx +=1;
1950: sw += weight[i];
1951: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1952: } /* end of wave */
1953: } /* end of individual */
1954: }else if (mle==4){ /* ml=4 no inter-extrapolation */
1955: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1956: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1957: for(mi=1; mi<= wav[i]-1; mi++){
1958: for (ii=1;ii<=nlstate+ndeath;ii++)
1959: for (j=1;j<=nlstate+ndeath;j++){
1960: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1961: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1962: }
1963: for(d=0; d<dh[mi][i]; d++){
1964: newm=savm;
1965: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1966: for (kk=1; kk<=cptcovage;kk++) {
1967: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1968: }
1969:
1970: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1971: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1972: savm=oldm;
1973: oldm=newm;
1974: } /* end mult */
1975:
1976: s1=s[mw[mi][i]][i];
1977: s2=s[mw[mi+1][i]][i];
1978: if( s2 > nlstate){
1979: lli=log(out[s1][s2] - savm[s1][s2]);
1980: }else{
1981: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
1982: }
1983: ipmx +=1;
1984: sw += weight[i];
1985: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1986: /* 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]); */
1987: } /* end of wave */
1988: } /* end of individual */
1989: }else{ /* ml=5 no inter-extrapolation no jackson =0.8a */
1990: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1991: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1992: for(mi=1; mi<= wav[i]-1; mi++){
1993: for (ii=1;ii<=nlstate+ndeath;ii++)
1994: for (j=1;j<=nlstate+ndeath;j++){
1995: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1996: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1997: }
1998: for(d=0; d<dh[mi][i]; d++){
1999: newm=savm;
2000: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2001: for (kk=1; kk<=cptcovage;kk++) {
2002: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2003: }
2004:
2005: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2006: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2007: savm=oldm;
2008: oldm=newm;
2009: } /* end mult */
2010:
2011: s1=s[mw[mi][i]][i];
2012: s2=s[mw[mi+1][i]][i];
2013: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2014: ipmx +=1;
2015: sw += weight[i];
2016: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2017: /*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]);*/
2018: } /* end of wave */
2019: } /* end of individual */
2020: } /* End of if */
2021: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2022: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2023: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2024: return -l;
2025: }
2026:
2027: /*************** log-likelihood *************/
2028: double funcone( double *x)
2029: {
2030: /* Same as likeli but slower because of a lot of printf and if */
2031: int i, ii, j, k, mi, d, kk;
2032: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
2033: double **out;
2034: double lli; /* Individual log likelihood */
2035: double llt;
2036: int s1, s2;
2037: double bbh, survp;
2038: /*extern weight */
2039: /* We are differentiating ll according to initial status */
2040: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2041: /*for(i=1;i<imx;i++)
2042: printf(" %d\n",s[4][i]);
2043: */
2044: cov[1]=1.;
2045:
2046: for(k=1; k<=nlstate; k++) ll[k]=0.;
2047:
2048: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2049: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2050: for(mi=1; mi<= wav[i]-1; mi++){
2051: for (ii=1;ii<=nlstate+ndeath;ii++)
2052: for (j=1;j<=nlstate+ndeath;j++){
2053: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2054: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2055: }
2056: for(d=0; d<dh[mi][i]; d++){
2057: newm=savm;
2058: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2059: for (kk=1; kk<=cptcovage;kk++) {
2060: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2061: }
2062: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
2063: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2064: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2065: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
2066: /* 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
2067: savm=oldm;
2068: oldm=newm;
2069: } /* end mult */
2070:
2071: s1=s[mw[mi][i]][i];
2072: s2=s[mw[mi+1][i]][i];
2073: bbh=(double)bh[mi][i]/(double)stepm;
2074: /* bias is positive if real duration
2075: * is higher than the multiple of stepm and negative otherwise.
2076: */
2077: if( s2 > nlstate && (mle <5) ){ /* Jackson */
2078: lli=log(out[s1][s2] - savm[s1][s2]);
2079: } else if (s2==-2) {
2080: for (j=1,survp=0. ; j<=nlstate; j++)
2081: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2082: lli= log(survp);
2083: }else if (mle==1){
2084: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2085: } else if(mle==2){
2086: 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 */
2087: } else if(mle==3){ /* exponential inter-extrapolation */
2088: 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 */
2089: } else if (mle==4){ /* mle=4 no inter-extrapolation */
2090: lli=log(out[s1][s2]); /* Original formula */
2091: } else{ /* mle=0 back to 1 */
2092: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2093: /*lli=log(out[s1][s2]); */ /* Original formula */
2094: } /* End of if */
2095: ipmx +=1;
2096: sw += weight[i];
2097: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2098: /*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]); */
2099: if(globpr){
2100: fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
2101: %11.6f %11.6f %11.6f ", \
2102: num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
2103: 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
2104: for(k=1,llt=0.,l=0.; k<=nlstate; k++){
2105: llt +=ll[k]*gipmx/gsw;
2106: fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
2107: }
2108: fprintf(ficresilk," %10.6f\n", -llt);
2109: }
2110: } /* end of wave */
2111: } /* end of individual */
2112: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2113: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2114: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2115: if(globpr==0){ /* First time we count the contributions and weights */
2116: gipmx=ipmx;
2117: gsw=sw;
2118: }
2119: return -l;
2120: }
2121:
2122:
2123: /*************** function likelione ***********/
2124: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
2125: {
2126: /* This routine should help understanding what is done with
2127: the selection of individuals/waves and
2128: to check the exact contribution to the likelihood.
2129: Plotting could be done.
2130: */
2131: int k;
2132:
2133: if(*globpri !=0){ /* Just counts and sums, no printings */
2134: strcpy(fileresilk,"ilk");
2135: strcat(fileresilk,fileres);
2136: if((ficresilk=fopen(fileresilk,"w"))==NULL) {
2137: printf("Problem with resultfile: %s\n", fileresilk);
2138: fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
2139: }
2140: 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");
2141: fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
2142: /* i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
2143: for(k=1; k<=nlstate; k++)
2144: fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
2145: fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
2146: }
2147:
2148: *fretone=(*funcone)(p);
2149: if(*globpri !=0){
2150: fclose(ficresilk);
2151: fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
2152: fflush(fichtm);
2153: }
2154: return;
2155: }
2156:
2157:
2158: /*********** Maximum Likelihood Estimation ***************/
2159:
2160: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
2161: {
2162: int i,j, iter=0;
2163: double **xi;
2164: double fret;
2165: double fretone; /* Only one call to likelihood */
2166: /* char filerespow[FILENAMELENGTH];*/
2167:
2168: #ifdef NLOPT
2169: int creturn;
2170: nlopt_opt opt;
2171: /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
2172: double *lb;
2173: double minf; /* the minimum objective value, upon return */
2174: double * p1; /* Shifted parameters from 0 instead of 1 */
2175: myfunc_data dinst, *d = &dinst;
2176: #endif
2177:
2178:
2179: xi=matrix(1,npar,1,npar);
2180: for (i=1;i<=npar;i++)
2181: for (j=1;j<=npar;j++)
2182: xi[i][j]=(i==j ? 1.0 : 0.0);
2183: printf("Powell\n"); fprintf(ficlog,"Powell\n");
2184: strcpy(filerespow,"pow");
2185: strcat(filerespow,fileres);
2186: if((ficrespow=fopen(filerespow,"w"))==NULL) {
2187: printf("Problem with resultfile: %s\n", filerespow);
2188: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
2189: }
2190: fprintf(ficrespow,"# Powell\n# iter -2*LL");
2191: for (i=1;i<=nlstate;i++)
2192: for(j=1;j<=nlstate+ndeath;j++)
2193: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
2194: fprintf(ficrespow,"\n");
2195: #ifdef POWELL
2196: powell(p,xi,npar,ftol,&iter,&fret,func);
2197: #endif
2198:
2199: #ifdef NLOPT
2200: #ifdef NEWUOA
2201: opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
2202: #else
2203: opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
2204: #endif
2205: lb=vector(0,npar-1);
2206: for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
2207: nlopt_set_lower_bounds(opt, lb);
2208: nlopt_set_initial_step1(opt, 0.1);
2209:
2210: p1= (p+1); /* p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
2211: d->function = func;
2212: printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
2213: nlopt_set_min_objective(opt, myfunc, d);
2214: nlopt_set_xtol_rel(opt, ftol);
2215: if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
2216: printf("nlopt failed! %d\n",creturn);
2217: }
2218: else {
2219: printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
2220: printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
2221: iter=1; /* not equal */
2222: }
2223: nlopt_destroy(opt);
2224: #endif
2225: free_matrix(xi,1,npar,1,npar);
2226: fclose(ficrespow);
2227: printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2228: fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2229: fprintf(ficres,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2230:
2231: }
2232:
2233: /**** Computes Hessian and covariance matrix ***/
2234: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
2235: {
2236: double **a,**y,*x,pd;
2237: double **hess;
2238: int i, j;
2239: int *indx;
2240:
2241: double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
2242: double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
2243: void lubksb(double **a, int npar, int *indx, double b[]) ;
2244: void ludcmp(double **a, int npar, int *indx, double *d) ;
2245: double gompertz(double p[]);
2246: hess=matrix(1,npar,1,npar);
2247:
2248: printf("\nCalculation of the hessian matrix. Wait...\n");
2249: fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
2250: for (i=1;i<=npar;i++){
2251: printf("%d",i);fflush(stdout);
2252: fprintf(ficlog,"%d",i);fflush(ficlog);
2253:
2254: hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
2255:
2256: /* printf(" %f ",p[i]);
2257: printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
2258: }
2259:
2260: for (i=1;i<=npar;i++) {
2261: for (j=1;j<=npar;j++) {
2262: if (j>i) {
2263: printf(".%d%d",i,j);fflush(stdout);
2264: fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
2265: hess[i][j]=hessij(p,delti,i,j,func,npar);
2266:
2267: hess[j][i]=hess[i][j];
2268: /*printf(" %lf ",hess[i][j]);*/
2269: }
2270: }
2271: }
2272: printf("\n");
2273: fprintf(ficlog,"\n");
2274:
2275: printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
2276: fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
2277:
2278: a=matrix(1,npar,1,npar);
2279: y=matrix(1,npar,1,npar);
2280: x=vector(1,npar);
2281: indx=ivector(1,npar);
2282: for (i=1;i<=npar;i++)
2283: for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
2284: ludcmp(a,npar,indx,&pd);
2285:
2286: for (j=1;j<=npar;j++) {
2287: for (i=1;i<=npar;i++) x[i]=0;
2288: x[j]=1;
2289: lubksb(a,npar,indx,x);
2290: for (i=1;i<=npar;i++){
2291: matcov[i][j]=x[i];
2292: }
2293: }
2294:
2295: printf("\n#Hessian matrix#\n");
2296: fprintf(ficlog,"\n#Hessian matrix#\n");
2297: for (i=1;i<=npar;i++) {
2298: for (j=1;j<=npar;j++) {
2299: printf("%.3e ",hess[i][j]);
2300: fprintf(ficlog,"%.3e ",hess[i][j]);
2301: }
2302: printf("\n");
2303: fprintf(ficlog,"\n");
2304: }
2305:
2306: /* Recompute Inverse */
2307: for (i=1;i<=npar;i++)
2308: for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
2309: ludcmp(a,npar,indx,&pd);
2310:
2311: /* printf("\n#Hessian matrix recomputed#\n");
2312:
2313: for (j=1;j<=npar;j++) {
2314: for (i=1;i<=npar;i++) x[i]=0;
2315: x[j]=1;
2316: lubksb(a,npar,indx,x);
2317: for (i=1;i<=npar;i++){
2318: y[i][j]=x[i];
2319: printf("%.3e ",y[i][j]);
2320: fprintf(ficlog,"%.3e ",y[i][j]);
2321: }
2322: printf("\n");
2323: fprintf(ficlog,"\n");
2324: }
2325: */
2326:
2327: free_matrix(a,1,npar,1,npar);
2328: free_matrix(y,1,npar,1,npar);
2329: free_vector(x,1,npar);
2330: free_ivector(indx,1,npar);
2331: free_matrix(hess,1,npar,1,npar);
2332:
2333:
2334: }
2335:
2336: /*************** hessian matrix ****************/
2337: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
2338: {
2339: int i;
2340: int l=1, lmax=20;
2341: double k1,k2;
2342: double p2[MAXPARM+1]; /* identical to x */
2343: double res;
2344: double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
2345: double fx;
2346: int k=0,kmax=10;
2347: double l1;
2348:
2349: fx=func(x);
2350: for (i=1;i<=npar;i++) p2[i]=x[i];
2351: for(l=0 ; l <=lmax; l++){ /* Enlarging the zone around the Maximum */
2352: l1=pow(10,l);
2353: delts=delt;
2354: for(k=1 ; k <kmax; k=k+1){
2355: delt = delta*(l1*k);
2356: p2[theta]=x[theta] +delt;
2357: k1=func(p2)-fx; /* Might be negative if too close to the theoretical maximum */
2358: p2[theta]=x[theta]-delt;
2359: k2=func(p2)-fx;
2360: /*res= (k1-2.0*fx+k2)/delt/delt; */
2361: res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
2362:
2363: #ifdef DEBUGHESS
2364: 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);
2365: 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);
2366: #endif
2367: /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
2368: if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
2369: k=kmax;
2370: }
2371: else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
2372: k=kmax; l=lmax*10;
2373: }
2374: else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
2375: delts=delt;
2376: }
2377: }
2378: }
2379: delti[theta]=delts;
2380: return res;
2381:
2382: }
2383:
2384: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
2385: {
2386: int i;
2387: int l=1, lmax=20;
2388: double k1,k2,k3,k4,res,fx;
2389: double p2[MAXPARM+1];
2390: int k;
2391:
2392: fx=func(x);
2393: for (k=1; k<=2; k++) {
2394: for (i=1;i<=npar;i++) p2[i]=x[i];
2395: p2[thetai]=x[thetai]+delti[thetai]/k;
2396: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2397: k1=func(p2)-fx;
2398:
2399: p2[thetai]=x[thetai]+delti[thetai]/k;
2400: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2401: k2=func(p2)-fx;
2402:
2403: p2[thetai]=x[thetai]-delti[thetai]/k;
2404: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2405: k3=func(p2)-fx;
2406:
2407: p2[thetai]=x[thetai]-delti[thetai]/k;
2408: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2409: k4=func(p2)-fx;
2410: res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
2411: #ifdef DEBUG
2412: 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);
2413: 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);
2414: #endif
2415: }
2416: return res;
2417: }
2418:
2419: /************** Inverse of matrix **************/
2420: void ludcmp(double **a, int n, int *indx, double *d)
2421: {
2422: int i,imax,j,k;
2423: double big,dum,sum,temp;
2424: double *vv;
2425:
2426: vv=vector(1,n);
2427: *d=1.0;
2428: for (i=1;i<=n;i++) {
2429: big=0.0;
2430: for (j=1;j<=n;j++)
2431: if ((temp=fabs(a[i][j])) > big) big=temp;
2432: if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
2433: vv[i]=1.0/big;
2434: }
2435: for (j=1;j<=n;j++) {
2436: for (i=1;i<j;i++) {
2437: sum=a[i][j];
2438: for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
2439: a[i][j]=sum;
2440: }
2441: big=0.0;
2442: for (i=j;i<=n;i++) {
2443: sum=a[i][j];
2444: for (k=1;k<j;k++)
2445: sum -= a[i][k]*a[k][j];
2446: a[i][j]=sum;
2447: if ( (dum=vv[i]*fabs(sum)) >= big) {
2448: big=dum;
2449: imax=i;
2450: }
2451: }
2452: if (j != imax) {
2453: for (k=1;k<=n;k++) {
2454: dum=a[imax][k];
2455: a[imax][k]=a[j][k];
2456: a[j][k]=dum;
2457: }
2458: *d = -(*d);
2459: vv[imax]=vv[j];
2460: }
2461: indx[j]=imax;
2462: if (a[j][j] == 0.0) a[j][j]=TINY;
2463: if (j != n) {
2464: dum=1.0/(a[j][j]);
2465: for (i=j+1;i<=n;i++) a[i][j] *= dum;
2466: }
2467: }
2468: free_vector(vv,1,n); /* Doesn't work */
2469: ;
2470: }
2471:
2472: void lubksb(double **a, int n, int *indx, double b[])
2473: {
2474: int i,ii=0,ip,j;
2475: double sum;
2476:
2477: for (i=1;i<=n;i++) {
2478: ip=indx[i];
2479: sum=b[ip];
2480: b[ip]=b[i];
2481: if (ii)
2482: for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
2483: else if (sum) ii=i;
2484: b[i]=sum;
2485: }
2486: for (i=n;i>=1;i--) {
2487: sum=b[i];
2488: for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
2489: b[i]=sum/a[i][i];
2490: }
2491: }
2492:
2493: void pstamp(FILE *fichier)
2494: {
2495: fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
2496: }
2497:
2498: /************ Frequencies ********************/
2499: 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[])
2500: { /* Some frequencies */
2501:
2502: int i, m, jk, j1, bool, z1,j;
2503: int first;
2504: double ***freq; /* Frequencies */
2505: double *pp, **prop;
2506: double pos,posprop, k2, dateintsum=0,k2cpt=0;
2507: char fileresp[FILENAMELENGTH];
2508:
2509: pp=vector(1,nlstate);
2510: prop=matrix(1,nlstate,iagemin,iagemax+3);
2511: strcpy(fileresp,"p");
2512: strcat(fileresp,fileres);
2513: if((ficresp=fopen(fileresp,"w"))==NULL) {
2514: printf("Problem with prevalence resultfile: %s\n", fileresp);
2515: fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
2516: exit(0);
2517: }
2518: freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
2519: j1=0;
2520:
2521: j=cptcoveff;
2522: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2523:
2524: first=1;
2525:
2526: /* for(k1=1; k1<=j ; k1++){ /* Loop on covariates */
2527: /* for(i1=1; i1<=ncodemax[k1];i1++){ /* Now it is 2 */
2528: /* j1++;
2529: */
2530: for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
2531: /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
2532: scanf("%d", i);*/
2533: for (i=-5; i<=nlstate+ndeath; i++)
2534: for (jk=-5; jk<=nlstate+ndeath; jk++)
2535: for(m=iagemin; m <= iagemax+3; m++)
2536: freq[i][jk][m]=0;
2537:
2538: for (i=1; i<=nlstate; i++)
2539: for(m=iagemin; m <= iagemax+3; m++)
2540: prop[i][m]=0;
2541:
2542: dateintsum=0;
2543: k2cpt=0;
2544: for (i=1; i<=imx; i++) {
2545: bool=1;
2546: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
2547: for (z1=1; z1<=cptcoveff; z1++)
2548: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
2549: /* Tests if the value of each of the covariates of i is equal to filter j1 */
2550: bool=0;
2551: /* 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",
2552: bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
2553: j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
2554: /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
2555: }
2556: }
2557:
2558: if (bool==1){
2559: for(m=firstpass; m<=lastpass; m++){
2560: k2=anint[m][i]+(mint[m][i]/12.);
2561: /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
2562: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2563: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2564: if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
2565: if (m<lastpass) {
2566: freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
2567: freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
2568: }
2569:
2570: if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
2571: dateintsum=dateintsum+k2;
2572: k2cpt++;
2573: }
2574: /*}*/
2575: }
2576: }
2577: } /* end i */
2578:
2579: /* fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
2580: pstamp(ficresp);
2581: if (cptcovn>0) {
2582: fprintf(ficresp, "\n#********** Variable ");
2583: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2584: fprintf(ficresp, "**********\n#");
2585: fprintf(ficlog, "\n#********** Variable ");
2586: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2587: fprintf(ficlog, "**********\n#");
2588: }
2589: for(i=1; i<=nlstate;i++)
2590: fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
2591: fprintf(ficresp, "\n");
2592:
2593: for(i=iagemin; i <= iagemax+3; i++){
2594: if(i==iagemax+3){
2595: fprintf(ficlog,"Total");
2596: }else{
2597: if(first==1){
2598: first=0;
2599: printf("See log file for details...\n");
2600: }
2601: fprintf(ficlog,"Age %d", i);
2602: }
2603: for(jk=1; jk <=nlstate ; jk++){
2604: for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
2605: pp[jk] += freq[jk][m][i];
2606: }
2607: for(jk=1; jk <=nlstate ; jk++){
2608: for(m=-1, pos=0; m <=0 ; m++)
2609: pos += freq[jk][m][i];
2610: if(pp[jk]>=1.e-10){
2611: if(first==1){
2612: printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
2613: }
2614: fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
2615: }else{
2616: if(first==1)
2617: printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2618: fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2619: }
2620: }
2621:
2622: for(jk=1; jk <=nlstate ; jk++){
2623: for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
2624: pp[jk] += freq[jk][m][i];
2625: }
2626: for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
2627: pos += pp[jk];
2628: posprop += prop[jk][i];
2629: }
2630: for(jk=1; jk <=nlstate ; jk++){
2631: if(pos>=1.e-5){
2632: if(first==1)
2633: printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2634: fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2635: }else{
2636: if(first==1)
2637: printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2638: fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2639: }
2640: if( i <= iagemax){
2641: if(pos>=1.e-5){
2642: fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
2643: /*probs[i][jk][j1]= pp[jk]/pos;*/
2644: /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
2645: }
2646: else
2647: fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
2648: }
2649: }
2650:
2651: for(jk=-1; jk <=nlstate+ndeath; jk++)
2652: for(m=-1; m <=nlstate+ndeath; m++)
2653: if(freq[jk][m][i] !=0 ) {
2654: if(first==1)
2655: printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
2656: fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
2657: }
2658: if(i <= iagemax)
2659: fprintf(ficresp,"\n");
2660: if(first==1)
2661: printf("Others in log...\n");
2662: fprintf(ficlog,"\n");
2663: }
2664: /*}*/
2665: }
2666: dateintmean=dateintsum/k2cpt;
2667:
2668: fclose(ficresp);
2669: free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
2670: free_vector(pp,1,nlstate);
2671: free_matrix(prop,1,nlstate,iagemin, iagemax+3);
2672: /* End of Freq */
2673: }
2674:
2675: /************ Prevalence ********************/
2676: 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)
2677: {
2678: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
2679: in each health status at the date of interview (if between dateprev1 and dateprev2).
2680: We still use firstpass and lastpass as another selection.
2681: */
2682:
2683: int i, m, jk, j1, bool, z1,j;
2684:
2685: double **prop;
2686: double posprop;
2687: double y2; /* in fractional years */
2688: int iagemin, iagemax;
2689: int first; /** to stop verbosity which is redirected to log file */
2690:
2691: iagemin= (int) agemin;
2692: iagemax= (int) agemax;
2693: /*pp=vector(1,nlstate);*/
2694: prop=matrix(1,nlstate,iagemin,iagemax+3);
2695: /* freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
2696: j1=0;
2697:
2698: /*j=cptcoveff;*/
2699: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2700:
2701: first=1;
2702: for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
2703: /*for(i1=1; i1<=ncodemax[k1];i1++){
2704: j1++;*/
2705:
2706: for (i=1; i<=nlstate; i++)
2707: for(m=iagemin; m <= iagemax+3; m++)
2708: prop[i][m]=0.0;
2709:
2710: for (i=1; i<=imx; i++) { /* Each individual */
2711: bool=1;
2712: if (cptcovn>0) {
2713: for (z1=1; z1<=cptcoveff; z1++)
2714: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
2715: bool=0;
2716: }
2717: if (bool==1) {
2718: for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
2719: y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
2720: if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
2721: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2722: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2723: 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);
2724: if (s[m][i]>0 && s[m][i]<=nlstate) {
2725: /*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]]);*/
2726: prop[s[m][i]][(int)agev[m][i]] += weight[i];
2727: prop[s[m][i]][iagemax+3] += weight[i];
2728: }
2729: }
2730: } /* end selection of waves */
2731: }
2732: }
2733: for(i=iagemin; i <= iagemax+3; i++){
2734: for(jk=1,posprop=0; jk <=nlstate ; jk++) {
2735: posprop += prop[jk][i];
2736: }
2737:
2738: for(jk=1; jk <=nlstate ; jk++){
2739: if( i <= iagemax){
2740: if(posprop>=1.e-5){
2741: probs[i][jk][j1]= prop[jk][i]/posprop;
2742: } else{
2743: if(first==1){
2744: first=0;
2745: 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]);
2746: }
2747: }
2748: }
2749: }/* end jk */
2750: }/* end i */
2751: /*} *//* end i1 */
2752: } /* end j1 */
2753:
2754: /* free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
2755: /*free_vector(pp,1,nlstate);*/
2756: free_matrix(prop,1,nlstate, iagemin,iagemax+3);
2757: } /* End of prevalence */
2758:
2759: /************* Waves Concatenation ***************/
2760:
2761: 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)
2762: {
2763: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
2764: Death is a valid wave (if date is known).
2765: mw[mi][i] is the mi (mi=1 to wav[i]) effective wave of individual i
2766: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
2767: and mw[mi+1][i]. dh depends on stepm.
2768: */
2769:
2770: int i, mi, m;
2771: /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
2772: double sum=0., jmean=0.;*/
2773: int first;
2774: int j, k=0,jk, ju, jl;
2775: double sum=0.;
2776: first=0;
2777: jmin=100000;
2778: jmax=-1;
2779: jmean=0.;
2780: for(i=1; i<=imx; i++){
2781: mi=0;
2782: m=firstpass;
2783: while(s[m][i] <= nlstate){
2784: if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
2785: mw[++mi][i]=m;
2786: if(m >=lastpass)
2787: break;
2788: else
2789: m++;
2790: }/* end while */
2791: if (s[m][i] > nlstate){
2792: mi++; /* Death is another wave */
2793: /* if(mi==0) never been interviewed correctly before death */
2794: /* Only death is a correct wave */
2795: mw[mi][i]=m;
2796: }
2797:
2798: wav[i]=mi;
2799: if(mi==0){
2800: nbwarn++;
2801: if(first==0){
2802: printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
2803: first=1;
2804: }
2805: if(first==1){
2806: fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
2807: }
2808: } /* end mi==0 */
2809: } /* End individuals */
2810:
2811: for(i=1; i<=imx; i++){
2812: for(mi=1; mi<wav[i];mi++){
2813: if (stepm <=0)
2814: dh[mi][i]=1;
2815: else{
2816: if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
2817: if (agedc[i] < 2*AGESUP) {
2818: j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
2819: if(j==0) j=1; /* Survives at least one month after exam */
2820: else if(j<0){
2821: nberr++;
2822: 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]);
2823: j=1; /* Temporary Dangerous patch */
2824: 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);
2825: 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]);
2826: 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);
2827: }
2828: k=k+1;
2829: if (j >= jmax){
2830: jmax=j;
2831: ijmax=i;
2832: }
2833: if (j <= jmin){
2834: jmin=j;
2835: ijmin=i;
2836: }
2837: sum=sum+j;
2838: /*if (j<0) printf("j=%d num=%d \n",j,i);*/
2839: /* printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
2840: }
2841: }
2842: else{
2843: j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
2844: /* 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]); */
2845:
2846: k=k+1;
2847: if (j >= jmax) {
2848: jmax=j;
2849: ijmax=i;
2850: }
2851: else if (j <= jmin){
2852: jmin=j;
2853: ijmin=i;
2854: }
2855: /* if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
2856: /*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]);*/
2857: if(j<0){
2858: nberr++;
2859: 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]);
2860: 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]);
2861: }
2862: sum=sum+j;
2863: }
2864: jk= j/stepm;
2865: jl= j -jk*stepm;
2866: ju= j -(jk+1)*stepm;
2867: if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
2868: if(jl==0){
2869: dh[mi][i]=jk;
2870: bh[mi][i]=0;
2871: }else{ /* We want a negative bias in order to only have interpolation ie
2872: * to avoid the price of an extra matrix product in likelihood */
2873: dh[mi][i]=jk+1;
2874: bh[mi][i]=ju;
2875: }
2876: }else{
2877: if(jl <= -ju){
2878: dh[mi][i]=jk;
2879: bh[mi][i]=jl; /* bias is positive if real duration
2880: * is higher than the multiple of stepm and negative otherwise.
2881: */
2882: }
2883: else{
2884: dh[mi][i]=jk+1;
2885: bh[mi][i]=ju;
2886: }
2887: if(dh[mi][i]==0){
2888: dh[mi][i]=1; /* At least one step */
2889: bh[mi][i]=ju; /* At least one step */
2890: /* 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);*/
2891: }
2892: } /* end if mle */
2893: }
2894: } /* end wave */
2895: }
2896: jmean=sum/k;
2897: 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);
2898: 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);
2899: }
2900:
2901: /*********** Tricode ****************************/
2902: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
2903: {
2904: /**< Uses cptcovn+2*cptcovprod as the number of covariates */
2905: /* Tvar[i]=atoi(stre); find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1
2906: /* Boring subroutine which should only output nbcode[Tvar[j]][k]
2907: * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
2908: /* nbcode[Tvar[j]][1]=
2909: */
2910:
2911: int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
2912: int modmaxcovj=0; /* Modality max of covariates j */
2913: int cptcode=0; /* Modality max of covariates j */
2914: int modmincovj=0; /* Modality min of covariates j */
2915:
2916:
2917: cptcoveff=0;
2918:
2919: for (k=-1; k < maxncov; k++) Ndum[k]=0;
2920: for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
2921:
2922: /* Loop on covariates without age and products */
2923: for (j=1; j<=(cptcovs); j++) { /* model V1 + V2*age+ V3 + V3*V4 : V1 + V3 = 2 only */
2924: for (i=1; i<=imx; i++) { /* Lopp on individuals: reads the data file to get the maximum value of the
2925: modality of this covariate Vj*/
2926: ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
2927: * If product of Vn*Vm, still boolean *:
2928: * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
2929: * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0 */
2930: /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
2931: modality of the nth covariate of individual i. */
2932: if (ij > modmaxcovj)
2933: modmaxcovj=ij;
2934: else if (ij < modmincovj)
2935: modmincovj=ij;
2936: if ((ij < -1) && (ij > NCOVMAX)){
2937: printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
2938: exit(1);
2939: }else
2940: Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
2941: /* If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
2942: /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
2943: /* getting the maximum value of the modality of the covariate
2944: (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
2945: female is 1, then modmaxcovj=1.*/
2946: }
2947: printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
2948: cptcode=modmaxcovj;
2949: /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
2950: /*for (i=0; i<=cptcode; i++) {*/
2951: for (i=modmincovj; i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
2952: printf("Frequencies of covariates %d V%d %d\n", j, Tvar[j], Ndum[i]);
2953: if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
2954: ncodemax[j]++; /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
2955: }
2956: /* In fact ncodemax[j]=2 (dichotom. variables only) but it could be more for
2957: historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
2958: } /* Ndum[-1] number of undefined modalities */
2959:
2960: /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
2961: /* For covariate j, modalities could be 1, 2, 3, 4. If Ndum[2]=0 ncodemax[j] is not 4 but 3 */
2962: /* If Ndum[3}= 635; Ndum[4]=0; Ndum[5]=0; Ndum[6]=27; Ndum[7]=125;
2963: modmincovj=3; modmaxcovj = 7;
2964: There are only 3 modalities non empty (or 2 if 27 is too few) : ncodemax[j]=3;
2965: which will be coded 0, 1, 2 which in binary on 3-1 digits are 0=00 1=01, 2=10; defining two dummy
2966: variables V1_1 and V1_2.
2967: nbcode[Tvar[j]][ij]=k;
2968: nbcode[Tvar[j]][1]=0;
2969: nbcode[Tvar[j]][2]=1;
2970: nbcode[Tvar[j]][3]=2;
2971: */
2972: ij=1; /* ij is similar to i but can jumps over null modalities */
2973: for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
2974: for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
2975: /*recode from 0 */
2976: if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
2977: nbcode[Tvar[j]][ij]=k; /* stores the modality in an array nbcode.
2978: k is a modality. If we have model=V1+V1*sex
2979: then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
2980: ij++;
2981: }
2982: if (ij > ncodemax[j]) break;
2983: } /* end of loop on */
2984: } /* end of loop on modality */
2985: } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/
2986:
2987: for (k=-1; k< maxncov; k++) Ndum[k]=0;
2988:
2989: for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */
2990: /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
2991: ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
2992: Ndum[ij]++;
2993: }
2994:
2995: ij=1;
2996: for (i=0; i<= maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
2997: /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
2998: if((Ndum[i]!=0) && (i<=ncovcol)){
2999: /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
3000: Tvaraff[ij]=i; /*For printing (unclear) */
3001: ij++;
3002: }else
3003: Tvaraff[ij]=0;
3004: }
3005: ij--;
3006: cptcoveff=ij; /*Number of total covariates*/
3007:
3008: }
3009:
3010:
3011: /*********** Health Expectancies ****************/
3012:
3013: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
3014:
3015: {
3016: /* Health expectancies, no variances */
3017: int i, j, nhstepm, hstepm, h, nstepm;
3018: int nhstepma, nstepma; /* Decreasing with age */
3019: double age, agelim, hf;
3020: double ***p3mat;
3021: double eip;
3022:
3023: pstamp(ficreseij);
3024: fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
3025: fprintf(ficreseij,"# Age");
3026: for(i=1; i<=nlstate;i++){
3027: for(j=1; j<=nlstate;j++){
3028: fprintf(ficreseij," e%1d%1d ",i,j);
3029: }
3030: fprintf(ficreseij," e%1d. ",i);
3031: }
3032: fprintf(ficreseij,"\n");
3033:
3034:
3035: if(estepm < stepm){
3036: printf ("Problem %d lower than %d\n",estepm, stepm);
3037: }
3038: else hstepm=estepm;
3039: /* We compute the life expectancy from trapezoids spaced every estepm months
3040: * This is mainly to measure the difference between two models: for example
3041: * if stepm=24 months pijx are given only every 2 years and by summing them
3042: * we are calculating an estimate of the Life Expectancy assuming a linear
3043: * progression in between and thus overestimating or underestimating according
3044: * to the curvature of the survival function. If, for the same date, we
3045: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3046: * to compare the new estimate of Life expectancy with the same linear
3047: * hypothesis. A more precise result, taking into account a more precise
3048: * curvature will be obtained if estepm is as small as stepm. */
3049:
3050: /* For example we decided to compute the life expectancy with the smallest unit */
3051: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3052: nhstepm is the number of hstepm from age to agelim
3053: nstepm is the number of stepm from age to agelin.
3054: Look at hpijx to understand the reason of that which relies in memory size
3055: and note for a fixed period like estepm months */
3056: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3057: survival function given by stepm (the optimization length). Unfortunately it
3058: means that if the survival funtion is printed only each two years of age and if
3059: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3060: results. So we changed our mind and took the option of the best precision.
3061: */
3062: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3063:
3064: agelim=AGESUP;
3065: /* If stepm=6 months */
3066: /* Computed by stepm unit matrices, product of hstepm matrices, stored
3067: in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
3068:
3069: /* nhstepm age range expressed in number of stepm */
3070: nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3071: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3072: /* if (stepm >= YEARM) hstepm=1;*/
3073: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3074: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3075:
3076: for (age=bage; age<=fage; age ++){
3077: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3078: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3079: /* if (stepm >= YEARM) hstepm=1;*/
3080: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3081:
3082: /* If stepm=6 months */
3083: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3084: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3085:
3086: hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3087:
3088: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3089:
3090: printf("%d|",(int)age);fflush(stdout);
3091: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3092:
3093: /* Computing expectancies */
3094: for(i=1; i<=nlstate;i++)
3095: for(j=1; j<=nlstate;j++)
3096: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3097: eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
3098:
3099: /* 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]);*/
3100:
3101: }
3102:
3103: fprintf(ficreseij,"%3.0f",age );
3104: for(i=1; i<=nlstate;i++){
3105: eip=0;
3106: for(j=1; j<=nlstate;j++){
3107: eip +=eij[i][j][(int)age];
3108: fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
3109: }
3110: fprintf(ficreseij,"%9.4f", eip );
3111: }
3112: fprintf(ficreseij,"\n");
3113:
3114: }
3115: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3116: printf("\n");
3117: fprintf(ficlog,"\n");
3118:
3119: }
3120:
3121: 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[] )
3122:
3123: {
3124: /* Covariances of health expectancies eij and of total life expectancies according
3125: to initial status i, ei. .
3126: */
3127: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
3128: int nhstepma, nstepma; /* Decreasing with age */
3129: double age, agelim, hf;
3130: double ***p3matp, ***p3matm, ***varhe;
3131: double **dnewm,**doldm;
3132: double *xp, *xm;
3133: double **gp, **gm;
3134: double ***gradg, ***trgradg;
3135: int theta;
3136:
3137: double eip, vip;
3138:
3139: varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
3140: xp=vector(1,npar);
3141: xm=vector(1,npar);
3142: dnewm=matrix(1,nlstate*nlstate,1,npar);
3143: doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
3144:
3145: pstamp(ficresstdeij);
3146: fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
3147: fprintf(ficresstdeij,"# Age");
3148: for(i=1; i<=nlstate;i++){
3149: for(j=1; j<=nlstate;j++)
3150: fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
3151: fprintf(ficresstdeij," e%1d. ",i);
3152: }
3153: fprintf(ficresstdeij,"\n");
3154:
3155: pstamp(ficrescveij);
3156: fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
3157: fprintf(ficrescveij,"# Age");
3158: for(i=1; i<=nlstate;i++)
3159: for(j=1; j<=nlstate;j++){
3160: cptj= (j-1)*nlstate+i;
3161: for(i2=1; i2<=nlstate;i2++)
3162: for(j2=1; j2<=nlstate;j2++){
3163: cptj2= (j2-1)*nlstate+i2;
3164: if(cptj2 <= cptj)
3165: fprintf(ficrescveij," %1d%1d,%1d%1d",i,j,i2,j2);
3166: }
3167: }
3168: fprintf(ficrescveij,"\n");
3169:
3170: if(estepm < stepm){
3171: printf ("Problem %d lower than %d\n",estepm, stepm);
3172: }
3173: else hstepm=estepm;
3174: /* We compute the life expectancy from trapezoids spaced every estepm months
3175: * This is mainly to measure the difference between two models: for example
3176: * if stepm=24 months pijx are given only every 2 years and by summing them
3177: * we are calculating an estimate of the Life Expectancy assuming a linear
3178: * progression in between and thus overestimating or underestimating according
3179: * to the curvature of the survival function. If, for the same date, we
3180: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3181: * to compare the new estimate of Life expectancy with the same linear
3182: * hypothesis. A more precise result, taking into account a more precise
3183: * curvature will be obtained if estepm is as small as stepm. */
3184:
3185: /* For example we decided to compute the life expectancy with the smallest unit */
3186: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3187: nhstepm is the number of hstepm from age to agelim
3188: nstepm is the number of stepm from age to agelin.
3189: Look at hpijx to understand the reason of that which relies in memory size
3190: and note for a fixed period like estepm months */
3191: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3192: survival function given by stepm (the optimization length). Unfortunately it
3193: means that if the survival funtion is printed only each two years of age and if
3194: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3195: results. So we changed our mind and took the option of the best precision.
3196: */
3197: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3198:
3199: /* If stepm=6 months */
3200: /* nhstepm age range expressed in number of stepm */
3201: agelim=AGESUP;
3202: nstepm=(int) rint((agelim-bage)*YEARM/stepm);
3203: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3204: /* if (stepm >= YEARM) hstepm=1;*/
3205: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3206:
3207: p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3208: p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3209: gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
3210: trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
3211: gp=matrix(0,nhstepm,1,nlstate*nlstate);
3212: gm=matrix(0,nhstepm,1,nlstate*nlstate);
3213:
3214: for (age=bage; age<=fage; age ++){
3215: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3216: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3217: /* if (stepm >= YEARM) hstepm=1;*/
3218: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3219:
3220: /* If stepm=6 months */
3221: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3222: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3223:
3224: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3225:
3226: /* Computing Variances of health expectancies */
3227: /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
3228: decrease memory allocation */
3229: for(theta=1; theta <=npar; theta++){
3230: for(i=1; i<=npar; i++){
3231: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3232: xm[i] = x[i] - (i==theta ?delti[theta]:0);
3233: }
3234: hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);
3235: hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);
3236:
3237: for(j=1; j<= nlstate; j++){
3238: for(i=1; i<=nlstate; i++){
3239: for(h=0; h<=nhstepm-1; h++){
3240: gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
3241: gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
3242: }
3243: }
3244: }
3245:
3246: for(ij=1; ij<= nlstate*nlstate; ij++)
3247: for(h=0; h<=nhstepm-1; h++){
3248: gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
3249: }
3250: }/* End theta */
3251:
3252:
3253: for(h=0; h<=nhstepm-1; h++)
3254: for(j=1; j<=nlstate*nlstate;j++)
3255: for(theta=1; theta <=npar; theta++)
3256: trgradg[h][j][theta]=gradg[h][theta][j];
3257:
3258:
3259: for(ij=1;ij<=nlstate*nlstate;ij++)
3260: for(ji=1;ji<=nlstate*nlstate;ji++)
3261: varhe[ij][ji][(int)age] =0.;
3262:
3263: printf("%d|",(int)age);fflush(stdout);
3264: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3265: for(h=0;h<=nhstepm-1;h++){
3266: for(k=0;k<=nhstepm-1;k++){
3267: matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
3268: matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
3269: for(ij=1;ij<=nlstate*nlstate;ij++)
3270: for(ji=1;ji<=nlstate*nlstate;ji++)
3271: varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
3272: }
3273: }
3274:
3275: /* Computing expectancies */
3276: hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3277: for(i=1; i<=nlstate;i++)
3278: for(j=1; j<=nlstate;j++)
3279: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3280: eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
3281:
3282: /* 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]);*/
3283:
3284: }
3285:
3286: fprintf(ficresstdeij,"%3.0f",age );
3287: for(i=1; i<=nlstate;i++){
3288: eip=0.;
3289: vip=0.;
3290: for(j=1; j<=nlstate;j++){
3291: eip += eij[i][j][(int)age];
3292: for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
3293: vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
3294: fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
3295: }
3296: fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
3297: }
3298: fprintf(ficresstdeij,"\n");
3299:
3300: fprintf(ficrescveij,"%3.0f",age );
3301: for(i=1; i<=nlstate;i++)
3302: for(j=1; j<=nlstate;j++){
3303: cptj= (j-1)*nlstate+i;
3304: for(i2=1; i2<=nlstate;i2++)
3305: for(j2=1; j2<=nlstate;j2++){
3306: cptj2= (j2-1)*nlstate+i2;
3307: if(cptj2 <= cptj)
3308: fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
3309: }
3310: }
3311: fprintf(ficrescveij,"\n");
3312:
3313: }
3314: free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
3315: free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
3316: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
3317: free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
3318: free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3319: free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3320: printf("\n");
3321: fprintf(ficlog,"\n");
3322:
3323: free_vector(xm,1,npar);
3324: free_vector(xp,1,npar);
3325: free_matrix(dnewm,1,nlstate*nlstate,1,npar);
3326: free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
3327: free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
3328: }
3329:
3330: /************ Variance ******************/
3331: 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[])
3332: {
3333: /* Variance of health expectancies */
3334: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
3335: /* double **newm;*/
3336: double **dnewm,**doldm;
3337: double **dnewmp,**doldmp;
3338: int i, j, nhstepm, hstepm, h, nstepm ;
3339: int k;
3340: double *xp;
3341: double **gp, **gm; /* for var eij */
3342: double ***gradg, ***trgradg; /*for var eij */
3343: double **gradgp, **trgradgp; /* for var p point j */
3344: double *gpp, *gmp; /* for var p point j */
3345: double **varppt; /* for var p point j nlstate to nlstate+ndeath */
3346: double ***p3mat;
3347: double age,agelim, hf;
3348: double ***mobaverage;
3349: int theta;
3350: char digit[4];
3351: char digitp[25];
3352:
3353: char fileresprobmorprev[FILENAMELENGTH];
3354:
3355: if(popbased==1){
3356: if(mobilav!=0)
3357: strcpy(digitp,"-populbased-mobilav-");
3358: else strcpy(digitp,"-populbased-nomobil-");
3359: }
3360: else
3361: strcpy(digitp,"-stablbased-");
3362:
3363: if (mobilav!=0) {
3364: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3365: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
3366: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
3367: printf(" Error in movingaverage mobilav=%d\n",mobilav);
3368: }
3369: }
3370:
3371: strcpy(fileresprobmorprev,"prmorprev");
3372: sprintf(digit,"%-d",ij);
3373: /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
3374: strcat(fileresprobmorprev,digit); /* Tvar to be done */
3375: strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
3376: strcat(fileresprobmorprev,fileres);
3377: if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
3378: printf("Problem with resultfile: %s\n", fileresprobmorprev);
3379: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
3380: }
3381: printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3382:
3383: fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3384: pstamp(ficresprobmorprev);
3385: 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);
3386: fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
3387: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3388: fprintf(ficresprobmorprev," p.%-d SE",j);
3389: for(i=1; i<=nlstate;i++)
3390: fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
3391: }
3392: fprintf(ficresprobmorprev,"\n");
3393: fprintf(ficgp,"\n# Routine varevsij");
3394: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
3395: 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");
3396: fprintf(fichtm,"\n<br>%s <br>\n",digitp);
3397: /* } */
3398: varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3399: pstamp(ficresvij);
3400: fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n# (weighted average of eij where weights are ");
3401: if(popbased==1)
3402: 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);
3403: else
3404: fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
3405: fprintf(ficresvij,"# Age");
3406: for(i=1; i<=nlstate;i++)
3407: for(j=1; j<=nlstate;j++)
3408: fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
3409: fprintf(ficresvij,"\n");
3410:
3411: xp=vector(1,npar);
3412: dnewm=matrix(1,nlstate,1,npar);
3413: doldm=matrix(1,nlstate,1,nlstate);
3414: dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
3415: doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3416:
3417: gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
3418: gpp=vector(nlstate+1,nlstate+ndeath);
3419: gmp=vector(nlstate+1,nlstate+ndeath);
3420: trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
3421:
3422: if(estepm < stepm){
3423: printf ("Problem %d lower than %d\n",estepm, stepm);
3424: }
3425: else hstepm=estepm;
3426: /* For example we decided to compute the life expectancy with the smallest unit */
3427: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3428: nhstepm is the number of hstepm from age to agelim
3429: nstepm is the number of stepm from age to agelin.
3430: Look at function hpijx to understand why (it is linked to memory size questions) */
3431: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3432: survival function given by stepm (the optimization length). Unfortunately it
3433: means that if the survival funtion is printed every two years of age and if
3434: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3435: results. So we changed our mind and took the option of the best precision.
3436: */
3437: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3438: agelim = AGESUP;
3439: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3440: nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3441: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3442: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3443: gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
3444: gp=matrix(0,nhstepm,1,nlstate);
3445: gm=matrix(0,nhstepm,1,nlstate);
3446:
3447:
3448: for(theta=1; theta <=npar; theta++){
3449: for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
3450: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3451: }
3452: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3453: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3454:
3455: if (popbased==1) {
3456: if(mobilav ==0){
3457: for(i=1; i<=nlstate;i++)
3458: prlim[i][i]=probs[(int)age][i][ij];
3459: }else{ /* mobilav */
3460: for(i=1; i<=nlstate;i++)
3461: prlim[i][i]=mobaverage[(int)age][i][ij];
3462: }
3463: }
3464:
3465: for(j=1; j<= nlstate; j++){
3466: for(h=0; h<=nhstepm; h++){
3467: for(i=1, gp[h][j]=0.;i<=nlstate;i++)
3468: gp[h][j] += prlim[i][i]*p3mat[i][j][h];
3469: }
3470: }
3471: /* This for computing probability of death (h=1 means
3472: computed over hstepm matrices product = hstepm*stepm months)
3473: as a weighted average of prlim.
3474: */
3475: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3476: for(i=1,gpp[j]=0.; i<= nlstate; i++)
3477: gpp[j] += prlim[i][i]*p3mat[i][j][1];
3478: }
3479: /* end probability of death */
3480:
3481: for(i=1; i<=npar; i++) /* Computes gradient x - delta */
3482: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3483: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3484: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3485:
3486: if (popbased==1) {
3487: if(mobilav ==0){
3488: for(i=1; i<=nlstate;i++)
3489: prlim[i][i]=probs[(int)age][i][ij];
3490: }else{ /* mobilav */
3491: for(i=1; i<=nlstate;i++)
3492: prlim[i][i]=mobaverage[(int)age][i][ij];
3493: }
3494: }
3495:
3496: for(j=1; j<= nlstate; j++){ /* Sum of wi * eij = e.j */
3497: for(h=0; h<=nhstepm; h++){
3498: for(i=1, gm[h][j]=0.;i<=nlstate;i++)
3499: gm[h][j] += prlim[i][i]*p3mat[i][j][h];
3500: }
3501: }
3502: /* This for computing probability of death (h=1 means
3503: computed over hstepm matrices product = hstepm*stepm months)
3504: as a weighted average of prlim.
3505: */
3506: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3507: for(i=1,gmp[j]=0.; i<= nlstate; i++)
3508: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3509: }
3510: /* end probability of death */
3511:
3512: for(j=1; j<= nlstate; j++) /* vareij */
3513: for(h=0; h<=nhstepm; h++){
3514: gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
3515: }
3516:
3517: for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
3518: gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
3519: }
3520:
3521: } /* End theta */
3522:
3523: trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
3524:
3525: for(h=0; h<=nhstepm; h++) /* veij */
3526: for(j=1; j<=nlstate;j++)
3527: for(theta=1; theta <=npar; theta++)
3528: trgradg[h][j][theta]=gradg[h][theta][j];
3529:
3530: for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
3531: for(theta=1; theta <=npar; theta++)
3532: trgradgp[j][theta]=gradgp[theta][j];
3533:
3534:
3535: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3536: for(i=1;i<=nlstate;i++)
3537: for(j=1;j<=nlstate;j++)
3538: vareij[i][j][(int)age] =0.;
3539:
3540: for(h=0;h<=nhstepm;h++){
3541: for(k=0;k<=nhstepm;k++){
3542: matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
3543: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
3544: for(i=1;i<=nlstate;i++)
3545: for(j=1;j<=nlstate;j++)
3546: vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
3547: }
3548: }
3549:
3550: /* pptj */
3551: matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
3552: matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
3553: for(j=nlstate+1;j<=nlstate+ndeath;j++)
3554: for(i=nlstate+1;i<=nlstate+ndeath;i++)
3555: varppt[j][i]=doldmp[j][i];
3556: /* end ppptj */
3557: /* x centered again */
3558: hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);
3559: prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
3560:
3561: if (popbased==1) {
3562: if(mobilav ==0){
3563: for(i=1; i<=nlstate;i++)
3564: prlim[i][i]=probs[(int)age][i][ij];
3565: }else{ /* mobilav */
3566: for(i=1; i<=nlstate;i++)
3567: prlim[i][i]=mobaverage[(int)age][i][ij];
3568: }
3569: }
3570:
3571: /* This for computing probability of death (h=1 means
3572: computed over hstepm (estepm) matrices product = hstepm*stepm months)
3573: as a weighted average of prlim.
3574: */
3575: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3576: for(i=1,gmp[j]=0.;i<= nlstate; i++)
3577: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3578: }
3579: /* end probability of death */
3580:
3581: fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
3582: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3583: fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
3584: for(i=1; i<=nlstate;i++){
3585: fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
3586: }
3587: }
3588: fprintf(ficresprobmorprev,"\n");
3589:
3590: fprintf(ficresvij,"%.0f ",age );
3591: for(i=1; i<=nlstate;i++)
3592: for(j=1; j<=nlstate;j++){
3593: fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
3594: }
3595: fprintf(ficresvij,"\n");
3596: free_matrix(gp,0,nhstepm,1,nlstate);
3597: free_matrix(gm,0,nhstepm,1,nlstate);
3598: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
3599: free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
3600: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3601: } /* End age */
3602: free_vector(gpp,nlstate+1,nlstate+ndeath);
3603: free_vector(gmp,nlstate+1,nlstate+ndeath);
3604: free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
3605: free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
3606: fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
3607: /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
3608: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
3609: /* fprintf(ficgp,"\n plot \"%s\" u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
3610: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
3611: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
3612: fprintf(ficgp,"\n plot \"%s\" u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
3613: fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)) t \"95\%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
3614: fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
3615: fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
3616: 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);
3617: /* 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);
3618: */
3619: /* fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
3620: fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
3621:
3622: free_vector(xp,1,npar);
3623: free_matrix(doldm,1,nlstate,1,nlstate);
3624: free_matrix(dnewm,1,nlstate,1,npar);
3625: free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3626: free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
3627: free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3628: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3629: fclose(ficresprobmorprev);
3630: fflush(ficgp);
3631: fflush(fichtm);
3632: } /* end varevsij */
3633:
3634: /************ Variance of prevlim ******************/
3635: 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[])
3636: {
3637: /* Variance of prevalence limit */
3638: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
3639:
3640: double **dnewm,**doldm;
3641: int i, j, nhstepm, hstepm;
3642: double *xp;
3643: double *gp, *gm;
3644: double **gradg, **trgradg;
3645: double age,agelim;
3646: int theta;
3647:
3648: pstamp(ficresvpl);
3649: fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
3650: fprintf(ficresvpl,"# Age");
3651: for(i=1; i<=nlstate;i++)
3652: fprintf(ficresvpl," %1d-%1d",i,i);
3653: fprintf(ficresvpl,"\n");
3654:
3655: xp=vector(1,npar);
3656: dnewm=matrix(1,nlstate,1,npar);
3657: doldm=matrix(1,nlstate,1,nlstate);
3658:
3659: hstepm=1*YEARM; /* Every year of age */
3660: hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
3661: agelim = AGESUP;
3662: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3663: nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3664: if (stepm >= YEARM) hstepm=1;
3665: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
3666: gradg=matrix(1,npar,1,nlstate);
3667: gp=vector(1,nlstate);
3668: gm=vector(1,nlstate);
3669:
3670: for(theta=1; theta <=npar; theta++){
3671: for(i=1; i<=npar; i++){ /* Computes gradient */
3672: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3673: }
3674: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3675: for(i=1;i<=nlstate;i++)
3676: gp[i] = prlim[i][i];
3677:
3678: for(i=1; i<=npar; i++) /* Computes gradient */
3679: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3680: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3681: for(i=1;i<=nlstate;i++)
3682: gm[i] = prlim[i][i];
3683:
3684: for(i=1;i<=nlstate;i++)
3685: gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
3686: } /* End theta */
3687:
3688: trgradg =matrix(1,nlstate,1,npar);
3689:
3690: for(j=1; j<=nlstate;j++)
3691: for(theta=1; theta <=npar; theta++)
3692: trgradg[j][theta]=gradg[theta][j];
3693:
3694: for(i=1;i<=nlstate;i++)
3695: varpl[i][(int)age] =0.;
3696: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
3697: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
3698: for(i=1;i<=nlstate;i++)
3699: varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
3700:
3701: fprintf(ficresvpl,"%.0f ",age );
3702: for(i=1; i<=nlstate;i++)
3703: fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
3704: fprintf(ficresvpl,"\n");
3705: free_vector(gp,1,nlstate);
3706: free_vector(gm,1,nlstate);
3707: free_matrix(gradg,1,npar,1,nlstate);
3708: free_matrix(trgradg,1,nlstate,1,npar);
3709: } /* End age */
3710:
3711: free_vector(xp,1,npar);
3712: free_matrix(doldm,1,nlstate,1,npar);
3713: free_matrix(dnewm,1,nlstate,1,nlstate);
3714:
3715: }
3716:
3717: /************ Variance of one-step probabilities ******************/
3718: 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[])
3719: {
3720: int i, j=0, k1, l1, tj;
3721: int k2, l2, j1, z1;
3722: int k=0, l;
3723: int first=1, first1, first2;
3724: double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
3725: double **dnewm,**doldm;
3726: double *xp;
3727: double *gp, *gm;
3728: double **gradg, **trgradg;
3729: double **mu;
3730: double age, cov[NCOVMAX+1];
3731: double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
3732: int theta;
3733: char fileresprob[FILENAMELENGTH];
3734: char fileresprobcov[FILENAMELENGTH];
3735: char fileresprobcor[FILENAMELENGTH];
3736: double ***varpij;
3737:
3738: strcpy(fileresprob,"prob");
3739: strcat(fileresprob,fileres);
3740: if((ficresprob=fopen(fileresprob,"w"))==NULL) {
3741: printf("Problem with resultfile: %s\n", fileresprob);
3742: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
3743: }
3744: strcpy(fileresprobcov,"probcov");
3745: strcat(fileresprobcov,fileres);
3746: if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
3747: printf("Problem with resultfile: %s\n", fileresprobcov);
3748: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
3749: }
3750: strcpy(fileresprobcor,"probcor");
3751: strcat(fileresprobcor,fileres);
3752: if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
3753: printf("Problem with resultfile: %s\n", fileresprobcor);
3754: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
3755: }
3756: printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3757: fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3758: printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3759: fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3760: printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3761: fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3762: pstamp(ficresprob);
3763: fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
3764: fprintf(ficresprob,"# Age");
3765: pstamp(ficresprobcov);
3766: fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
3767: fprintf(ficresprobcov,"# Age");
3768: pstamp(ficresprobcor);
3769: fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
3770: fprintf(ficresprobcor,"# Age");
3771:
3772:
3773: for(i=1; i<=nlstate;i++)
3774: for(j=1; j<=(nlstate+ndeath);j++){
3775: fprintf(ficresprob," p%1d-%1d (SE)",i,j);
3776: fprintf(ficresprobcov," p%1d-%1d ",i,j);
3777: fprintf(ficresprobcor," p%1d-%1d ",i,j);
3778: }
3779: /* fprintf(ficresprob,"\n");
3780: fprintf(ficresprobcov,"\n");
3781: fprintf(ficresprobcor,"\n");
3782: */
3783: xp=vector(1,npar);
3784: dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3785: doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
3786: mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
3787: varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
3788: first=1;
3789: fprintf(ficgp,"\n# Routine varprob");
3790: fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
3791: fprintf(fichtm,"\n");
3792:
3793: fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
3794: fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
3795: file %s<br>\n",optionfilehtmcov);
3796: fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
3797: and drawn. It helps understanding how is the covariance between two incidences.\
3798: They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
3799: 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. \
3800: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
3801: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
3802: standard deviations wide on each axis. <br>\
3803: Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
3804: and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
3805: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
3806:
3807: cov[1]=1;
3808: /* tj=cptcoveff; */
3809: tj = (int) pow(2,cptcoveff);
3810: if (cptcovn<1) {tj=1;ncodemax[1]=1;}
3811: j1=0;
3812: for(j1=1; j1<=tj;j1++){
3813: /*for(i1=1; i1<=ncodemax[t];i1++){ */
3814: /*j1++;*/
3815: if (cptcovn>0) {
3816: fprintf(ficresprob, "\n#********** Variable ");
3817: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3818: fprintf(ficresprob, "**********\n#\n");
3819: fprintf(ficresprobcov, "\n#********** Variable ");
3820: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3821: fprintf(ficresprobcov, "**********\n#\n");
3822:
3823: fprintf(ficgp, "\n#********** Variable ");
3824: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3825: fprintf(ficgp, "**********\n#\n");
3826:
3827:
3828: fprintf(fichtmcov, "\n<hr size=\"2\" color=\"#EC5E5E\">********** Variable ");
3829: for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3830: fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
3831:
3832: fprintf(ficresprobcor, "\n#********** Variable ");
3833: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3834: fprintf(ficresprobcor, "**********\n#");
3835: }
3836:
3837: gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
3838: trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3839: gp=vector(1,(nlstate)*(nlstate+ndeath));
3840: gm=vector(1,(nlstate)*(nlstate+ndeath));
3841: for (age=bage; age<=fage; age ++){
3842: cov[2]=age;
3843: for (k=1; k<=cptcovn;k++) {
3844: cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
3845: * 1 1 1 1 1
3846: * 2 2 1 1 1
3847: * 3 1 2 1 1
3848: */
3849: /* nbcode[1][1]=0 nbcode[1][2]=1;*/
3850: }
3851: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
3852: for (k=1; k<=cptcovprod;k++)
3853: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
3854:
3855:
3856: for(theta=1; theta <=npar; theta++){
3857: for(i=1; i<=npar; i++)
3858: xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
3859:
3860: pmij(pmmij,cov,ncovmodel,xp,nlstate);
3861:
3862: k=0;
3863: for(i=1; i<= (nlstate); i++){
3864: for(j=1; j<=(nlstate+ndeath);j++){
3865: k=k+1;
3866: gp[k]=pmmij[i][j];
3867: }
3868: }
3869:
3870: for(i=1; i<=npar; i++)
3871: xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
3872:
3873: pmij(pmmij,cov,ncovmodel,xp,nlstate);
3874: k=0;
3875: for(i=1; i<=(nlstate); i++){
3876: for(j=1; j<=(nlstate+ndeath);j++){
3877: k=k+1;
3878: gm[k]=pmmij[i][j];
3879: }
3880: }
3881:
3882: for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
3883: gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];
3884: }
3885:
3886: for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
3887: for(theta=1; theta <=npar; theta++)
3888: trgradg[j][theta]=gradg[theta][j];
3889:
3890: matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
3891: matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
3892:
3893: pmij(pmmij,cov,ncovmodel,x,nlstate);
3894:
3895: k=0;
3896: for(i=1; i<=(nlstate); i++){
3897: for(j=1; j<=(nlstate+ndeath);j++){
3898: k=k+1;
3899: mu[k][(int) age]=pmmij[i][j];
3900: }
3901: }
3902: for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
3903: for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
3904: varpij[i][j][(int)age] = doldm[i][j];
3905:
3906: /*printf("\n%d ",(int)age);
3907: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
3908: printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
3909: fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
3910: }*/
3911:
3912: fprintf(ficresprob,"\n%d ",(int)age);
3913: fprintf(ficresprobcov,"\n%d ",(int)age);
3914: fprintf(ficresprobcor,"\n%d ",(int)age);
3915:
3916: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
3917: fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
3918: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
3919: fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
3920: fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
3921: }
3922: i=0;
3923: for (k=1; k<=(nlstate);k++){
3924: for (l=1; l<=(nlstate+ndeath);l++){
3925: i++;
3926: fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
3927: fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
3928: for (j=1; j<=i;j++){
3929: /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
3930: fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
3931: fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
3932: }
3933: }
3934: }/* end of loop for state */
3935: } /* end of loop for age */
3936: free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
3937: free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
3938: free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
3939: free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
3940:
3941: /* Confidence intervalle of pij */
3942: /*
3943: fprintf(ficgp,"\nunset parametric;unset label");
3944: fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
3945: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
3946: 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);
3947: fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
3948: fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
3949: fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
3950: */
3951:
3952: /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
3953: first1=1;first2=2;
3954: for (k2=1; k2<=(nlstate);k2++){
3955: for (l2=1; l2<=(nlstate+ndeath);l2++){
3956: if(l2==k2) continue;
3957: j=(k2-1)*(nlstate+ndeath)+l2;
3958: for (k1=1; k1<=(nlstate);k1++){
3959: for (l1=1; l1<=(nlstate+ndeath);l1++){
3960: if(l1==k1) continue;
3961: i=(k1-1)*(nlstate+ndeath)+l1;
3962: if(i<=j) continue;
3963: for (age=bage; age<=fage; age ++){
3964: if ((int)age %5==0){
3965: v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
3966: v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
3967: cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
3968: mu1=mu[i][(int) age]/stepm*YEARM ;
3969: mu2=mu[j][(int) age]/stepm*YEARM;
3970: c12=cv12/sqrt(v1*v2);
3971: /* Computing eigen value of matrix of covariance */
3972: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
3973: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
3974: if ((lc2 <0) || (lc1 <0) ){
3975: if(first2==1){
3976: first1=0;
3977: 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);
3978: }
3979: 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);
3980: /* lc1=fabs(lc1); */ /* If we want to have them positive */
3981: /* lc2=fabs(lc2); */
3982: }
3983:
3984: /* Eigen vectors */
3985: v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
3986: /*v21=sqrt(1.-v11*v11); *//* error */
3987: v21=(lc1-v1)/cv12*v11;
3988: v12=-v21;
3989: v22=v11;
3990: tnalp=v21/v11;
3991: if(first1==1){
3992: first1=0;
3993: 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);
3994: }
3995: 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);
3996: /*printf(fignu*/
3997: /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
3998: /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
3999: if(first==1){
4000: first=0;
4001: fprintf(ficgp,"\nset parametric;unset label");
4002: 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);
4003: fprintf(ficgp,"\nset ter png small size 320, 240");
4004: fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
4005: :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
4006: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
4007: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
4008: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4009: fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4010: fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
4011: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4012: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4013: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4014: 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",\
4015: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4016: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4017: }else{
4018: first=0;
4019: fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
4020: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4021: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4022: 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",\
4023: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4024: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4025: }/* if first */
4026: } /* age mod 5 */
4027: } /* end loop age */
4028: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4029: first=1;
4030: } /*l12 */
4031: } /* k12 */
4032: } /*l1 */
4033: }/* k1 */
4034: /* } /* loop covariates */
4035: }
4036: free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
4037: free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
4038: free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4039: free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
4040: free_vector(xp,1,npar);
4041: fclose(ficresprob);
4042: fclose(ficresprobcov);
4043: fclose(ficresprobcor);
4044: fflush(ficgp);
4045: fflush(fichtmcov);
4046: }
4047:
4048:
4049: /******************* Printing html file ***********/
4050: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
4051: int lastpass, int stepm, int weightopt, char model[],\
4052: int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
4053: int popforecast, int estepm ,\
4054: double jprev1, double mprev1,double anprev1, \
4055: double jprev2, double mprev2,double anprev2){
4056: int jj1, k1, i1, cpt;
4057:
4058: fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
4059: <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
4060: </ul>");
4061: fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
4062: - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
4063: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
4064: fprintf(fichtm,"\
4065: - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
4066: stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
4067: fprintf(fichtm,"\
4068: - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
4069: subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
4070: fprintf(fichtm,"\
4071: - (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): \
4072: <a href=\"%s\">%s</a> <br>\n",
4073: estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
4074: fprintf(fichtm,"\
4075: - Population projections by age and states: \
4076: <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
4077:
4078: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
4079:
4080: m=pow(2,cptcoveff);
4081: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4082:
4083: jj1=0;
4084: for(k1=1; k1<=m;k1++){
4085: for(i1=1; i1<=ncodemax[k1];i1++){
4086: jj1++;
4087: if (cptcovn > 0) {
4088: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4089: for (cpt=1; cpt<=cptcoveff;cpt++)
4090: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4091: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4092: }
4093: /* Pij */
4094: 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> \
4095: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
4096: /* Quasi-incidences */
4097: fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
4098: 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> \
4099: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
4100: /* Period (stable) prevalence in each health state */
4101: for(cpt=1; cpt<=nlstate;cpt++){
4102: fprintf(fichtm,"<br>- Convergence to period (stable) prevalence in state %d. Or probability to be in state %d being in state (1 to %d) at different ages. <a href=\"%s%d_%d.png\">%s%d_%d.png</a><br> \
4103: <img src=\"%s%d_%d.png\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
4104: }
4105: for(cpt=1; cpt<=nlstate;cpt++) {
4106: 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> \
4107: <img src=\"%s%d%d.png\">",cpt,nlstate,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
4108: }
4109: } /* end i1 */
4110: }/* End k1 */
4111: fprintf(fichtm,"</ul>");
4112:
4113:
4114: fprintf(fichtm,"\
4115: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
4116: - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
4117:
4118: fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4119: subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
4120: fprintf(fichtm,"\
4121: - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4122: subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
4123:
4124: fprintf(fichtm,"\
4125: - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4126: subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
4127: fprintf(fichtm,"\
4128: - 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): \
4129: <a href=\"%s\">%s</a> <br>\n</li>",
4130: estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
4131: fprintf(fichtm,"\
4132: - (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): \
4133: <a href=\"%s\">%s</a> <br>\n</li>",
4134: estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
4135: fprintf(fichtm,"\
4136: - 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",
4137: estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
4138: fprintf(fichtm,"\
4139: - 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",
4140: estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
4141: fprintf(fichtm,"\
4142: - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
4143: subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
4144:
4145: /* if(popforecast==1) fprintf(fichtm,"\n */
4146: /* - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
4147: /* - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
4148: /* <br>",fileres,fileres,fileres,fileres); */
4149: /* else */
4150: /* 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); */
4151: fflush(fichtm);
4152: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
4153:
4154: m=pow(2,cptcoveff);
4155: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4156:
4157: jj1=0;
4158: for(k1=1; k1<=m;k1++){
4159: for(i1=1; i1<=ncodemax[k1];i1++){
4160: jj1++;
4161: if (cptcovn > 0) {
4162: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4163: for (cpt=1; cpt<=cptcoveff;cpt++)
4164: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4165: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4166: }
4167: for(cpt=1; cpt<=nlstate;cpt++) {
4168: fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
4169: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
4170: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);
4171: }
4172: fprintf(fichtm,"\n<br>- Total life expectancy by age and \
4173: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
4174: true period expectancies (those weighted with period prevalences are also\
4175: drawn in addition to the population based expectancies computed using\
4176: observed and cahotic prevalences: %s%d.png<br>\
4177: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
4178: } /* end i1 */
4179: }/* End k1 */
4180: fprintf(fichtm,"</ul>");
4181: fflush(fichtm);
4182: }
4183:
4184: /******************* Gnuplot file **************/
4185: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4186:
4187: char dirfileres[132],optfileres[132];
4188: int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
4189: int ng=0;
4190: /* if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
4191: /* printf("Problem with file %s",optionfilegnuplot); */
4192: /* fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
4193: /* } */
4194:
4195: /*#ifdef windows */
4196: fprintf(ficgp,"cd \"%s\" \n",pathc);
4197: /*#endif */
4198: m=pow(2,cptcoveff);
4199:
4200: strcpy(dirfileres,optionfilefiname);
4201: strcpy(optfileres,"vpl");
4202: /* 1eme*/
4203: fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
4204: for (cpt=1; cpt<= nlstate ; cpt ++) {
4205: for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
4206: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
4207: fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
4208: fprintf(ficgp,"set xlabel \"Age\" \n\
4209: set ylabel \"Probability\" \n\
4210: set ter png small size 320, 240\n\
4211: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
4212:
4213: for (i=1; i<= nlstate ; i ++) {
4214: if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
4215: else fprintf(ficgp," \%%*lf (\%%*lf)");
4216: }
4217: 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);
4218: for (i=1; i<= nlstate ; i ++) {
4219: if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
4220: else fprintf(ficgp," \%%*lf (\%%*lf)");
4221: }
4222: 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);
4223: for (i=1; i<= nlstate ; i ++) {
4224: if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
4225: else fprintf(ficgp," \%%*lf (\%%*lf)");
4226: }
4227: 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));
4228: }
4229: }
4230: /*2 eme*/
4231: fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
4232: for (k1=1; k1<= m ; k1 ++) {
4233: fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
4234: fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
4235:
4236: for (i=1; i<= nlstate+1 ; i ++) {
4237: k=2*i;
4238: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4239: for (j=1; j<= nlstate+1 ; j ++) {
4240: if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
4241: else fprintf(ficgp," \%%*lf (\%%*lf)");
4242: }
4243: if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
4244: else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
4245: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4246: for (j=1; j<= nlstate+1 ; j ++) {
4247: if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
4248: else fprintf(ficgp," \%%*lf (\%%*lf)");
4249: }
4250: fprintf(ficgp,"\" t\"\" w l lt 0,");
4251: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4252: for (j=1; j<= nlstate+1 ; j ++) {
4253: if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
4254: else fprintf(ficgp," \%%*lf (\%%*lf)");
4255: }
4256: if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
4257: else fprintf(ficgp,"\" t\"\" w l lt 0,");
4258: }
4259: }
4260:
4261: /*3eme*/
4262:
4263: for (k1=1; k1<= m ; k1 ++) {
4264: for (cpt=1; cpt<= nlstate ; cpt ++) {
4265: /* k=2+nlstate*(2*cpt-2); */
4266: k=2+(nlstate+1)*(cpt-1);
4267: fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
4268: fprintf(ficgp,"set ter png small size 320, 240\n\
4269: 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);
4270: /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4271: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4272: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4273: fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4274: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4275: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4276:
4277: */
4278: for (i=1; i< nlstate ; i ++) {
4279: 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);
4280: /* 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);*/
4281:
4282: }
4283: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
4284: }
4285: }
4286:
4287: /* CV preval stable (period) */
4288: for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
4289: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
4290: k=3;
4291: fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
4292: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
4293: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
4294: set ter png small size 320, 240\n\
4295: unset log y\n\
4296: plot [%.f:%.f] ", ageminpar, agemaxpar);
4297: for (i=1; i<= nlstate ; i ++){
4298: if(i==1)
4299: fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
4300: else
4301: fprintf(ficgp,", '' ");
4302: l=(nlstate+ndeath)*(i-1)+1;
4303: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
4304: for (j=1; j<= (nlstate-1) ; j ++)
4305: fprintf(ficgp,"+$%d",k+l+j);
4306: fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
4307: } /* nlstate */
4308: fprintf(ficgp,"\n");
4309: } /* end cpt state*/
4310: } /* end covariate */
4311:
4312: /* proba elementaires */
4313: for(i=1,jk=1; i <=nlstate; i++){
4314: for(k=1; k <=(nlstate+ndeath); k++){
4315: if (k != i) {
4316: for(j=1; j <=ncovmodel; j++){
4317: fprintf(ficgp,"p%d=%f ",jk,p[jk]);
4318: jk++;
4319: fprintf(ficgp,"\n");
4320: }
4321: }
4322: }
4323: }
4324: /*goto avoid;*/
4325: for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
4326: for(jk=1; jk <=m; jk++) {
4327: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);
4328: if (ng==2)
4329: fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
4330: else
4331: fprintf(ficgp,"\nset title \"Probability\"\n");
4332: fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot [%.f:%.f] ",ageminpar,agemaxpar);
4333: i=1;
4334: for(k2=1; k2<=nlstate; k2++) {
4335: k3=i;
4336: for(k=1; k<=(nlstate+ndeath); k++) {
4337: if (k != k2){
4338: if(ng==2)
4339: fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
4340: else
4341: fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
4342: ij=1;/* To be checked else nbcode[0][0] wrong */
4343: for(j=3; j <=ncovmodel; j++) {
4344: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /\* Bug valgrind *\/ */
4345: /* /\*fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);*\/ */
4346: /* ij++; */
4347: /* } */
4348: /* else */
4349: fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4350: }
4351: fprintf(ficgp,")/(1");
4352:
4353: for(k1=1; k1 <=nlstate; k1++){
4354: fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
4355: ij=1;
4356: for(j=3; j <=ncovmodel; j++){
4357: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { */
4358: /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]); */
4359: /* ij++; */
4360: /* } */
4361: /* else */
4362: fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4363: }
4364: fprintf(ficgp,")");
4365: }
4366: fprintf(ficgp,") t \"p%d%d\" ", k2,k);
4367: if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
4368: i=i+ncovmodel;
4369: }
4370: } /* end k */
4371: } /* end k2 */
4372: } /* end jk */
4373: } /* end ng */
4374: /* avoid: */
4375: fflush(ficgp);
4376: } /* end gnuplot */
4377:
4378:
4379: /*************** Moving average **************/
4380: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
4381:
4382: int i, cpt, cptcod;
4383: int modcovmax =1;
4384: int mobilavrange, mob;
4385: double age;
4386:
4387: modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
4388: a covariate has 2 modalities */
4389: if (cptcovn<1) modcovmax=1; /* At least 1 pass */
4390:
4391: if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
4392: if(mobilav==1) mobilavrange=5; /* default */
4393: else mobilavrange=mobilav;
4394: for (age=bage; age<=fage; age++)
4395: for (i=1; i<=nlstate;i++)
4396: for (cptcod=1;cptcod<=modcovmax;cptcod++)
4397: mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
4398: /* We keep the original values on the extreme ages bage, fage and for
4399: fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
4400: we use a 5 terms etc. until the borders are no more concerned.
4401: */
4402: for (mob=3;mob <=mobilavrange;mob=mob+2){
4403: for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
4404: for (i=1; i<=nlstate;i++){
4405: for (cptcod=1;cptcod<=modcovmax;cptcod++){
4406: mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
4407: for (cpt=1;cpt<=(mob-1)/2;cpt++){
4408: mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
4409: mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
4410: }
4411: mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
4412: }
4413: }
4414: }/* end age */
4415: }/* end mob */
4416: }else return -1;
4417: return 0;
4418: }/* End movingaverage */
4419:
4420:
4421: /************** Forecasting ******************/
4422: 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){
4423: /* proj1, year, month, day of starting projection
4424: agemin, agemax range of age
4425: dateprev1 dateprev2 range of dates during which prevalence is computed
4426: anproj2 year of en of projection (same day and month as proj1).
4427: */
4428: int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
4429: double agec; /* generic age */
4430: double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
4431: double *popeffectif,*popcount;
4432: double ***p3mat;
4433: double ***mobaverage;
4434: char fileresf[FILENAMELENGTH];
4435:
4436: agelim=AGESUP;
4437: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4438:
4439: strcpy(fileresf,"f");
4440: strcat(fileresf,fileres);
4441: if((ficresf=fopen(fileresf,"w"))==NULL) {
4442: printf("Problem with forecast resultfile: %s\n", fileresf);
4443: fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
4444: }
4445: printf("Computing forecasting: result on file '%s' \n", fileresf);
4446: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
4447:
4448: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4449:
4450: if (mobilav!=0) {
4451: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4452: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4453: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4454: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4455: }
4456: }
4457:
4458: stepsize=(int) (stepm+YEARM-1)/YEARM;
4459: if (stepm<=12) stepsize=1;
4460: if(estepm < stepm){
4461: printf ("Problem %d lower than %d\n",estepm, stepm);
4462: }
4463: else hstepm=estepm;
4464:
4465: hstepm=hstepm/stepm;
4466: yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp and
4467: fractional in yp1 */
4468: anprojmean=yp;
4469: yp2=modf((yp1*12),&yp);
4470: mprojmean=yp;
4471: yp1=modf((yp2*30.5),&yp);
4472: jprojmean=yp;
4473: if(jprojmean==0) jprojmean=1;
4474: if(mprojmean==0) jprojmean=1;
4475:
4476: i1=cptcoveff;
4477: if (cptcovn < 1){i1=1;}
4478:
4479: fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
4480:
4481: fprintf(ficresf,"#****** Routine prevforecast **\n");
4482:
4483: /* if (h==(int)(YEARM*yearp)){ */
4484: for(cptcov=1, k=0;cptcov<=i1;cptcov++){
4485: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4486: k=k+1;
4487: fprintf(ficresf,"\n#******");
4488: for(j=1;j<=cptcoveff;j++) {
4489: 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]]);
4490: }
4491: fprintf(ficresf,"******\n");
4492: fprintf(ficresf,"# Covariate valuofcovar yearproj age");
4493: for(j=1; j<=nlstate+ndeath;j++){
4494: for(i=1; i<=nlstate;i++)
4495: fprintf(ficresf," p%d%d",i,j);
4496: fprintf(ficresf," p.%d",j);
4497: }
4498: for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
4499: fprintf(ficresf,"\n");
4500: fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);
4501:
4502: for (agec=fage; agec>=(ageminpar-1); agec--){
4503: nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
4504: nhstepm = nhstepm/hstepm;
4505: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4506: oldm=oldms;savm=savms;
4507: hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
4508:
4509: for (h=0; h<=nhstepm; h++){
4510: if (h*hstepm/YEARM*stepm ==yearp) {
4511: fprintf(ficresf,"\n");
4512: for(j=1;j<=cptcoveff;j++)
4513: fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4514: fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
4515: }
4516: for(j=1; j<=nlstate+ndeath;j++) {
4517: ppij=0.;
4518: for(i=1; i<=nlstate;i++) {
4519: if (mobilav==1)
4520: ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
4521: else {
4522: ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
4523: }
4524: if (h*hstepm/YEARM*stepm== yearp) {
4525: fprintf(ficresf," %.3f", p3mat[i][j][h]);
4526: }
4527: } /* end i */
4528: if (h*hstepm/YEARM*stepm==yearp) {
4529: fprintf(ficresf," %.3f", ppij);
4530: }
4531: }/* end j */
4532: } /* end h */
4533: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4534: } /* end agec */
4535: } /* end yearp */
4536: } /* end cptcod */
4537: } /* end cptcov */
4538:
4539: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4540:
4541: fclose(ficresf);
4542: }
4543:
4544: /************** Forecasting *****not tested NB*************/
4545: 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){
4546:
4547: int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
4548: int *popage;
4549: double calagedatem, agelim, kk1, kk2;
4550: double *popeffectif,*popcount;
4551: double ***p3mat,***tabpop,***tabpopprev;
4552: double ***mobaverage;
4553: char filerespop[FILENAMELENGTH];
4554:
4555: tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4556: tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4557: agelim=AGESUP;
4558: calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
4559:
4560: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4561:
4562:
4563: strcpy(filerespop,"pop");
4564: strcat(filerespop,fileres);
4565: if((ficrespop=fopen(filerespop,"w"))==NULL) {
4566: printf("Problem with forecast resultfile: %s\n", filerespop);
4567: fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
4568: }
4569: printf("Computing forecasting: result on file '%s' \n", filerespop);
4570: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
4571:
4572: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4573:
4574: if (mobilav!=0) {
4575: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4576: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4577: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4578: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4579: }
4580: }
4581:
4582: stepsize=(int) (stepm+YEARM-1)/YEARM;
4583: if (stepm<=12) stepsize=1;
4584:
4585: agelim=AGESUP;
4586:
4587: hstepm=1;
4588: hstepm=hstepm/stepm;
4589:
4590: if (popforecast==1) {
4591: if((ficpop=fopen(popfile,"r"))==NULL) {
4592: printf("Problem with population file : %s\n",popfile);exit(0);
4593: fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
4594: }
4595: popage=ivector(0,AGESUP);
4596: popeffectif=vector(0,AGESUP);
4597: popcount=vector(0,AGESUP);
4598:
4599: i=1;
4600: while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
4601:
4602: imx=i;
4603: for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
4604: }
4605:
4606: for(cptcov=1,k=0;cptcov<=i2;cptcov++){
4607: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4608: k=k+1;
4609: fprintf(ficrespop,"\n#******");
4610: for(j=1;j<=cptcoveff;j++) {
4611: fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4612: }
4613: fprintf(ficrespop,"******\n");
4614: fprintf(ficrespop,"# Age");
4615: for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
4616: if (popforecast==1) fprintf(ficrespop," [Population]");
4617:
4618: for (cpt=0; cpt<=0;cpt++) {
4619: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4620:
4621: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4622: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4623: nhstepm = nhstepm/hstepm;
4624:
4625: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4626: oldm=oldms;savm=savms;
4627: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4628:
4629: for (h=0; h<=nhstepm; h++){
4630: if (h==(int) (calagedatem+YEARM*cpt)) {
4631: fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4632: }
4633: for(j=1; j<=nlstate+ndeath;j++) {
4634: kk1=0.;kk2=0;
4635: for(i=1; i<=nlstate;i++) {
4636: if (mobilav==1)
4637: kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
4638: else {
4639: kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
4640: }
4641: }
4642: if (h==(int)(calagedatem+12*cpt)){
4643: tabpop[(int)(agedeb)][j][cptcod]=kk1;
4644: /*fprintf(ficrespop," %.3f", kk1);
4645: if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
4646: }
4647: }
4648: for(i=1; i<=nlstate;i++){
4649: kk1=0.;
4650: for(j=1; j<=nlstate;j++){
4651: kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
4652: }
4653: tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
4654: }
4655:
4656: if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
4657: fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
4658: }
4659: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4660: }
4661: }
4662:
4663: /******/
4664:
4665: for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
4666: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4667: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4668: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4669: nhstepm = nhstepm/hstepm;
4670:
4671: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4672: oldm=oldms;savm=savms;
4673: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4674: for (h=0; h<=nhstepm; h++){
4675: if (h==(int) (calagedatem+YEARM*cpt)) {
4676: fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4677: }
4678: for(j=1; j<=nlstate+ndeath;j++) {
4679: kk1=0.;kk2=0;
4680: for(i=1; i<=nlstate;i++) {
4681: kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];
4682: }
4683: if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);
4684: }
4685: }
4686: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4687: }
4688: }
4689: }
4690: }
4691:
4692: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4693:
4694: if (popforecast==1) {
4695: free_ivector(popage,0,AGESUP);
4696: free_vector(popeffectif,0,AGESUP);
4697: free_vector(popcount,0,AGESUP);
4698: }
4699: free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4700: free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4701: fclose(ficrespop);
4702: } /* End of popforecast */
4703:
4704: int fileappend(FILE *fichier, char *optionfich)
4705: {
4706: if((fichier=fopen(optionfich,"a"))==NULL) {
4707: printf("Problem with file: %s\n", optionfich);
4708: fprintf(ficlog,"Problem with file: %s\n", optionfich);
4709: return (0);
4710: }
4711: fflush(fichier);
4712: return (1);
4713: }
4714:
4715:
4716: /**************** function prwizard **********************/
4717: void prwizard(int ncovmodel, int nlstate, int ndeath, char model[], FILE *ficparo)
4718: {
4719:
4720: /* Wizard to print covariance matrix template */
4721:
4722: char ca[32], cb[32];
4723: int i,j, k, li, lj, lk, ll, jj, npar, itimes;
4724: int numlinepar;
4725:
4726: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4727: fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4728: for(i=1; i <=nlstate; i++){
4729: jj=0;
4730: for(j=1; j <=nlstate+ndeath; j++){
4731: if(j==i) continue;
4732: jj++;
4733: /*ca[0]= k+'a'-1;ca[1]='\0';*/
4734: printf("%1d%1d",i,j);
4735: fprintf(ficparo,"%1d%1d",i,j);
4736: for(k=1; k<=ncovmodel;k++){
4737: /* printf(" %lf",param[i][j][k]); */
4738: /* fprintf(ficparo," %lf",param[i][j][k]); */
4739: printf(" 0.");
4740: fprintf(ficparo," 0.");
4741: }
4742: printf("\n");
4743: fprintf(ficparo,"\n");
4744: }
4745: }
4746: printf("# Scales (for hessian or gradient estimation)\n");
4747: fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
4748: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
4749: for(i=1; i <=nlstate; i++){
4750: jj=0;
4751: for(j=1; j <=nlstate+ndeath; j++){
4752: if(j==i) continue;
4753: jj++;
4754: fprintf(ficparo,"%1d%1d",i,j);
4755: printf("%1d%1d",i,j);
4756: fflush(stdout);
4757: for(k=1; k<=ncovmodel;k++){
4758: /* printf(" %le",delti3[i][j][k]); */
4759: /* fprintf(ficparo," %le",delti3[i][j][k]); */
4760: printf(" 0.");
4761: fprintf(ficparo," 0.");
4762: }
4763: numlinepar++;
4764: printf("\n");
4765: fprintf(ficparo,"\n");
4766: }
4767: }
4768: printf("# Covariance matrix\n");
4769: /* # 121 Var(a12)\n\ */
4770: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4771: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
4772: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
4773: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
4774: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
4775: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
4776: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4777: fflush(stdout);
4778: fprintf(ficparo,"# Covariance matrix\n");
4779: /* # 121 Var(a12)\n\ */
4780: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4781: /* # ...\n\ */
4782: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4783:
4784: for(itimes=1;itimes<=2;itimes++){
4785: jj=0;
4786: for(i=1; i <=nlstate; i++){
4787: for(j=1; j <=nlstate+ndeath; j++){
4788: if(j==i) continue;
4789: for(k=1; k<=ncovmodel;k++){
4790: jj++;
4791: ca[0]= k+'a'-1;ca[1]='\0';
4792: if(itimes==1){
4793: printf("#%1d%1d%d",i,j,k);
4794: fprintf(ficparo,"#%1d%1d%d",i,j,k);
4795: }else{
4796: printf("%1d%1d%d",i,j,k);
4797: fprintf(ficparo,"%1d%1d%d",i,j,k);
4798: /* printf(" %.5le",matcov[i][j]); */
4799: }
4800: ll=0;
4801: for(li=1;li <=nlstate; li++){
4802: for(lj=1;lj <=nlstate+ndeath; lj++){
4803: if(lj==li) continue;
4804: for(lk=1;lk<=ncovmodel;lk++){
4805: ll++;
4806: if(ll<=jj){
4807: cb[0]= lk +'a'-1;cb[1]='\0';
4808: if(ll<jj){
4809: if(itimes==1){
4810: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4811: fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4812: }else{
4813: printf(" 0.");
4814: fprintf(ficparo," 0.");
4815: }
4816: }else{
4817: if(itimes==1){
4818: printf(" Var(%s%1d%1d)",ca,i,j);
4819: fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
4820: }else{
4821: printf(" 0.");
4822: fprintf(ficparo," 0.");
4823: }
4824: }
4825: }
4826: } /* end lk */
4827: } /* end lj */
4828: } /* end li */
4829: printf("\n");
4830: fprintf(ficparo,"\n");
4831: numlinepar++;
4832: } /* end k*/
4833: } /*end j */
4834: } /* end i */
4835: } /* end itimes */
4836:
4837: } /* end of prwizard */
4838: /******************* Gompertz Likelihood ******************************/
4839: double gompertz(double x[])
4840: {
4841: double A,B,L=0.0,sump=0.,num=0.;
4842: int i,n=0; /* n is the size of the sample */
4843:
4844: for (i=0;i<=imx-1 ; i++) {
4845: sump=sump+weight[i];
4846: /* sump=sump+1;*/
4847: num=num+1;
4848: }
4849:
4850:
4851: /* for (i=0; i<=imx; i++)
4852: 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]);*/
4853:
4854: for (i=1;i<=imx ; i++)
4855: {
4856: if (cens[i] == 1 && wav[i]>1)
4857: A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
4858:
4859: if (cens[i] == 0 && wav[i]>1)
4860: A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
4861: +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);
4862:
4863: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
4864: if (wav[i] > 1 ) { /* ??? */
4865: L=L+A*weight[i];
4866: /* 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]);*/
4867: }
4868: }
4869:
4870: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
4871:
4872: return -2*L*num/sump;
4873: }
4874:
4875: #ifdef GSL
4876: /******************* Gompertz_f Likelihood ******************************/
4877: double gompertz_f(const gsl_vector *v, void *params)
4878: {
4879: double A,B,LL=0.0,sump=0.,num=0.;
4880: double *x= (double *) v->data;
4881: int i,n=0; /* n is the size of the sample */
4882:
4883: for (i=0;i<=imx-1 ; i++) {
4884: sump=sump+weight[i];
4885: /* sump=sump+1;*/
4886: num=num+1;
4887: }
4888:
4889:
4890: /* for (i=0; i<=imx; i++)
4891: 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]);*/
4892: printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
4893: for (i=1;i<=imx ; i++)
4894: {
4895: if (cens[i] == 1 && wav[i]>1)
4896: A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
4897:
4898: if (cens[i] == 0 && wav[i]>1)
4899: A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
4900: +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);
4901:
4902: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
4903: if (wav[i] > 1 ) { /* ??? */
4904: LL=LL+A*weight[i];
4905: /* 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]);*/
4906: }
4907: }
4908:
4909: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
4910: printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
4911:
4912: return -2*LL*num/sump;
4913: }
4914: #endif
4915:
4916: /******************* Printing html file ***********/
4917: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
4918: int lastpass, int stepm, int weightopt, char model[],\
4919: int imx, double p[],double **matcov,double agemortsup){
4920: int i,k;
4921:
4922: fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
4923: fprintf(fichtm," mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
4924: for (i=1;i<=2;i++)
4925: 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]));
4926: fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
4927: fprintf(fichtm,"</ul>");
4928:
4929: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
4930:
4931: 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>");
4932:
4933: for (k=agegomp;k<(agemortsup-2);k++)
4934: 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]);
4935:
4936:
4937: fflush(fichtm);
4938: }
4939:
4940: /******************* Gnuplot file **************/
4941: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4942:
4943: char dirfileres[132],optfileres[132];
4944:
4945: int ng;
4946:
4947:
4948: /*#ifdef windows */
4949: fprintf(ficgp,"cd \"%s\" \n",pathc);
4950: /*#endif */
4951:
4952:
4953: strcpy(dirfileres,optionfilefiname);
4954: strcpy(optfileres,"vpl");
4955: fprintf(ficgp,"set out \"graphmort.png\"\n ");
4956: fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
4957: fprintf(ficgp, "set ter png small size 320, 240\n set log y\n");
4958: /* fprintf(ficgp, "set size 0.65,0.65\n"); */
4959: fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
4960:
4961: }
4962:
4963: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
4964: {
4965:
4966: /*-------- data file ----------*/
4967: FILE *fic;
4968: char dummy[]=" ";
4969: int i=0, j=0, n=0;
4970: int linei, month, year,iout;
4971: char line[MAXLINE], linetmp[MAXLINE];
4972: char stra[MAXLINE], strb[MAXLINE];
4973: char *stratrunc;
4974: int lstra;
4975:
4976:
4977: if((fic=fopen(datafile,"r"))==NULL) {
4978: printf("Problem while opening datafile: %s\n", datafile);return 1;
4979: fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
4980: }
4981:
4982: i=1;
4983: linei=0;
4984: while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
4985: linei=linei+1;
4986: for(j=strlen(line); j>=0;j--){ /* Untabifies line */
4987: if(line[j] == '\t')
4988: line[j] = ' ';
4989: }
4990: for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
4991: ;
4992: };
4993: line[j+1]=0; /* Trims blanks at end of line */
4994: if(line[0]=='#'){
4995: fprintf(ficlog,"Comment line\n%s\n",line);
4996: printf("Comment line\n%s\n",line);
4997: continue;
4998: }
4999: trimbb(linetmp,line); /* Trims multiple blanks in line */
5000: strcpy(line, linetmp);
5001:
5002:
5003: for (j=maxwav;j>=1;j--){
5004: cutv(stra, strb, line, ' ');
5005: if(strb[0]=='.') { /* Missing status */
5006: lval=-1;
5007: }else{
5008: errno=0;
5009: lval=strtol(strb,&endptr,10);
5010: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
5011: if( strb[0]=='\0' || (*endptr != '\0')){
5012: 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);
5013: 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);
5014: return 1;
5015: }
5016: }
5017: s[j][i]=lval;
5018:
5019: strcpy(line,stra);
5020: cutv(stra, strb,line,' ');
5021: if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
5022: }
5023: else if(iout=sscanf(strb,"%s.",dummy) != 0){
5024: month=99;
5025: year=9999;
5026: }else{
5027: 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);
5028: 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);
5029: return 1;
5030: }
5031: anint[j][i]= (double) year;
5032: mint[j][i]= (double)month;
5033: strcpy(line,stra);
5034: } /* ENd Waves */
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 death (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 death (mm/yyyy or .). Exiting.\n",strb, linei,i,line);fflush(ficlog);
5045: return 1;
5046: }
5047: andc[i]=(double) year;
5048: moisdc[i]=(double) month;
5049: strcpy(line,stra);
5050:
5051: cutv(stra, strb,line,' ');
5052: if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
5053: }
5054: else if(iout=sscanf(strb,"%s.", dummy) != 0){
5055: month=99;
5056: year=9999;
5057: }else{
5058: 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);
5059: 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);
5060: return 1;
5061: }
5062: if (year==9999) {
5063: 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);
5064: 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);
5065: return 1;
5066:
5067: }
5068: annais[i]=(double)(year);
5069: moisnais[i]=(double)(month);
5070: strcpy(line,stra);
5071:
5072: cutv(stra, strb,line,' ');
5073: errno=0;
5074: dval=strtod(strb,&endptr);
5075: if( strb[0]=='\0' || (*endptr != '\0')){
5076: printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight. Exiting.\n",dval, i,line,linei);
5077: 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);
5078: fflush(ficlog);
5079: return 1;
5080: }
5081: weight[i]=dval;
5082: strcpy(line,stra);
5083:
5084: for (j=ncovcol;j>=1;j--){
5085: cutv(stra, strb,line,' ');
5086: if(strb[0]=='.') { /* Missing status */
5087: lval=-1;
5088: }else{
5089: errno=0;
5090: lval=strtol(strb,&endptr,10);
5091: if( strb[0]=='\0' || (*endptr != '\0')){
5092: 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);
5093: 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);
5094: return 1;
5095: }
5096: }
5097: if(lval <-1 || lval >1){
5098: printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
5099: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5100: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5101: For example, for multinomial values like 1, 2 and 3,\n \
5102: build V1=0 V2=0 for the reference value (1),\n \
5103: V1=1 V2=0 for (2) \n \
5104: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5105: output of IMaCh is often meaningless.\n \
5106: Exiting.\n",lval,linei, i,line,j);
5107: fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
5108: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5109: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5110: For example, for multinomial values like 1, 2 and 3,\n \
5111: build V1=0 V2=0 for the reference value (1),\n \
5112: V1=1 V2=0 for (2) \n \
5113: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5114: output of IMaCh is often meaningless.\n \
5115: Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
5116: return 1;
5117: }
5118: covar[j][i]=(double)(lval);
5119: strcpy(line,stra);
5120: }
5121: lstra=strlen(stra);
5122:
5123: if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
5124: stratrunc = &(stra[lstra-9]);
5125: num[i]=atol(stratrunc);
5126: }
5127: else
5128: num[i]=atol(stra);
5129: /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
5130: 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;}*/
5131:
5132: i=i+1;
5133: } /* End loop reading data */
5134:
5135: *imax=i-1; /* Number of individuals */
5136: fclose(fic);
5137:
5138: return (0);
5139: /* endread: */
5140: printf("Exiting readdata: ");
5141: fclose(fic);
5142: return (1);
5143:
5144:
5145:
5146: }
5147: void removespace(char *str) {
5148: char *p1 = str, *p2 = str;
5149: do
5150: while (*p2 == ' ')
5151: p2++;
5152: while (*p1++ = *p2++);
5153: }
5154:
5155: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
5156: * Model V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age
5157: * - cptcovt total number of covariates of the model nbocc(+)+1 = 8
5158: * - cptcovn or number of covariates k of the models excluding age*products =6
5159: * - cptcovage number of covariates with age*products =2
5160: * - cptcovs number of simple covariates
5161: * - 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
5162: * which is a new column after the 9 (ncovcol) variables.
5163: * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
5164: * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
5165: * Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
5166: * - Tvard[k] p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
5167: */
5168: {
5169: int i, j, k, ks;
5170: int j1, k1, k2;
5171: char modelsav[80];
5172: char stra[80], strb[80], strc[80], strd[80],stre[80];
5173:
5174: /*removespace(model);*/
5175: if (strlen(model) >1){ /* If there is at least 1 covariate */
5176: j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
5177: j=nbocc(model,'+'); /**< j=Number of '+' */
5178: j1=nbocc(model,'*'); /**< j1=Number of '*' */
5179: cptcovs=j+1-j1; /**< Number of simple covariates V1+V2*age+V3 +V3*V4=> V1 + V3 =2 */
5180: cptcovt= j+1; /* Number of total covariates in the model V1 + V2*age+ V3 + V3*V4=> 4*/
5181: /* including age products which are counted in cptcovage.
5182: /* but the covariates which are products must be treated separately: ncovn=4- 2=2 (V1+V3). */
5183: cptcovprod=j1; /**< Number of products V1*V2 +v3*age = 2 */
5184: cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1 */
5185: strcpy(modelsav,model);
5186: if (strstr(model,"AGE") !=0){
5187: printf("Error. AGE must be in lower case 'age' model=%s ",model);
5188: fprintf(ficlog,"Error. AGE must be in lower case model=%s ",model);fflush(ficlog);
5189: return 1;
5190: }
5191: if (strstr(model,"v") !=0){
5192: printf("Error. 'v' must be in upper case 'V' model=%s ",model);
5193: fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
5194: return 1;
5195: }
5196:
5197: /* Design
5198: * V1 V2 V3 V4 V5 V6 V7 V8 V9 Weight
5199: * < ncovcol=8 >
5200: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
5201: * k= 1 2 3 4 5 6 7 8
5202: * cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
5203: * covar[k,i], value of kth covariate if not including age for individual i:
5204: * covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
5205: * Tvar[k] # of the kth covariate: Tvar[1]=2 Tvar[4]=3 Tvar[8]=8
5206: * if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and
5207: * Tage[++cptcovage]=k
5208: * if products, new covar are created after ncovcol with k1
5209: * Tvar[k]=ncovcol+k1; # of the kth covariate product: Tvar[5]=ncovcol+1=10 Tvar[6]=ncovcol+1=11
5210: * Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
5211: * 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
5212: * Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
5213: * Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
5214: * V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
5215: * < ncovcol=8 >
5216: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 d1 d1 d2 d2
5217: * k= 1 2 3 4 5 6 7 8 9 10 11 12
5218: * Tvar[k]= 2 1 3 3 10 11 8 8 5 6 7 8
5219: * p Tvar[1]@12={2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5220: * p Tprod[1]@2={ 6, 5}
5221: *p Tvard[1][1]@4= {7, 8, 5, 6}
5222: * covar[k][i]= V2 V1 ? V3 V5*V6? V7*V8? ? V8
5223: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
5224: *How to reorganize?
5225: * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
5226: * Tvars {2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5227: * {2, 1, 4, 8, 5, 6, 3, 7}
5228: * Struct []
5229: */
5230:
5231: /* This loop fills the array Tvar from the string 'model'.*/
5232: /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
5233: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 */
5234: /* k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
5235: /* k=3 V4 Tvar[k=3]= 4 (from V4) */
5236: /* k=2 V1 Tvar[k=2]= 1 (from V1) */
5237: /* k=1 Tvar[1]=2 (from V2) */
5238: /* k=5 Tvar[5] */
5239: /* for (k=1; k<=cptcovn;k++) { */
5240: /* cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
5241: /* } */
5242: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
5243: /*
5244: * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
5245: for(k=cptcovt; k>=1;k--) /**< Number of covariates */
5246: Tvar[k]=0;
5247: cptcovage=0;
5248: for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
5249: cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+'
5250: modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */
5251: if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
5252: /* printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
5253: /*scanf("%d",i);*/
5254: if (strchr(strb,'*')) { /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
5255: cutl(strc,strd,strb,'*'); /**< strd*strc Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
5256: if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
5257: /* covar is not filled and then is empty */
5258: cptcovprod--;
5259: cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
5260: Tvar[k]=atoi(stre); /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2 */
5261: cptcovage++; /* Sums the number of covariates which include age as a product */
5262: Tage[cptcovage]=k; /* Tage[1] = 4 */
5263: /*printf("stre=%s ", stre);*/
5264: } else if (strcmp(strd,"age")==0) { /* or age*Vn */
5265: cptcovprod--;
5266: cutl(stre,strb,strc,'V');
5267: Tvar[k]=atoi(stre);
5268: cptcovage++;
5269: Tage[cptcovage]=k;
5270: } else { /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2 strb=V3*V2*/
5271: /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
5272: cptcovn++;
5273: cptcovprodnoage++;k1++;
5274: cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
5275: Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
5276: because this model-covariate is a construction we invent a new column
5277: ncovcol + k1
5278: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
5279: Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
5280: cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
5281: Tprod[k1]=k; /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 */
5282: Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
5283: Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
5284: k2=k2+2;
5285: Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
5286: Tvar[cptcovt+k2+1]=Tvard[k1][2]; /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
5287: for (i=1; i<=lastobs;i++){
5288: /* Computes the new covariate which is a product of
5289: covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
5290: covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
5291: }
5292: } /* End age is not in the model */
5293: } /* End if model includes a product */
5294: else { /* no more sum */
5295: /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
5296: /* scanf("%d",i);*/
5297: cutl(strd,strc,strb,'V');
5298: ks++; /**< Number of simple covariates */
5299: cptcovn++;
5300: Tvar[k]=atoi(strd);
5301: }
5302: strcpy(modelsav,stra); /* modelsav=V2+V1+V4 stra=V2+V1+V4 */
5303: /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
5304: scanf("%d",i);*/
5305: } /* end of loop + */
5306: } /* end model */
5307:
5308: /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
5309: If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
5310:
5311: /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
5312: printf("cptcovprod=%d ", cptcovprod);
5313: fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
5314:
5315: scanf("%d ",i);*/
5316:
5317:
5318: return (0); /* with covar[new additional covariate if product] and Tage if age */
5319: /*endread:*/
5320: printf("Exiting decodemodel: ");
5321: return (1);
5322: }
5323:
5324: calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
5325: {
5326: int i, m;
5327:
5328: for (i=1; i<=imx; i++) {
5329: for(m=2; (m<= maxwav); m++) {
5330: if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
5331: anint[m][i]=9999;
5332: s[m][i]=-1;
5333: }
5334: if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
5335: *nberr++;
5336: 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);
5337: 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);
5338: s[m][i]=-1;
5339: }
5340: if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
5341: *nberr++;
5342: 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]);
5343: 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]);
5344: s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
5345: }
5346: }
5347: }
5348:
5349: for (i=1; i<=imx; i++) {
5350: agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
5351: for(m=firstpass; (m<= lastpass); m++){
5352: if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
5353: if (s[m][i] >= nlstate+1) {
5354: if(agedc[i]>0)
5355: if((int)moisdc[i]!=99 && (int)andc[i]!=9999)
5356: agev[m][i]=agedc[i];
5357: /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
5358: else {
5359: if ((int)andc[i]!=9999){
5360: nbwarn++;
5361: printf("Warning negative age at death: %ld line:%d\n",num[i],i);
5362: fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
5363: agev[m][i]=-1;
5364: }
5365: }
5366: }
5367: else if(s[m][i] !=9){ /* Standard case, age in fractional
5368: years but with the precision of a month */
5369: agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
5370: if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
5371: agev[m][i]=1;
5372: else if(agev[m][i] < *agemin){
5373: *agemin=agev[m][i];
5374: printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
5375: }
5376: else if(agev[m][i] >*agemax){
5377: *agemax=agev[m][i];
5378: /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
5379: }
5380: /*agev[m][i]=anint[m][i]-annais[i];*/
5381: /* agev[m][i] = age[i]+2*m;*/
5382: }
5383: else { /* =9 */
5384: agev[m][i]=1;
5385: s[m][i]=-1;
5386: }
5387: }
5388: else /*= 0 Unknown */
5389: agev[m][i]=1;
5390: }
5391:
5392: }
5393: for (i=1; i<=imx; i++) {
5394: for(m=firstpass; (m<=lastpass); m++){
5395: if (s[m][i] > (nlstate+ndeath)) {
5396: *nberr++;
5397: 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);
5398: 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);
5399: return 1;
5400: }
5401: }
5402: }
5403:
5404: /*for (i=1; i<=imx; i++){
5405: for (m=firstpass; (m<lastpass); m++){
5406: printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
5407: }
5408:
5409: }*/
5410:
5411:
5412: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
5413: fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
5414:
5415: return (0);
5416: /* endread:*/
5417: printf("Exiting calandcheckages: ");
5418: return (1);
5419: }
5420:
5421:
5422: /***********************************************/
5423: /**************** Main Program *****************/
5424: /***********************************************/
5425:
5426: int main(int argc, char *argv[])
5427: {
5428: #ifdef GSL
5429: const gsl_multimin_fminimizer_type *T;
5430: size_t iteri = 0, it;
5431: int rval = GSL_CONTINUE;
5432: int status = GSL_SUCCESS;
5433: double ssval;
5434: #endif
5435: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
5436: int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
5437:
5438: int jj, ll, li, lj, lk;
5439: int numlinepar=0; /* Current linenumber of parameter file */
5440: int itimes;
5441: int NDIM=2;
5442: int vpopbased=0;
5443:
5444: char ca[32], cb[32];
5445: /* FILE *fichtm; *//* Html File */
5446: /* FILE *ficgp;*/ /*Gnuplot File */
5447: struct stat info;
5448: double agedeb;
5449: double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
5450:
5451: double fret;
5452: double dum; /* Dummy variable */
5453: double ***p3mat;
5454: double ***mobaverage;
5455:
5456: char line[MAXLINE];
5457: char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
5458: char pathr[MAXLINE], pathimach[MAXLINE];
5459: char *tok, *val; /* pathtot */
5460: int firstobs=1, lastobs=10;
5461: int c, h , cpt;
5462: int jl;
5463: int i1, j1, jk, stepsize;
5464: int *tab;
5465: int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
5466: int mobilav=0,popforecast=0;
5467: int hstepm, nhstepm;
5468: int agemortsup;
5469: float sumlpop=0.;
5470: double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
5471: double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
5472:
5473: double bage=0, fage=110, age, agelim, agebase;
5474: double ftolpl=FTOL;
5475: double **prlim;
5476: double ***param; /* Matrix of parameters */
5477: double *p;
5478: double **matcov; /* Matrix of covariance */
5479: double ***delti3; /* Scale */
5480: double *delti; /* Scale */
5481: double ***eij, ***vareij;
5482: double **varpl; /* Variances of prevalence limits by age */
5483: double *epj, vepp;
5484:
5485: double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
5486: double **ximort;
5487: char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
5488: int *dcwave;
5489:
5490: char z[1]="c";
5491:
5492: /*char *strt;*/
5493: char strtend[80];
5494:
5495:
5496: /* setlocale (LC_ALL, ""); */
5497: /* bindtextdomain (PACKAGE, LOCALEDIR); */
5498: /* textdomain (PACKAGE); */
5499: /* setlocale (LC_CTYPE, ""); */
5500: /* setlocale (LC_MESSAGES, ""); */
5501:
5502: /* gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
5503: rstart_time = time(NULL);
5504: /* (void) gettimeofday(&start_time,&tzp);*/
5505: start_time = *localtime(&rstart_time);
5506: curr_time=start_time;
5507: /*tml = *localtime(&start_time.tm_sec);*/
5508: /* strcpy(strstart,asctime(&tml)); */
5509: strcpy(strstart,asctime(&start_time));
5510:
5511: /* printf("Localtime (at start)=%s",strstart); */
5512: /* tp.tm_sec = tp.tm_sec +86400; */
5513: /* tm = *localtime(&start_time.tm_sec); */
5514: /* tmg.tm_year=tmg.tm_year +dsign*dyear; */
5515: /* tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
5516: /* tmg.tm_hour=tmg.tm_hour + 1; */
5517: /* tp.tm_sec = mktime(&tmg); */
5518: /* strt=asctime(&tmg); */
5519: /* printf("Time(after) =%s",strstart); */
5520: /* (void) time (&time_value);
5521: * printf("time=%d,t-=%d\n",time_value,time_value-86400);
5522: * tm = *localtime(&time_value);
5523: * strstart=asctime(&tm);
5524: * printf("tim_value=%d,asctime=%s\n",time_value,strstart);
5525: */
5526:
5527: nberr=0; /* Number of errors and warnings */
5528: nbwarn=0;
5529: getcwd(pathcd, size);
5530:
5531: printf("\n%s\n%s",version,fullversion);
5532: if(argc <=1){
5533: printf("\nEnter the parameter file name: ");
5534: fgets(pathr,FILENAMELENGTH,stdin);
5535: i=strlen(pathr);
5536: if(pathr[i-1]=='\n')
5537: pathr[i-1]='\0';
5538: i=strlen(pathr);
5539: if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
5540: pathr[i-1]='\0';
5541: for (tok = pathr; tok != NULL; ){
5542: printf("Pathr |%s|\n",pathr);
5543: while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
5544: printf("val= |%s| pathr=%s\n",val,pathr);
5545: strcpy (pathtot, val);
5546: if(pathr[0] == '\0') break; /* Dirty */
5547: }
5548: }
5549: else{
5550: strcpy(pathtot,argv[1]);
5551: }
5552: /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
5553: /*cygwin_split_path(pathtot,path,optionfile);
5554: printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
5555: /* cutv(path,optionfile,pathtot,'\\');*/
5556:
5557: /* Split argv[0], imach program to get pathimach */
5558: printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
5559: split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
5560: printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
5561: /* strcpy(pathimach,argv[0]); */
5562: /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
5563: split(pathtot,path,optionfile,optionfilext,optionfilefiname);
5564: printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
5565: chdir(path); /* Can be a relative path */
5566: if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
5567: printf("Current directory %s!\n",pathcd);
5568: strcpy(command,"mkdir ");
5569: strcat(command,optionfilefiname);
5570: if((outcmd=system(command)) != 0){
5571: printf("Problem creating directory or it already exists %s%s, err=%d\n",path,optionfilefiname,outcmd);
5572: /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
5573: /* fclose(ficlog); */
5574: /* exit(1); */
5575: }
5576: /* if((imk=mkdir(optionfilefiname))<0){ */
5577: /* perror("mkdir"); */
5578: /* } */
5579:
5580: /*-------- arguments in the command line --------*/
5581:
5582: /* Log file */
5583: strcat(filelog, optionfilefiname);
5584: strcat(filelog,".log"); /* */
5585: if((ficlog=fopen(filelog,"w"))==NULL) {
5586: printf("Problem with logfile %s\n",filelog);
5587: goto end;
5588: }
5589: fprintf(ficlog,"Log filename:%s\n",filelog);
5590: fprintf(ficlog,"\n%s\n%s",version,fullversion);
5591: fprintf(ficlog,"\nEnter the parameter file name: \n");
5592: fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
5593: path=%s \n\
5594: optionfile=%s\n\
5595: optionfilext=%s\n\
5596: optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
5597:
5598: printf("Local time (at start):%s",strstart);
5599: fprintf(ficlog,"Local time (at start): %s",strstart);
5600: fflush(ficlog);
5601: /* (void) gettimeofday(&curr_time,&tzp); */
5602: /* printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
5603:
5604: /* */
5605: strcpy(fileres,"r");
5606: strcat(fileres, optionfilefiname);
5607: strcat(fileres,".txt"); /* Other files have txt extension */
5608:
5609: /*---------arguments file --------*/
5610:
5611: if((ficpar=fopen(optionfile,"r"))==NULL) {
5612: printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
5613: fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
5614: fflush(ficlog);
5615: /* goto end; */
5616: exit(70);
5617: }
5618:
5619:
5620:
5621: strcpy(filereso,"o");
5622: strcat(filereso,fileres);
5623: if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
5624: printf("Problem with Output resultfile: %s\n", filereso);
5625: fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
5626: fflush(ficlog);
5627: goto end;
5628: }
5629:
5630: /* Reads comments: lines beginning with '#' */
5631: numlinepar=0;
5632: while((c=getc(ficpar))=='#' && c!= EOF){
5633: ungetc(c,ficpar);
5634: fgets(line, MAXLINE, ficpar);
5635: numlinepar++;
5636: fputs(line,stdout);
5637: fputs(line,ficparo);
5638: fputs(line,ficlog);
5639: }
5640: ungetc(c,ficpar);
5641:
5642: 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);
5643: numlinepar++;
5644: 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);
5645: 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);
5646: 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);
5647: fflush(ficlog);
5648: while((c=getc(ficpar))=='#' && c!= EOF){
5649: ungetc(c,ficpar);
5650: fgets(line, MAXLINE, ficpar);
5651: numlinepar++;
5652: fputs(line, stdout);
5653: //puts(line);
5654: fputs(line,ficparo);
5655: fputs(line,ficlog);
5656: }
5657: ungetc(c,ficpar);
5658:
5659:
5660: covar=matrix(0,NCOVMAX,1,n); /**< used in readdata */
5661: cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
5662: /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
5663: v1+v2*age+v2*v3 makes cptcovn = 3
5664: */
5665: if (strlen(model)>1)
5666: 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*/
5667: else
5668: ncovmodel=2;
5669: nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
5670: nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
5671: npar= nforce*ncovmodel; /* Number of parameters like aij*/
5672: if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
5673: 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);
5674: 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);
5675: fflush(stdout);
5676: fclose (ficlog);
5677: goto end;
5678: }
5679: delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5680: delti=delti3[1][1];
5681: /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
5682: if(mle==-1){ /* Print a wizard for help writing covariance matrix */
5683: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
5684: printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
5685: fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
5686: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
5687: fclose (ficparo);
5688: fclose (ficlog);
5689: goto end;
5690: exit(0);
5691: }
5692: else if(mle==-3) {
5693: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
5694: printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
5695: fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
5696: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5697: matcov=matrix(1,npar,1,npar);
5698: }
5699: else{
5700: /* Read guessed parameters */
5701: /* Reads comments: lines beginning with '#' */
5702: while((c=getc(ficpar))=='#' && c!= EOF){
5703: ungetc(c,ficpar);
5704: fgets(line, MAXLINE, ficpar);
5705: numlinepar++;
5706: fputs(line,stdout);
5707: fputs(line,ficparo);
5708: fputs(line,ficlog);
5709: }
5710: ungetc(c,ficpar);
5711:
5712: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5713: for(i=1; i <=nlstate; i++){
5714: j=0;
5715: for(jj=1; jj <=nlstate+ndeath; jj++){
5716: if(jj==i) continue;
5717: j++;
5718: fscanf(ficpar,"%1d%1d",&i1,&j1);
5719: if ((i1 != i) && (j1 != j)){
5720: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
5721: It might be a problem of design; if ncovcol and the model are correct\n \
5722: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
5723: exit(1);
5724: }
5725: fprintf(ficparo,"%1d%1d",i1,j1);
5726: if(mle==1)
5727: printf("%1d%1d",i,j);
5728: fprintf(ficlog,"%1d%1d",i,j);
5729: for(k=1; k<=ncovmodel;k++){
5730: fscanf(ficpar," %lf",¶m[i][j][k]);
5731: if(mle==1){
5732: printf(" %lf",param[i][j][k]);
5733: fprintf(ficlog," %lf",param[i][j][k]);
5734: }
5735: else
5736: fprintf(ficlog," %lf",param[i][j][k]);
5737: fprintf(ficparo," %lf",param[i][j][k]);
5738: }
5739: fscanf(ficpar,"\n");
5740: numlinepar++;
5741: if(mle==1)
5742: printf("\n");
5743: fprintf(ficlog,"\n");
5744: fprintf(ficparo,"\n");
5745: }
5746: }
5747: fflush(ficlog);
5748:
5749: /* Reads scales values */
5750: p=param[1][1];
5751:
5752: /* Reads comments: lines beginning with '#' */
5753: while((c=getc(ficpar))=='#' && c!= EOF){
5754: ungetc(c,ficpar);
5755: fgets(line, MAXLINE, ficpar);
5756: numlinepar++;
5757: fputs(line,stdout);
5758: fputs(line,ficparo);
5759: fputs(line,ficlog);
5760: }
5761: ungetc(c,ficpar);
5762:
5763: for(i=1; i <=nlstate; i++){
5764: for(j=1; j <=nlstate+ndeath-1; j++){
5765: fscanf(ficpar,"%1d%1d",&i1,&j1);
5766: if ( (i1-i) * (j1-j) != 0){
5767: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
5768: exit(1);
5769: }
5770: printf("%1d%1d",i,j);
5771: fprintf(ficparo,"%1d%1d",i1,j1);
5772: fprintf(ficlog,"%1d%1d",i1,j1);
5773: for(k=1; k<=ncovmodel;k++){
5774: fscanf(ficpar,"%le",&delti3[i][j][k]);
5775: printf(" %le",delti3[i][j][k]);
5776: fprintf(ficparo," %le",delti3[i][j][k]);
5777: fprintf(ficlog," %le",delti3[i][j][k]);
5778: }
5779: fscanf(ficpar,"\n");
5780: numlinepar++;
5781: printf("\n");
5782: fprintf(ficparo,"\n");
5783: fprintf(ficlog,"\n");
5784: }
5785: }
5786: fflush(ficlog);
5787:
5788: /* Reads covariance matrix */
5789: delti=delti3[1][1];
5790:
5791:
5792: /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
5793:
5794: /* Reads comments: lines beginning with '#' */
5795: while((c=getc(ficpar))=='#' && c!= EOF){
5796: ungetc(c,ficpar);
5797: fgets(line, MAXLINE, ficpar);
5798: numlinepar++;
5799: fputs(line,stdout);
5800: fputs(line,ficparo);
5801: fputs(line,ficlog);
5802: }
5803: ungetc(c,ficpar);
5804:
5805: matcov=matrix(1,npar,1,npar);
5806: for(i=1; i <=npar; i++)
5807: for(j=1; j <=npar; j++) matcov[i][j]=0.;
5808:
5809: for(i=1; i <=npar; i++){
5810: fscanf(ficpar,"%s",str);
5811: if(mle==1)
5812: printf("%s",str);
5813: fprintf(ficlog,"%s",str);
5814: fprintf(ficparo,"%s",str);
5815: for(j=1; j <=i; j++){
5816: fscanf(ficpar," %le",&matcov[i][j]);
5817: if(mle==1){
5818: printf(" %.5le",matcov[i][j]);
5819: }
5820: fprintf(ficlog," %.5le",matcov[i][j]);
5821: fprintf(ficparo," %.5le",matcov[i][j]);
5822: }
5823: fscanf(ficpar,"\n");
5824: numlinepar++;
5825: if(mle==1)
5826: printf("\n");
5827: fprintf(ficlog,"\n");
5828: fprintf(ficparo,"\n");
5829: }
5830: for(i=1; i <=npar; i++)
5831: for(j=i+1;j<=npar;j++)
5832: matcov[i][j]=matcov[j][i];
5833:
5834: if(mle==1)
5835: printf("\n");
5836: fprintf(ficlog,"\n");
5837:
5838: fflush(ficlog);
5839:
5840: /*-------- Rewriting parameter file ----------*/
5841: strcpy(rfileres,"r"); /* "Rparameterfile */
5842: strcat(rfileres,optionfilefiname); /* Parameter file first name*/
5843: strcat(rfileres,"."); /* */
5844: strcat(rfileres,optionfilext); /* Other files have txt extension */
5845: if((ficres =fopen(rfileres,"w"))==NULL) {
5846: printf("Problem writing new parameter file: %s\n", fileres);goto end;
5847: fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
5848: }
5849: fprintf(ficres,"#%s\n",version);
5850: } /* End of mle != -3 */
5851:
5852:
5853: n= lastobs;
5854: num=lvector(1,n);
5855: moisnais=vector(1,n);
5856: annais=vector(1,n);
5857: moisdc=vector(1,n);
5858: andc=vector(1,n);
5859: agedc=vector(1,n);
5860: cod=ivector(1,n);
5861: weight=vector(1,n);
5862: for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
5863: mint=matrix(1,maxwav,1,n);
5864: anint=matrix(1,maxwav,1,n);
5865: s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */
5866: tab=ivector(1,NCOVMAX);
5867: ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
5868:
5869: /* Reads data from file datafile */
5870: if (readdata(datafile, firstobs, lastobs, &imx)==1)
5871: goto end;
5872:
5873: /* Calculation of the number of parameters from char model */
5874: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4
5875: k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
5876: k=3 V4 Tvar[k=3]= 4 (from V4)
5877: k=2 V1 Tvar[k=2]= 1 (from V1)
5878: k=1 Tvar[1]=2 (from V2)
5879: */
5880: Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
5881: /* V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs).
5882: For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4,
5883: Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
5884: */
5885: /* For model-covariate k tells which data-covariate to use but
5886: because this model-covariate is a construction we invent a new column
5887: ncovcol + k1
5888: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
5889: Tvar[3=V1*V4]=4+1 etc */
5890: Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
5891: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
5892: if V2+V1+V1*V4+age*V3+V3*V2 TProd[k1=2]=5 (V3*V2)
5893: */
5894: Tvaraff=ivector(1,NCOVMAX); /* Unclear */
5895: 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
5896: * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd.
5897: * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
5898: Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
5899: 4 covariates (3 plus signs)
5900: Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
5901: */
5902:
5903: if(decodemodel(model, lastobs) == 1)
5904: goto end;
5905:
5906: if((double)(lastobs-imx)/(double)imx > 1.10){
5907: nbwarn++;
5908: 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);
5909: 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);
5910: }
5911: /* if(mle==1){*/
5912: if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
5913: for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
5914: }
5915:
5916: /*-calculation of age at interview from date of interview and age at death -*/
5917: agev=matrix(1,maxwav,1,imx);
5918:
5919: if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
5920: goto end;
5921:
5922:
5923: agegomp=(int)agemin;
5924: free_vector(moisnais,1,n);
5925: free_vector(annais,1,n);
5926: /* free_matrix(mint,1,maxwav,1,n);
5927: free_matrix(anint,1,maxwav,1,n);*/
5928: free_vector(moisdc,1,n);
5929: free_vector(andc,1,n);
5930: /* */
5931:
5932: wav=ivector(1,imx);
5933: dh=imatrix(1,lastpass-firstpass+1,1,imx);
5934: bh=imatrix(1,lastpass-firstpass+1,1,imx);
5935: mw=imatrix(1,lastpass-firstpass+1,1,imx);
5936:
5937: /* Concatenates waves */
5938: concatwav(wav, dh, bh, mw, s, agedc, agev, firstpass, lastpass, imx, nlstate, stepm);
5939: /* */
5940:
5941: /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
5942:
5943: nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
5944: ncodemax[1]=1;
5945: Ndum =ivector(-1,NCOVMAX);
5946: if (ncovmodel > 2)
5947: tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
5948:
5949: codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
5950: /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
5951: h=0;
5952:
5953:
5954: /*if (cptcovn > 0) */
5955:
5956:
5957: m=pow(2,cptcoveff);
5958:
5959: for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
5960: 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 */
5961: for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
5962: for(cpt=1; cpt <=pow(2,k-1); cpt++){ /* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 */
5963: h++;
5964: if (h>m)
5965: h=1;
5966: /**< codtab(h,k) k = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
5967: * h 1 2 3 4
5968: *______________________________
5969: * 1 i=1 1 i=1 1 i=1 1 i=1 1
5970: * 2 2 1 1 1
5971: * 3 i=2 1 2 1 1
5972: * 4 2 2 1 1
5973: * 5 i=3 1 i=2 1 2 1
5974: * 6 2 1 2 1
5975: * 7 i=4 1 2 2 1
5976: * 8 2 2 2 1
5977: * 9 i=5 1 i=3 1 i=2 1 1
5978: * 10 2 1 1 1
5979: * 11 i=6 1 2 1 1
5980: * 12 2 2 1 1
5981: * 13 i=7 1 i=4 1 2 1
5982: * 14 2 1 2 1
5983: * 15 i=8 1 2 2 1
5984: * 16 2 2 2 1
5985: */
5986: codtab[h][k]=j;
5987: /*codtab[h][Tvar[k]]=j;*/
5988: 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]]);
5989: }
5990: }
5991: }
5992: }
5993: /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
5994: codtab[1][2]=1;codtab[2][2]=2; */
5995: /* for(i=1; i <=m ;i++){
5996: for(k=1; k <=cptcovn; k++){
5997: printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
5998: }
5999: printf("\n");
6000: }
6001: scanf("%d",i);*/
6002:
6003: free_ivector(Ndum,-1,NCOVMAX);
6004:
6005:
6006:
6007: /*------------ gnuplot -------------*/
6008: strcpy(optionfilegnuplot,optionfilefiname);
6009: if(mle==-3)
6010: strcat(optionfilegnuplot,"-mort");
6011: strcat(optionfilegnuplot,".gp");
6012:
6013: if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
6014: printf("Problem with file %s",optionfilegnuplot);
6015: }
6016: else{
6017: fprintf(ficgp,"\n# %s\n", version);
6018: fprintf(ficgp,"# %s\n", optionfilegnuplot);
6019: //fprintf(ficgp,"set missing 'NaNq'\n");
6020: fprintf(ficgp,"set datafile missing 'NaNq'\n");
6021: }
6022: /* fclose(ficgp);*/
6023: /*--------- index.htm --------*/
6024:
6025: strcpy(optionfilehtm,optionfilefiname); /* Main html file */
6026: if(mle==-3)
6027: strcat(optionfilehtm,"-mort");
6028: strcat(optionfilehtm,".htm");
6029: if((fichtm=fopen(optionfilehtm,"w"))==NULL) {
6030: printf("Problem with %s \n",optionfilehtm);
6031: exit(0);
6032: }
6033:
6034: strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
6035: strcat(optionfilehtmcov,"-cov.htm");
6036: if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL) {
6037: printf("Problem with %s \n",optionfilehtmcov), exit(0);
6038: }
6039: else{
6040: fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6041: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6042: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
6043: optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
6044: }
6045:
6046: fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6047: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6048: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
6049: \n\
6050: <hr size=\"2\" color=\"#EC5E5E\">\
6051: <ul><li><h4>Parameter files</h4>\n\
6052: - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
6053: - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
6054: - Log file of the run: <a href=\"%s\">%s</a><br>\n\
6055: - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
6056: - Date and time at start: %s</ul>\n",\
6057: optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
6058: optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
6059: fileres,fileres,\
6060: filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
6061: fflush(fichtm);
6062:
6063: strcpy(pathr,path);
6064: strcat(pathr,optionfilefiname);
6065: chdir(optionfilefiname); /* Move to directory named optionfile */
6066:
6067: /* Calculates basic frequencies. Computes observed prevalence at single age
6068: and prints on file fileres'p'. */
6069: freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
6070:
6071: fprintf(fichtm,"\n");
6072: fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
6073: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
6074: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
6075: imx,agemin,agemax,jmin,jmax,jmean);
6076: pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6077: oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6078: newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6079: savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6080: oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
6081:
6082:
6083: /* For Powell, parameters are in a vector p[] starting at p[1]
6084: so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
6085: p=param[1][1]; /* *(*(*(param +1)+1)+0) */
6086:
6087: globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
6088:
6089: if (mle==-3){
6090: ximort=matrix(1,NDIM,1,NDIM);
6091: /* ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
6092: cens=ivector(1,n);
6093: ageexmed=vector(1,n);
6094: agecens=vector(1,n);
6095: dcwave=ivector(1,n);
6096:
6097: for (i=1; i<=imx; i++){
6098: dcwave[i]=-1;
6099: for (m=firstpass; m<=lastpass; m++)
6100: if (s[m][i]>nlstate) {
6101: dcwave[i]=m;
6102: /* printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
6103: break;
6104: }
6105: }
6106:
6107: for (i=1; i<=imx; i++) {
6108: if (wav[i]>0){
6109: ageexmed[i]=agev[mw[1][i]][i];
6110: j=wav[i];
6111: agecens[i]=1.;
6112:
6113: if (ageexmed[i]> 1 && wav[i] > 0){
6114: agecens[i]=agev[mw[j][i]][i];
6115: cens[i]= 1;
6116: }else if (ageexmed[i]< 1)
6117: cens[i]= -1;
6118: if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
6119: cens[i]=0 ;
6120: }
6121: else cens[i]=-1;
6122: }
6123:
6124: for (i=1;i<=NDIM;i++) {
6125: for (j=1;j<=NDIM;j++)
6126: ximort[i][j]=(i == j ? 1.0 : 0.0);
6127: }
6128:
6129: /*p[1]=0.0268; p[NDIM]=0.083;*/
6130: /*printf("%lf %lf", p[1], p[2]);*/
6131:
6132:
6133: #ifdef GSL
6134: printf("GSL optimization\n"); fprintf(ficlog,"Powell\n");
6135: #else
6136: printf("Powell\n"); fprintf(ficlog,"Powell\n");
6137: #endif
6138: strcpy(filerespow,"pow-mort");
6139: strcat(filerespow,fileres);
6140: if((ficrespow=fopen(filerespow,"w"))==NULL) {
6141: printf("Problem with resultfile: %s\n", filerespow);
6142: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
6143: }
6144: #ifdef GSL
6145: fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
6146: #else
6147: fprintf(ficrespow,"# Powell\n# iter -2*LL");
6148: #endif
6149: /* for (i=1;i<=nlstate;i++)
6150: for(j=1;j<=nlstate+ndeath;j++)
6151: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
6152: */
6153: fprintf(ficrespow,"\n");
6154: #ifdef GSL
6155: /* gsl starts here */
6156: T = gsl_multimin_fminimizer_nmsimplex;
6157: gsl_multimin_fminimizer *sfm = NULL;
6158: gsl_vector *ss, *x;
6159: gsl_multimin_function minex_func;
6160:
6161: /* Initial vertex size vector */
6162: ss = gsl_vector_alloc (NDIM);
6163:
6164: if (ss == NULL){
6165: GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
6166: }
6167: /* Set all step sizes to 1 */
6168: gsl_vector_set_all (ss, 0.001);
6169:
6170: /* Starting point */
6171:
6172: x = gsl_vector_alloc (NDIM);
6173:
6174: if (x == NULL){
6175: gsl_vector_free(ss);
6176: GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
6177: }
6178:
6179: /* Initialize method and iterate */
6180: /* p[1]=0.0268; p[NDIM]=0.083; */
6181: /* gsl_vector_set(x, 0, 0.0268); */
6182: /* gsl_vector_set(x, 1, 0.083); */
6183: gsl_vector_set(x, 0, p[1]);
6184: gsl_vector_set(x, 1, p[2]);
6185:
6186: minex_func.f = &gompertz_f;
6187: minex_func.n = NDIM;
6188: minex_func.params = (void *)&p; /* ??? */
6189:
6190: sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
6191: gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
6192:
6193: printf("Iterations beginning .....\n\n");
6194: printf("Iter. # Intercept Slope -Log Likelihood Simplex size\n");
6195:
6196: iteri=0;
6197: while (rval == GSL_CONTINUE){
6198: iteri++;
6199: status = gsl_multimin_fminimizer_iterate(sfm);
6200:
6201: if (status) printf("error: %s\n", gsl_strerror (status));
6202: fflush(0);
6203:
6204: if (status)
6205: break;
6206:
6207: rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
6208: ssval = gsl_multimin_fminimizer_size (sfm);
6209:
6210: if (rval == GSL_SUCCESS)
6211: printf ("converged to a local maximum at\n");
6212:
6213: printf("%5d ", iteri);
6214: for (it = 0; it < NDIM; it++){
6215: printf ("%10.5f ", gsl_vector_get (sfm->x, it));
6216: }
6217: printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
6218: }
6219:
6220: printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
6221:
6222: gsl_vector_free(x); /* initial values */
6223: gsl_vector_free(ss); /* inital step size */
6224: for (it=0; it<NDIM; it++){
6225: p[it+1]=gsl_vector_get(sfm->x,it);
6226: fprintf(ficrespow," %.12lf", p[it]);
6227: }
6228: gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1) */
6229: #endif
6230: #ifdef POWELL
6231: powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
6232: #endif
6233: fclose(ficrespow);
6234:
6235: hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);
6236:
6237: for(i=1; i <=NDIM; i++)
6238: for(j=i+1;j<=NDIM;j++)
6239: matcov[i][j]=matcov[j][i];
6240:
6241: printf("\nCovariance matrix\n ");
6242: for(i=1; i <=NDIM; i++) {
6243: for(j=1;j<=NDIM;j++){
6244: printf("%f ",matcov[i][j]);
6245: }
6246: printf("\n ");
6247: }
6248:
6249: printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
6250: for (i=1;i<=NDIM;i++)
6251: printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
6252:
6253: lsurv=vector(1,AGESUP);
6254: lpop=vector(1,AGESUP);
6255: tpop=vector(1,AGESUP);
6256: lsurv[agegomp]=100000;
6257:
6258: for (k=agegomp;k<=AGESUP;k++) {
6259: agemortsup=k;
6260: if (p[1]*exp(p[2]*(k-agegomp))>1) break;
6261: }
6262:
6263: for (k=agegomp;k<agemortsup;k++)
6264: lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
6265:
6266: for (k=agegomp;k<agemortsup;k++){
6267: lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
6268: sumlpop=sumlpop+lpop[k];
6269: }
6270:
6271: tpop[agegomp]=sumlpop;
6272: for (k=agegomp;k<(agemortsup-3);k++){
6273: /* tpop[k+1]=2;*/
6274: tpop[k+1]=tpop[k]-lpop[k];
6275: }
6276:
6277:
6278: printf("\nAge lx qx dx Lx Tx e(x)\n");
6279: for (k=agegomp;k<(agemortsup-2);k++)
6280: 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]);
6281:
6282:
6283: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6284: printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6285:
6286: printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
6287: stepm, weightopt,\
6288: model,imx,p,matcov,agemortsup);
6289:
6290: free_vector(lsurv,1,AGESUP);
6291: free_vector(lpop,1,AGESUP);
6292: free_vector(tpop,1,AGESUP);
6293: #ifdef GSL
6294: free_ivector(cens,1,n);
6295: free_vector(agecens,1,n);
6296: free_ivector(dcwave,1,n);
6297: free_matrix(ximort,1,NDIM,1,NDIM);
6298: #endif
6299: } /* Endof if mle==-3 */
6300:
6301: else{ /* For mle >=1 */
6302: globpr=0;/* debug */
6303: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
6304: printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6305: for (k=1; k<=npar;k++)
6306: printf(" %d %8.5f",k,p[k]);
6307: printf("\n");
6308: globpr=1; /* to print the contributions */
6309: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
6310: printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6311: for (k=1; k<=npar;k++)
6312: printf(" %d %8.5f",k,p[k]);
6313: printf("\n");
6314: if(mle>=1){ /* Could be 1 or 2 */
6315: mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
6316: }
6317:
6318: /*--------- results files --------------*/
6319: 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);
6320:
6321:
6322: fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6323: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6324: fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6325: for(i=1,jk=1; i <=nlstate; i++){
6326: for(k=1; k <=(nlstate+ndeath); k++){
6327: if (k != i) {
6328: printf("%d%d ",i,k);
6329: fprintf(ficlog,"%d%d ",i,k);
6330: fprintf(ficres,"%1d%1d ",i,k);
6331: for(j=1; j <=ncovmodel; j++){
6332: printf("%lf ",p[jk]);
6333: fprintf(ficlog,"%lf ",p[jk]);
6334: fprintf(ficres,"%lf ",p[jk]);
6335: jk++;
6336: }
6337: printf("\n");
6338: fprintf(ficlog,"\n");
6339: fprintf(ficres,"\n");
6340: }
6341: }
6342: }
6343: if(mle!=0){
6344: /* Computing hessian and covariance matrix */
6345: ftolhess=ftol; /* Usually correct */
6346: hesscov(matcov, p, npar, delti, ftolhess, func);
6347: }
6348: fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
6349: printf("# Scales (for hessian or gradient estimation)\n");
6350: fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
6351: for(i=1,jk=1; i <=nlstate; i++){
6352: for(j=1; j <=nlstate+ndeath; j++){
6353: if (j!=i) {
6354: fprintf(ficres,"%1d%1d",i,j);
6355: printf("%1d%1d",i,j);
6356: fprintf(ficlog,"%1d%1d",i,j);
6357: for(k=1; k<=ncovmodel;k++){
6358: printf(" %.5e",delti[jk]);
6359: fprintf(ficlog," %.5e",delti[jk]);
6360: fprintf(ficres," %.5e",delti[jk]);
6361: jk++;
6362: }
6363: printf("\n");
6364: fprintf(ficlog,"\n");
6365: fprintf(ficres,"\n");
6366: }
6367: }
6368: }
6369:
6370: 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");
6371: if(mle>=1)
6372: 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");
6373: 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");
6374: /* # 121 Var(a12)\n\ */
6375: /* # 122 Cov(b12,a12) Var(b12)\n\ */
6376: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
6377: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
6378: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
6379: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
6380: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
6381: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
6382:
6383:
6384: /* Just to have a covariance matrix which will be more understandable
6385: even is we still don't want to manage dictionary of variables
6386: */
6387: for(itimes=1;itimes<=2;itimes++){
6388: jj=0;
6389: for(i=1; i <=nlstate; i++){
6390: for(j=1; j <=nlstate+ndeath; j++){
6391: if(j==i) continue;
6392: for(k=1; k<=ncovmodel;k++){
6393: jj++;
6394: ca[0]= k+'a'-1;ca[1]='\0';
6395: if(itimes==1){
6396: if(mle>=1)
6397: printf("#%1d%1d%d",i,j,k);
6398: fprintf(ficlog,"#%1d%1d%d",i,j,k);
6399: fprintf(ficres,"#%1d%1d%d",i,j,k);
6400: }else{
6401: if(mle>=1)
6402: printf("%1d%1d%d",i,j,k);
6403: fprintf(ficlog,"%1d%1d%d",i,j,k);
6404: fprintf(ficres,"%1d%1d%d",i,j,k);
6405: }
6406: ll=0;
6407: for(li=1;li <=nlstate; li++){
6408: for(lj=1;lj <=nlstate+ndeath; lj++){
6409: if(lj==li) continue;
6410: for(lk=1;lk<=ncovmodel;lk++){
6411: ll++;
6412: if(ll<=jj){
6413: cb[0]= lk +'a'-1;cb[1]='\0';
6414: if(ll<jj){
6415: if(itimes==1){
6416: if(mle>=1)
6417: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6418: fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6419: fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6420: }else{
6421: if(mle>=1)
6422: printf(" %.5e",matcov[jj][ll]);
6423: fprintf(ficlog," %.5e",matcov[jj][ll]);
6424: fprintf(ficres," %.5e",matcov[jj][ll]);
6425: }
6426: }else{
6427: if(itimes==1){
6428: if(mle>=1)
6429: printf(" Var(%s%1d%1d)",ca,i,j);
6430: fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
6431: fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
6432: }else{
6433: if(mle>=1)
6434: printf(" %.5e",matcov[jj][ll]);
6435: fprintf(ficlog," %.5e",matcov[jj][ll]);
6436: fprintf(ficres," %.5e",matcov[jj][ll]);
6437: }
6438: }
6439: }
6440: } /* end lk */
6441: } /* end lj */
6442: } /* end li */
6443: if(mle>=1)
6444: printf("\n");
6445: fprintf(ficlog,"\n");
6446: fprintf(ficres,"\n");
6447: numlinepar++;
6448: } /* end k*/
6449: } /*end j */
6450: } /* end i */
6451: } /* end itimes */
6452:
6453: fflush(ficlog);
6454: fflush(ficres);
6455:
6456: while((c=getc(ficpar))=='#' && c!= EOF){
6457: ungetc(c,ficpar);
6458: fgets(line, MAXLINE, ficpar);
6459: fputs(line,stdout);
6460: fputs(line,ficparo);
6461: }
6462: ungetc(c,ficpar);
6463:
6464: estepm=0;
6465: fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
6466: if (estepm==0 || estepm < stepm) estepm=stepm;
6467: if (fage <= 2) {
6468: bage = ageminpar;
6469: fage = agemaxpar;
6470: }
6471:
6472: fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
6473: fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6474: fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6475:
6476: while((c=getc(ficpar))=='#' && c!= EOF){
6477: ungetc(c,ficpar);
6478: fgets(line, MAXLINE, ficpar);
6479: fputs(line,stdout);
6480: fputs(line,ficparo);
6481: }
6482: ungetc(c,ficpar);
6483:
6484: 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);
6485: 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);
6486: 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);
6487: printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
6488: 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);
6489:
6490: while((c=getc(ficpar))=='#' && c!= EOF){
6491: ungetc(c,ficpar);
6492: fgets(line, MAXLINE, ficpar);
6493: fputs(line,stdout);
6494: fputs(line,ficparo);
6495: }
6496: ungetc(c,ficpar);
6497:
6498:
6499: dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
6500: dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
6501:
6502: fscanf(ficpar,"pop_based=%d\n",&popbased);
6503: fprintf(ficparo,"pop_based=%d\n",popbased);
6504: fprintf(ficres,"pop_based=%d\n",popbased);
6505:
6506: while((c=getc(ficpar))=='#' && c!= EOF){
6507: ungetc(c,ficpar);
6508: fgets(line, MAXLINE, ficpar);
6509: fputs(line,stdout);
6510: fputs(line,ficparo);
6511: }
6512: ungetc(c,ficpar);
6513:
6514: 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);
6515: 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);
6516: 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);
6517: 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);
6518: 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);
6519: /* day and month of proj2 are not used but only year anproj2.*/
6520:
6521:
6522:
6523: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
6524: /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
6525:
6526: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6527: printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6528:
6529: printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
6530: model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
6531: jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
6532:
6533: /*------------ free_vector -------------*/
6534: /* chdir(path); */
6535:
6536: free_ivector(wav,1,imx);
6537: free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
6538: free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
6539: free_imatrix(mw,1,lastpass-firstpass+1,1,imx);
6540: free_lvector(num,1,n);
6541: free_vector(agedc,1,n);
6542: /*free_matrix(covar,0,NCOVMAX,1,n);*/
6543: /*free_matrix(covar,1,NCOVMAX,1,n);*/
6544: fclose(ficparo);
6545: fclose(ficres);
6546:
6547:
6548: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
6549: #include "prevlim.h" /* Use ficrespl, ficlog */
6550: fclose(ficrespl);
6551:
6552: #ifdef FREEEXIT2
6553: #include "freeexit2.h"
6554: #endif
6555:
6556: /*------------- h Pij x at various ages ------------*/
6557: #include "hpijx.h"
6558: fclose(ficrespij);
6559:
6560: /*-------------- Variance of one-step probabilities---*/
6561: k=1;
6562: varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
6563:
6564:
6565: probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
6566: for(i=1;i<=AGESUP;i++)
6567: for(j=1;j<=NCOVMAX;j++)
6568: for(k=1;k<=NCOVMAX;k++)
6569: probs[i][j][k]=0.;
6570:
6571: /*---------- Forecasting ------------------*/
6572: /*if((stepm == 1) && (strcmp(model,".")==0)){*/
6573: if(prevfcast==1){
6574: /* if(stepm ==1){*/
6575: prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
6576: /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
6577: /* } */
6578: /* else{ */
6579: /* erreur=108; */
6580: /* 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); */
6581: /* 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); */
6582: /* } */
6583: }
6584:
6585:
6586: /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
6587:
6588: prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
6589: /* 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",\
6590: ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
6591: */
6592:
6593: if (mobilav!=0) {
6594: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
6595: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
6596: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
6597: printf(" Error in movingaverage mobilav=%d\n",mobilav);
6598: }
6599: }
6600:
6601:
6602: /*---------- Health expectancies, no variances ------------*/
6603:
6604: strcpy(filerese,"e");
6605: strcat(filerese,fileres);
6606: if((ficreseij=fopen(filerese,"w"))==NULL) {
6607: printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
6608: fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
6609: }
6610: printf("Computing Health Expectancies: result on file '%s' \n", filerese);
6611: fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
6612: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6613: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6614:
6615: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6616: fprintf(ficreseij,"\n#****** ");
6617: for(j=1;j<=cptcoveff;j++) {
6618: fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6619: }
6620: fprintf(ficreseij,"******\n");
6621:
6622: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6623: oldm=oldms;savm=savms;
6624: evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);
6625:
6626: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
6627: /*}*/
6628: }
6629: fclose(ficreseij);
6630:
6631:
6632: /*---------- Health expectancies and variances ------------*/
6633:
6634:
6635: strcpy(filerest,"t");
6636: strcat(filerest,fileres);
6637: if((ficrest=fopen(filerest,"w"))==NULL) {
6638: printf("Problem with total LE resultfile: %s\n", filerest);goto end;
6639: fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
6640: }
6641: printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
6642: fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
6643:
6644:
6645: strcpy(fileresstde,"stde");
6646: strcat(fileresstde,fileres);
6647: if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
6648: printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
6649: fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
6650: }
6651: printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
6652: fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
6653:
6654: strcpy(filerescve,"cve");
6655: strcat(filerescve,fileres);
6656: if((ficrescveij=fopen(filerescve,"w"))==NULL) {
6657: printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
6658: fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
6659: }
6660: printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
6661: fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
6662:
6663: strcpy(fileresv,"v");
6664: strcat(fileresv,fileres);
6665: if((ficresvij=fopen(fileresv,"w"))==NULL) {
6666: printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
6667: fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
6668: }
6669: printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
6670: fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
6671:
6672: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6673: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6674:
6675: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6676: fprintf(ficrest,"\n#****** ");
6677: for(j=1;j<=cptcoveff;j++)
6678: fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6679: fprintf(ficrest,"******\n");
6680:
6681: fprintf(ficresstdeij,"\n#****** ");
6682: fprintf(ficrescveij,"\n#****** ");
6683: for(j=1;j<=cptcoveff;j++) {
6684: fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6685: fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6686: }
6687: fprintf(ficresstdeij,"******\n");
6688: fprintf(ficrescveij,"******\n");
6689:
6690: fprintf(ficresvij,"\n#****** ");
6691: for(j=1;j<=cptcoveff;j++)
6692: fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6693: fprintf(ficresvij,"******\n");
6694:
6695: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6696: oldm=oldms;savm=savms;
6697: cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
6698: /*
6699: */
6700: /* goto endfree; */
6701:
6702: vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6703: pstamp(ficrest);
6704:
6705:
6706: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
6707: oldm=oldms;savm=savms; /* Segmentation fault */
6708: cptcod= 0; /* To be deleted */
6709: 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 */
6710: 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 ");
6711: if(vpopbased==1)
6712: 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);
6713: else
6714: fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
6715: fprintf(ficrest,"# Age e.. (std) ");
6716: for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
6717: fprintf(ficrest,"\n");
6718:
6719: epj=vector(1,nlstate+1);
6720: for(age=bage; age <=fage ;age++){
6721: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
6722: if (vpopbased==1) {
6723: if(mobilav ==0){
6724: for(i=1; i<=nlstate;i++)
6725: prlim[i][i]=probs[(int)age][i][k];
6726: }else{ /* mobilav */
6727: for(i=1; i<=nlstate;i++)
6728: prlim[i][i]=mobaverage[(int)age][i][k];
6729: }
6730: }
6731:
6732: fprintf(ficrest," %4.0f",age);
6733: for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
6734: for(i=1, epj[j]=0.;i <=nlstate;i++) {
6735: epj[j] += prlim[i][i]*eij[i][j][(int)age];
6736: /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
6737: }
6738: epj[nlstate+1] +=epj[j];
6739: }
6740:
6741: for(i=1, vepp=0.;i <=nlstate;i++)
6742: for(j=1;j <=nlstate;j++)
6743: vepp += vareij[i][j][(int)age];
6744: fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
6745: for(j=1;j <=nlstate;j++){
6746: fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
6747: }
6748: fprintf(ficrest,"\n");
6749: }
6750: }
6751: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
6752: free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
6753: free_vector(epj,1,nlstate+1);
6754: /*}*/
6755: }
6756: free_vector(weight,1,n);
6757: free_imatrix(Tvard,1,NCOVMAX,1,2);
6758: free_imatrix(s,1,maxwav+1,1,n);
6759: free_matrix(anint,1,maxwav,1,n);
6760: free_matrix(mint,1,maxwav,1,n);
6761: free_ivector(cod,1,n);
6762: free_ivector(tab,1,NCOVMAX);
6763: fclose(ficresstdeij);
6764: fclose(ficrescveij);
6765: fclose(ficresvij);
6766: fclose(ficrest);
6767: fclose(ficpar);
6768:
6769: /*------- Variance of period (stable) prevalence------*/
6770:
6771: strcpy(fileresvpl,"vpl");
6772: strcat(fileresvpl,fileres);
6773: if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
6774: printf("Problem with variance of period (stable) prevalence resultfile: %s\n", fileresvpl);
6775: exit(0);
6776: }
6777: printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
6778:
6779: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6780: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6781:
6782: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6783: fprintf(ficresvpl,"\n#****** ");
6784: for(j=1;j<=cptcoveff;j++)
6785: fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6786: fprintf(ficresvpl,"******\n");
6787:
6788: varpl=matrix(1,nlstate,(int) bage, (int) fage);
6789: oldm=oldms;savm=savms;
6790: varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
6791: free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
6792: /*}*/
6793: }
6794:
6795: fclose(ficresvpl);
6796:
6797: /*---------- End : free ----------------*/
6798: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
6799: free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
6800: } /* mle==-3 arrives here for freeing */
6801: /* endfree:*/
6802: free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
6803: free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
6804: free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
6805: free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
6806: free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
6807: free_matrix(covar,0,NCOVMAX,1,n);
6808: free_matrix(matcov,1,npar,1,npar);
6809: /*free_vector(delti,1,npar);*/
6810: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
6811: free_matrix(agev,1,maxwav,1,imx);
6812: free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
6813:
6814: free_ivector(ncodemax,1,NCOVMAX);
6815: free_ivector(Tvar,1,NCOVMAX);
6816: free_ivector(Tprod,1,NCOVMAX);
6817: free_ivector(Tvaraff,1,NCOVMAX);
6818: free_ivector(Tage,1,NCOVMAX);
6819:
6820: free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
6821: free_imatrix(codtab,1,100,1,10);
6822: fflush(fichtm);
6823: fflush(ficgp);
6824:
6825:
6826: if((nberr >0) || (nbwarn>0)){
6827: printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
6828: fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
6829: }else{
6830: printf("End of Imach\n");
6831: fprintf(ficlog,"End of Imach\n");
6832: }
6833: printf("See log file on %s\n",filelog);
6834: /* gettimeofday(&end_time, (struct timezone*)0);*/ /* after time */
6835: /*(void) gettimeofday(&end_time,&tzp);*/
6836: rend_time = time(NULL);
6837: end_time = *localtime(&rend_time);
6838: /* tml = *localtime(&end_time.tm_sec); */
6839: strcpy(strtend,asctime(&end_time));
6840: printf("Local time at start %s\nLocal time at end %s",strstart, strtend);
6841: fprintf(ficlog,"Local time at start %s\nLocal time at end %s\n",strstart, strtend);
6842: printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
6843:
6844: printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
6845: fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
6846: fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
6847: /* printf("Total time was %d uSec.\n", total_usecs);*/
6848: /* if(fileappend(fichtm,optionfilehtm)){ */
6849: fprintf(fichtm,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
6850: fclose(fichtm);
6851: fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
6852: fclose(fichtmcov);
6853: fclose(ficgp);
6854: fclose(ficlog);
6855: /*------ End -----------*/
6856:
6857:
6858: printf("Before Current directory %s!\n",pathcd);
6859: if(chdir(pathcd) != 0)
6860: printf("Can't move to directory %s!\n",path);
6861: if(getcwd(pathcd,MAXLINE) > 0)
6862: printf("Current directory %s!\n",pathcd);
6863: /*strcat(plotcmd,CHARSEPARATOR);*/
6864: sprintf(plotcmd,"gnuplot");
6865: #ifdef _WIN32
6866: sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
6867: #endif
6868: if(!stat(plotcmd,&info)){
6869: printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
6870: if(!stat(getenv("GNUPLOTBIN"),&info)){
6871: printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
6872: }else
6873: strcpy(pplotcmd,plotcmd);
6874: #ifdef __unix
6875: strcpy(plotcmd,GNUPLOTPROGRAM);
6876: if(!stat(plotcmd,&info)){
6877: printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
6878: }else
6879: strcpy(pplotcmd,plotcmd);
6880: #endif
6881: }else
6882: strcpy(pplotcmd,plotcmd);
6883:
6884: sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
6885: printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
6886:
6887: if((outcmd=system(plotcmd)) != 0){
6888: printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
6889: printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
6890: sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
6891: if((outcmd=system(plotcmd)) != 0)
6892: printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
6893: }
6894: printf(" Successful, please wait...");
6895: while (z[0] != 'q') {
6896: /* chdir(path); */
6897: printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
6898: scanf("%s",z);
6899: /* if (z[0] == 'c') system("./imach"); */
6900: if (z[0] == 'e') {
6901: #ifdef __APPLE__
6902: sprintf(pplotcmd, "open %s", optionfilehtm);
6903: #elif __linux
6904: sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
6905: #else
6906: sprintf(pplotcmd, "%s", optionfilehtm);
6907: #endif
6908: printf("Starting browser with: %s",pplotcmd);fflush(stdout);
6909: system(pplotcmd);
6910: }
6911: else if (z[0] == 'g') system(plotcmd);
6912: else if (z[0] == 'q') exit(0);
6913: }
6914: end:
6915: while (z[0] != 'q') {
6916: printf("\nType q for exiting: ");
6917: scanf("%s",z);
6918: }
6919: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>