1: /* $Id: imach.c,v 1.152 2014/06/18 17:54:09 brouard Exp $
2: $State: Exp $
3: $Log: imach.c,v $
4: Revision 1.152 2014/06/18 17:54:09 brouard
5: Summary: open browser, use gnuplot on same dir than imach if not found in the path
6:
7: Revision 1.151 2014/06/18 16:43:30 brouard
8: *** empty log message ***
9:
10: Revision 1.150 2014/06/18 16:42:35 brouard
11: Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
12: Author: brouard
13:
14: Revision 1.149 2014/06/18 15:51:14 brouard
15: Summary: Some fixes in parameter files errors
16: Author: Nicolas Brouard
17:
18: Revision 1.148 2014/06/17 17:38:48 brouard
19: Summary: Nothing new
20: Author: Brouard
21:
22: Just a new packaging for OS/X version 0.98nS
23:
24: Revision 1.147 2014/06/16 10:33:11 brouard
25: *** empty log message ***
26:
27: Revision 1.146 2014/06/16 10:20:28 brouard
28: Summary: Merge
29: Author: Brouard
30:
31: Merge, before building revised version.
32:
33: Revision 1.145 2014/06/10 21:23:15 brouard
34: Summary: Debugging with valgrind
35: Author: Nicolas Brouard
36:
37: Lot of changes in order to output the results with some covariates
38: After the Edimburgh REVES conference 2014, it seems mandatory to
39: improve the code.
40: No more memory valgrind error but a lot has to be done in order to
41: continue the work of splitting the code into subroutines.
42: Also, decodemodel has been improved. Tricode is still not
43: optimal. nbcode should be improved. Documentation has been added in
44: the source code.
45:
46: Revision 1.143 2014/01/26 09:45:38 brouard
47: Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
48:
49: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
50: (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
51:
52: Revision 1.142 2014/01/26 03:57:36 brouard
53: Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
54:
55: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
56:
57: Revision 1.141 2014/01/26 02:42:01 brouard
58: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
59:
60: Revision 1.140 2011/09/02 10:37:54 brouard
61: Summary: times.h is ok with mingw32 now.
62:
63: Revision 1.139 2010/06/14 07:50:17 brouard
64: After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
65: I remember having already fixed agemin agemax which are pointers now but not cvs saved.
66:
67: Revision 1.138 2010/04/30 18:19:40 brouard
68: *** empty log message ***
69:
70: Revision 1.137 2010/04/29 18:11:38 brouard
71: (Module): Checking covariates for more complex models
72: than V1+V2. A lot of change to be done. Unstable.
73:
74: Revision 1.136 2010/04/26 20:30:53 brouard
75: (Module): merging some libgsl code. Fixing computation
76: of likelione (using inter/intrapolation if mle = 0) in order to
77: get same likelihood as if mle=1.
78: Some cleaning of code and comments added.
79:
80: Revision 1.135 2009/10/29 15:33:14 brouard
81: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
82:
83: Revision 1.134 2009/10/29 13:18:53 brouard
84: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
85:
86: Revision 1.133 2009/07/06 10:21:25 brouard
87: just nforces
88:
89: Revision 1.132 2009/07/06 08:22:05 brouard
90: Many tings
91:
92: Revision 1.131 2009/06/20 16:22:47 brouard
93: Some dimensions resccaled
94:
95: Revision 1.130 2009/05/26 06:44:34 brouard
96: (Module): Max Covariate is now set to 20 instead of 8. A
97: lot of cleaning with variables initialized to 0. Trying to make
98: V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
99:
100: Revision 1.129 2007/08/31 13:49:27 lievre
101: Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
102:
103: Revision 1.128 2006/06/30 13:02:05 brouard
104: (Module): Clarifications on computing e.j
105:
106: Revision 1.127 2006/04/28 18:11:50 brouard
107: (Module): Yes the sum of survivors was wrong since
108: imach-114 because nhstepm was no more computed in the age
109: loop. Now we define nhstepma in the age loop.
110: (Module): In order to speed up (in case of numerous covariates) we
111: compute health expectancies (without variances) in a first step
112: and then all the health expectancies with variances or standard
113: deviation (needs data from the Hessian matrices) which slows the
114: computation.
115: In the future we should be able to stop the program is only health
116: expectancies and graph are needed without standard deviations.
117:
118: Revision 1.126 2006/04/28 17:23:28 brouard
119: (Module): Yes the sum of survivors was wrong since
120: imach-114 because nhstepm was no more computed in the age
121: loop. Now we define nhstepma in the age loop.
122: Version 0.98h
123:
124: Revision 1.125 2006/04/04 15:20:31 lievre
125: Errors in calculation of health expectancies. Age was not initialized.
126: Forecasting file added.
127:
128: Revision 1.124 2006/03/22 17:13:53 lievre
129: Parameters are printed with %lf instead of %f (more numbers after the comma).
130: The log-likelihood is printed in the log file
131:
132: Revision 1.123 2006/03/20 10:52:43 brouard
133: * imach.c (Module): <title> changed, corresponds to .htm file
134: name. <head> headers where missing.
135:
136: * imach.c (Module): Weights can have a decimal point as for
137: English (a comma might work with a correct LC_NUMERIC environment,
138: otherwise the weight is truncated).
139: Modification of warning when the covariates values are not 0 or
140: 1.
141: Version 0.98g
142:
143: Revision 1.122 2006/03/20 09:45:41 brouard
144: (Module): Weights can have a decimal point as for
145: English (a comma might work with a correct LC_NUMERIC environment,
146: otherwise the weight is truncated).
147: Modification of warning when the covariates values are not 0 or
148: 1.
149: Version 0.98g
150:
151: Revision 1.121 2006/03/16 17:45:01 lievre
152: * imach.c (Module): Comments concerning covariates added
153:
154: * imach.c (Module): refinements in the computation of lli if
155: status=-2 in order to have more reliable computation if stepm is
156: not 1 month. Version 0.98f
157:
158: Revision 1.120 2006/03/16 15:10:38 lievre
159: (Module): refinements in the computation of lli if
160: status=-2 in order to have more reliable computation if stepm is
161: not 1 month. Version 0.98f
162:
163: Revision 1.119 2006/03/15 17:42:26 brouard
164: (Module): Bug if status = -2, the loglikelihood was
165: computed as likelihood omitting the logarithm. Version O.98e
166:
167: Revision 1.118 2006/03/14 18:20:07 brouard
168: (Module): varevsij Comments added explaining the second
169: table of variances if popbased=1 .
170: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
171: (Module): Function pstamp added
172: (Module): Version 0.98d
173:
174: Revision 1.117 2006/03/14 17:16:22 brouard
175: (Module): varevsij Comments added explaining the second
176: table of variances if popbased=1 .
177: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
178: (Module): Function pstamp added
179: (Module): Version 0.98d
180:
181: Revision 1.116 2006/03/06 10:29:27 brouard
182: (Module): Variance-covariance wrong links and
183: varian-covariance of ej. is needed (Saito).
184:
185: Revision 1.115 2006/02/27 12:17:45 brouard
186: (Module): One freematrix added in mlikeli! 0.98c
187:
188: Revision 1.114 2006/02/26 12:57:58 brouard
189: (Module): Some improvements in processing parameter
190: filename with strsep.
191:
192: Revision 1.113 2006/02/24 14:20:24 brouard
193: (Module): Memory leaks checks with valgrind and:
194: datafile was not closed, some imatrix were not freed and on matrix
195: allocation too.
196:
197: Revision 1.112 2006/01/30 09:55:26 brouard
198: (Module): Back to gnuplot.exe instead of wgnuplot.exe
199:
200: Revision 1.111 2006/01/25 20:38:18 brouard
201: (Module): Lots of cleaning and bugs added (Gompertz)
202: (Module): Comments can be added in data file. Missing date values
203: can be a simple dot '.'.
204:
205: Revision 1.110 2006/01/25 00:51:50 brouard
206: (Module): Lots of cleaning and bugs added (Gompertz)
207:
208: Revision 1.109 2006/01/24 19:37:15 brouard
209: (Module): Comments (lines starting with a #) are allowed in data.
210:
211: Revision 1.108 2006/01/19 18:05:42 lievre
212: Gnuplot problem appeared...
213: To be fixed
214:
215: Revision 1.107 2006/01/19 16:20:37 brouard
216: Test existence of gnuplot in imach path
217:
218: Revision 1.106 2006/01/19 13:24:36 brouard
219: Some cleaning and links added in html output
220:
221: Revision 1.105 2006/01/05 20:23:19 lievre
222: *** empty log message ***
223:
224: Revision 1.104 2005/09/30 16:11:43 lievre
225: (Module): sump fixed, loop imx fixed, and simplifications.
226: (Module): If the status is missing at the last wave but we know
227: that the person is alive, then we can code his/her status as -2
228: (instead of missing=-1 in earlier versions) and his/her
229: contributions to the likelihood is 1 - Prob of dying from last
230: health status (= 1-p13= p11+p12 in the easiest case of somebody in
231: the healthy state at last known wave). Version is 0.98
232:
233: Revision 1.103 2005/09/30 15:54:49 lievre
234: (Module): sump fixed, loop imx fixed, and simplifications.
235:
236: Revision 1.102 2004/09/15 17:31:30 brouard
237: Add the possibility to read data file including tab characters.
238:
239: Revision 1.101 2004/09/15 10:38:38 brouard
240: Fix on curr_time
241:
242: Revision 1.100 2004/07/12 18:29:06 brouard
243: Add version for Mac OS X. Just define UNIX in Makefile
244:
245: Revision 1.99 2004/06/05 08:57:40 brouard
246: *** empty log message ***
247:
248: Revision 1.98 2004/05/16 15:05:56 brouard
249: New version 0.97 . First attempt to estimate force of mortality
250: directly from the data i.e. without the need of knowing the health
251: state at each age, but using a Gompertz model: log u =a + b*age .
252: This is the basic analysis of mortality and should be done before any
253: other analysis, in order to test if the mortality estimated from the
254: cross-longitudinal survey is different from the mortality estimated
255: from other sources like vital statistic data.
256:
257: The same imach parameter file can be used but the option for mle should be -3.
258:
259: Agnès, who wrote this part of the code, tried to keep most of the
260: former routines in order to include the new code within the former code.
261:
262: The output is very simple: only an estimate of the intercept and of
263: the slope with 95% confident intervals.
264:
265: Current limitations:
266: A) Even if you enter covariates, i.e. with the
267: model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
268: B) There is no computation of Life Expectancy nor Life Table.
269:
270: Revision 1.97 2004/02/20 13:25:42 lievre
271: Version 0.96d. Population forecasting command line is (temporarily)
272: suppressed.
273:
274: Revision 1.96 2003/07/15 15:38:55 brouard
275: * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
276: rewritten within the same printf. Workaround: many printfs.
277:
278: Revision 1.95 2003/07/08 07:54:34 brouard
279: * imach.c (Repository):
280: (Repository): Using imachwizard code to output a more meaningful covariance
281: matrix (cov(a12,c31) instead of numbers.
282:
283: Revision 1.94 2003/06/27 13:00:02 brouard
284: Just cleaning
285:
286: Revision 1.93 2003/06/25 16:33:55 brouard
287: (Module): On windows (cygwin) function asctime_r doesn't
288: exist so I changed back to asctime which exists.
289: (Module): Version 0.96b
290:
291: Revision 1.92 2003/06/25 16:30:45 brouard
292: (Module): On windows (cygwin) function asctime_r doesn't
293: exist so I changed back to asctime which exists.
294:
295: Revision 1.91 2003/06/25 15:30:29 brouard
296: * imach.c (Repository): Duplicated warning errors corrected.
297: (Repository): Elapsed time after each iteration is now output. It
298: helps to forecast when convergence will be reached. Elapsed time
299: is stamped in powell. We created a new html file for the graphs
300: concerning matrix of covariance. It has extension -cov.htm.
301:
302: Revision 1.90 2003/06/24 12:34:15 brouard
303: (Module): Some bugs corrected for windows. Also, when
304: mle=-1 a template is output in file "or"mypar.txt with the design
305: of the covariance matrix to be input.
306:
307: Revision 1.89 2003/06/24 12:30:52 brouard
308: (Module): Some bugs corrected for windows. Also, when
309: mle=-1 a template is output in file "or"mypar.txt with the design
310: of the covariance matrix to be input.
311:
312: Revision 1.88 2003/06/23 17:54:56 brouard
313: * 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.
314:
315: Revision 1.87 2003/06/18 12:26:01 brouard
316: Version 0.96
317:
318: Revision 1.86 2003/06/17 20:04:08 brouard
319: (Module): Change position of html and gnuplot routines and added
320: routine fileappend.
321:
322: Revision 1.85 2003/06/17 13:12:43 brouard
323: * imach.c (Repository): Check when date of death was earlier that
324: current date of interview. It may happen when the death was just
325: prior to the death. In this case, dh was negative and likelihood
326: was wrong (infinity). We still send an "Error" but patch by
327: assuming that the date of death was just one stepm after the
328: interview.
329: (Repository): Because some people have very long ID (first column)
330: we changed int to long in num[] and we added a new lvector for
331: memory allocation. But we also truncated to 8 characters (left
332: truncation)
333: (Repository): No more line truncation errors.
334:
335: Revision 1.84 2003/06/13 21:44:43 brouard
336: * imach.c (Repository): Replace "freqsummary" at a correct
337: place. It differs from routine "prevalence" which may be called
338: many times. Probs is memory consuming and must be used with
339: parcimony.
340: Version 0.95a3 (should output exactly the same maximization than 0.8a2)
341:
342: Revision 1.83 2003/06/10 13:39:11 lievre
343: *** empty log message ***
344:
345: Revision 1.82 2003/06/05 15:57:20 brouard
346: Add log in imach.c and fullversion number is now printed.
347:
348: */
349: /*
350: Interpolated Markov Chain
351:
352: Short summary of the programme:
353:
354: This program computes Healthy Life Expectancies from
355: cross-longitudinal data. Cross-longitudinal data consist in: -1- a
356: first survey ("cross") where individuals from different ages are
357: interviewed on their health status or degree of disability (in the
358: case of a health survey which is our main interest) -2- at least a
359: second wave of interviews ("longitudinal") which measure each change
360: (if any) in individual health status. Health expectancies are
361: computed from the time spent in each health state according to a
362: model. More health states you consider, more time is necessary to reach the
363: Maximum Likelihood of the parameters involved in the model. The
364: simplest model is the multinomial logistic model where pij is the
365: probability to be observed in state j at the second wave
366: conditional to be observed in state i at the first wave. Therefore
367: the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
368: 'age' is age and 'sex' is a covariate. If you want to have a more
369: complex model than "constant and age", you should modify the program
370: where the markup *Covariates have to be included here again* invites
371: you to do it. More covariates you add, slower the
372: convergence.
373:
374: The advantage of this computer programme, compared to a simple
375: multinomial logistic model, is clear when the delay between waves is not
376: identical for each individual. Also, if a individual missed an
377: intermediate interview, the information is lost, but taken into
378: account using an interpolation or extrapolation.
379:
380: hPijx is the probability to be observed in state i at age x+h
381: conditional to the observed state i at age x. The delay 'h' can be
382: split into an exact number (nh*stepm) of unobserved intermediate
383: states. This elementary transition (by month, quarter,
384: semester or year) is modelled as a multinomial logistic. The hPx
385: matrix is simply the matrix product of nh*stepm elementary matrices
386: and the contribution of each individual to the likelihood is simply
387: hPijx.
388:
389: Also this programme outputs the covariance matrix of the parameters but also
390: of the life expectancies. It also computes the period (stable) prevalence.
391:
392: Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
393: Institut national d'études démographiques, Paris.
394: This software have been partly granted by Euro-REVES, a concerted action
395: from the European Union.
396: It is copyrighted identically to a GNU software product, ie programme and
397: software can be distributed freely for non commercial use. Latest version
398: can be accessed at http://euroreves.ined.fr/imach .
399:
400: Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
401: or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
402:
403: **********************************************************************/
404: /*
405: main
406: read parameterfile
407: read datafile
408: concatwav
409: freqsummary
410: if (mle >= 1)
411: mlikeli
412: print results files
413: if mle==1
414: computes hessian
415: read end of parameter file: agemin, agemax, bage, fage, estepm
416: begin-prev-date,...
417: open gnuplot file
418: open html file
419: period (stable) prevalence | pl_nom 1-1 2-2 etc by covariate
420: for age prevalim() | #****** V1=0 V2=1 V3=1 V4=0 ******
421: | 65 1 0 2 1 3 1 4 0 0.96326 0.03674
422: freexexit2 possible for memory heap.
423:
424: h Pij x | pij_nom ficrestpij
425: # Cov Agex agex+h hpijx with i,j= 1-1 1-2 1-3 2-1 2-2 2-3
426: 1 85 85 1.00000 0.00000 0.00000 0.00000 1.00000 0.00000
427: 1 85 86 0.68299 0.22291 0.09410 0.71093 0.00000 0.28907
428:
429: 1 65 99 0.00364 0.00322 0.99314 0.00350 0.00310 0.99340
430: 1 65 100 0.00214 0.00204 0.99581 0.00206 0.00196 0.99597
431: variance of p one-step probabilities varprob | prob_nom ficresprob #One-step probabilities and stand. devi in ()
432: Standard deviation of one-step probabilities | probcor_nom ficresprobcor #One-step probabilities and correlation matrix
433: Matrix of variance covariance of one-step probabilities | probcov_nom ficresprobcov #One-step probabilities and covariance matrix
434:
435: forecasting if prevfcast==1 prevforecast call prevalence()
436: health expectancies
437: Variance-covariance of DFLE
438: prevalence()
439: movingaverage()
440: varevsij()
441: if popbased==1 varevsij(,popbased)
442: total life expectancies
443: Variance of period (stable) prevalence
444: end
445: */
446:
447:
448:
449:
450: #include <math.h>
451: #include <stdio.h>
452: #include <stdlib.h>
453: #include <string.h>
454: #include <unistd.h>
455:
456: #include <limits.h>
457: #include <sys/types.h>
458: #include <sys/stat.h>
459: #include <errno.h>
460: extern int errno;
461:
462: #ifdef LINUX
463: #include <time.h>
464: #include "timeval.h"
465: #else
466: #include <sys/time.h>
467: #endif
468:
469: #ifdef GSL
470: #include <gsl/gsl_errno.h>
471: #include <gsl/gsl_multimin.h>
472: #endif
473:
474: /* #include <libintl.h> */
475: /* #define _(String) gettext (String) */
476:
477: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
478:
479: #define GNUPLOTPROGRAM "gnuplot"
480: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
481: #define FILENAMELENGTH 132
482:
483: #define GLOCK_ERROR_NOPATH -1 /* empty path */
484: #define GLOCK_ERROR_GETCWD -2 /* cannot get cwd */
485:
486: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
487: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
488:
489: #define NINTERVMAX 8
490: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
491: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
492: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
493: #define codtabm(h,k) 1 & (h-1) >> (k-1) ;
494: #define MAXN 20000
495: #define YEARM 12. /**< Number of months per year */
496: #define AGESUP 130
497: #define AGEBASE 40
498: #define AGEGOMP 10. /**< Minimal age for Gompertz adjustment */
499: #ifdef UNIX
500: #define DIRSEPARATOR '/'
501: #define CHARSEPARATOR "/"
502: #define ODIRSEPARATOR '\\'
503: #else
504: #define DIRSEPARATOR '\\'
505: #define CHARSEPARATOR "\\"
506: #define ODIRSEPARATOR '/'
507: #endif
508:
509: /* $Id: imach.c,v 1.152 2014/06/18 17:54:09 brouard Exp $ */
510: /* $State: Exp $ */
511:
512: char version[]="Imach version 0.98nT, January 2014,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121)";
513: char fullversion[]="$Revision: 1.152 $ $Date: 2014/06/18 17:54:09 $";
514: char strstart[80];
515: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
516: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings */
517: int nvar=0, nforce=0; /* Number of variables, number of forces */
518: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
519: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
520: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
521: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
522: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
523: int cptcovprodnoage=0; /**< Number of covariate products without age */
524: int cptcoveff=0; /* Total number of covariates to vary for printing results */
525: int cptcov=0; /* Working variable */
526: int npar=NPARMAX;
527: int nlstate=2; /* Number of live states */
528: int ndeath=1; /* Number of dead states */
529: int ncovmodel=0, ncovcol=0; /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
530: int popbased=0;
531:
532: int *wav; /* Number of waves for this individuual 0 is possible */
533: int maxwav=0; /* Maxim number of waves */
534: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
535: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */
536: int gipmx=0, gsw=0; /* Global variables on the number of contributions
537: to the likelihood and the sum of weights (done by funcone)*/
538: int mle=1, weightopt=0;
539: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
540: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
541: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
542: * wave mi and wave mi+1 is not an exact multiple of stepm. */
543: double jmean=1; /* Mean space between 2 waves */
544: double **matprod2(); /* test */
545: double **oldm, **newm, **savm; /* Working pointers to matrices */
546: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
547: /*FILE *fic ; */ /* Used in readdata only */
548: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
549: FILE *ficlog, *ficrespow;
550: int globpr=0; /* Global variable for printing or not */
551: double fretone; /* Only one call to likelihood */
552: long ipmx=0; /* Number of contributions */
553: double sw; /* Sum of weights */
554: char filerespow[FILENAMELENGTH];
555: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
556: FILE *ficresilk;
557: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
558: FILE *ficresprobmorprev;
559: FILE *fichtm, *fichtmcov; /* Html File */
560: FILE *ficreseij;
561: char filerese[FILENAMELENGTH];
562: FILE *ficresstdeij;
563: char fileresstde[FILENAMELENGTH];
564: FILE *ficrescveij;
565: char filerescve[FILENAMELENGTH];
566: FILE *ficresvij;
567: char fileresv[FILENAMELENGTH];
568: FILE *ficresvpl;
569: char fileresvpl[FILENAMELENGTH];
570: char title[MAXLINE];
571: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH], filerespl[FILENAMELENGTH];
572: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
573: char tmpout[FILENAMELENGTH], tmpout2[FILENAMELENGTH];
574: char command[FILENAMELENGTH];
575: int outcmd=0;
576:
577: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
578:
579: char filelog[FILENAMELENGTH]; /* Log file */
580: char filerest[FILENAMELENGTH];
581: char fileregp[FILENAMELENGTH];
582: char popfile[FILENAMELENGTH];
583:
584: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
585:
586: struct timeval start_time, end_time, curr_time, last_time, forecast_time;
587: struct timezone tzp;
588: extern int gettimeofday();
589: struct tm tmg, tm, tmf, *gmtime(), *localtime();
590: long time_value;
591: extern long time();
592: char strcurr[80], strfor[80];
593:
594: char *endptr;
595: long lval;
596: double dval;
597:
598: #define NR_END 1
599: #define FREE_ARG char*
600: #define FTOL 1.0e-10
601:
602: #define NRANSI
603: #define ITMAX 200
604:
605: #define TOL 2.0e-4
606:
607: #define CGOLD 0.3819660
608: #define ZEPS 1.0e-10
609: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
610:
611: #define GOLD 1.618034
612: #define GLIMIT 100.0
613: #define TINY 1.0e-20
614:
615: static double maxarg1,maxarg2;
616: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
617: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
618:
619: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
620: #define rint(a) floor(a+0.5)
621:
622: static double sqrarg;
623: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
624: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
625: int agegomp= AGEGOMP;
626:
627: int imx;
628: int stepm=1;
629: /* Stepm, step in month: minimum step interpolation*/
630:
631: int estepm;
632: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
633:
634: int m,nb;
635: long *num;
636: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
637: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
638: double **pmmij, ***probs;
639: double *ageexmed,*agecens;
640: double dateintmean=0;
641:
642: double *weight;
643: int **s; /* Status */
644: double *agedc;
645: double **covar; /**< covar[j,i], value of jth covariate for individual i,
646: * covar=matrix(0,NCOVMAX,1,n);
647: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; */
648: double idx;
649: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
650: int *Ndum; /** Freq of modality (tricode */
651: int **codtab; /**< codtab=imatrix(1,100,1,10); */
652: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
653: double *lsurv, *lpop, *tpop;
654:
655: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
656: double ftolhess; /**< Tolerance for computing hessian */
657:
658: /**************** split *************************/
659: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
660: {
661: /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
662: the name of the file (name), its extension only (ext) and its first part of the name (finame)
663: */
664: char *ss; /* pointer */
665: int l1, l2; /* length counters */
666:
667: l1 = strlen(path ); /* length of path */
668: if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
669: ss= strrchr( path, DIRSEPARATOR ); /* find last / */
670: if ( ss == NULL ) { /* no directory, so determine current directory */
671: strcpy( name, path ); /* we got the fullname name because no directory */
672: /*if(strrchr(path, ODIRSEPARATOR )==NULL)
673: printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
674: /* get current working directory */
675: /* extern char* getcwd ( char *buf , int len);*/
676: if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
677: return( GLOCK_ERROR_GETCWD );
678: }
679: /* got dirc from getcwd*/
680: printf(" DIRC = %s \n",dirc);
681: } else { /* strip direcotry from path */
682: ss++; /* after this, the filename */
683: l2 = strlen( ss ); /* length of filename */
684: if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
685: strcpy( name, ss ); /* save file name */
686: strncpy( dirc, path, l1 - l2 ); /* now the directory */
687: dirc[l1-l2] = 0; /* add zero */
688: printf(" DIRC2 = %s \n",dirc);
689: }
690: /* We add a separator at the end of dirc if not exists */
691: l1 = strlen( dirc ); /* length of directory */
692: if( dirc[l1-1] != DIRSEPARATOR ){
693: dirc[l1] = DIRSEPARATOR;
694: dirc[l1+1] = 0;
695: printf(" DIRC3 = %s \n",dirc);
696: }
697: ss = strrchr( name, '.' ); /* find last / */
698: if (ss >0){
699: ss++;
700: strcpy(ext,ss); /* save extension */
701: l1= strlen( name);
702: l2= strlen(ss)+1;
703: strncpy( finame, name, l1-l2);
704: finame[l1-l2]= 0;
705: }
706:
707: return( 0 ); /* we're done */
708: }
709:
710:
711: /******************************************/
712:
713: void replace_back_to_slash(char *s, char*t)
714: {
715: int i;
716: int lg=0;
717: i=0;
718: lg=strlen(t);
719: for(i=0; i<= lg; i++) {
720: (s[i] = t[i]);
721: if (t[i]== '\\') s[i]='/';
722: }
723: }
724:
725: char *trimbb(char *out, char *in)
726: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
727: char *s;
728: s=out;
729: while (*in != '\0'){
730: while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
731: in++;
732: }
733: *out++ = *in++;
734: }
735: *out='\0';
736: return s;
737: }
738:
739: char *cutl(char *blocc, char *alocc, char *in, char occ)
740: {
741: /* cuts string in into blocc and alocc where blocc ends before first occurence of char 'occ'
742: and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
743: gives blocc="abcdef2ghi" and alocc="j".
744: If occ is not found blocc is null and alocc is equal to in. Returns blocc
745: */
746: char *s, *t, *bl;
747: t=in;s=in;
748: while ((*in != occ) && (*in != '\0')){
749: *alocc++ = *in++;
750: }
751: if( *in == occ){
752: *(alocc)='\0';
753: s=++in;
754: }
755:
756: if (s == t) {/* occ not found */
757: *(alocc-(in-s))='\0';
758: in=s;
759: }
760: while ( *in != '\0'){
761: *blocc++ = *in++;
762: }
763:
764: *blocc='\0';
765: return t;
766: }
767: char *cutv(char *blocc, char *alocc, char *in, char occ)
768: {
769: /* cuts string in into blocc and alocc where blocc ends before last occurence of char 'occ'
770: and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
771: gives blocc="abcdef2ghi" and alocc="j".
772: If occ is not found blocc is null and alocc is equal to in. Returns alocc
773: */
774: char *s, *t;
775: t=in;s=in;
776: while (*in != '\0'){
777: while( *in == occ){
778: *blocc++ = *in++;
779: s=in;
780: }
781: *blocc++ = *in++;
782: }
783: if (s == t) /* occ not found */
784: *(blocc-(in-s))='\0';
785: else
786: *(blocc-(in-s)-1)='\0';
787: in=s;
788: while ( *in != '\0'){
789: *alocc++ = *in++;
790: }
791:
792: *alocc='\0';
793: return s;
794: }
795:
796: int nbocc(char *s, char occ)
797: {
798: int i,j=0;
799: int lg=20;
800: i=0;
801: lg=strlen(s);
802: for(i=0; i<= lg; i++) {
803: if (s[i] == occ ) j++;
804: }
805: return j;
806: }
807:
808: /* void cutv(char *u,char *v, char*t, char occ) */
809: /* { */
810: /* /\* cuts string t into u and v where u ends before last occurence of char 'occ' */
811: /* and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
812: /* gives u="abcdef2ghi" and v="j" *\/ */
813: /* int i,lg,j,p=0; */
814: /* i=0; */
815: /* lg=strlen(t); */
816: /* for(j=0; j<=lg-1; j++) { */
817: /* if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
818: /* } */
819:
820: /* for(j=0; j<p; j++) { */
821: /* (u[j] = t[j]); */
822: /* } */
823: /* u[p]='\0'; */
824:
825: /* for(j=0; j<= lg; j++) { */
826: /* if (j>=(p+1))(v[j-p-1] = t[j]); */
827: /* } */
828: /* } */
829:
830: /********************** nrerror ********************/
831:
832: void nrerror(char error_text[])
833: {
834: fprintf(stderr,"ERREUR ...\n");
835: fprintf(stderr,"%s\n",error_text);
836: exit(EXIT_FAILURE);
837: }
838: /*********************** vector *******************/
839: double *vector(int nl, int nh)
840: {
841: double *v;
842: v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
843: if (!v) nrerror("allocation failure in vector");
844: return v-nl+NR_END;
845: }
846:
847: /************************ free vector ******************/
848: void free_vector(double*v, int nl, int nh)
849: {
850: free((FREE_ARG)(v+nl-NR_END));
851: }
852:
853: /************************ivector *******************************/
854: int *ivector(long nl,long nh)
855: {
856: int *v;
857: v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
858: if (!v) nrerror("allocation failure in ivector");
859: return v-nl+NR_END;
860: }
861:
862: /******************free ivector **************************/
863: void free_ivector(int *v, long nl, long nh)
864: {
865: free((FREE_ARG)(v+nl-NR_END));
866: }
867:
868: /************************lvector *******************************/
869: long *lvector(long nl,long nh)
870: {
871: long *v;
872: v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
873: if (!v) nrerror("allocation failure in ivector");
874: return v-nl+NR_END;
875: }
876:
877: /******************free lvector **************************/
878: void free_lvector(long *v, long nl, long nh)
879: {
880: free((FREE_ARG)(v+nl-NR_END));
881: }
882:
883: /******************* imatrix *******************************/
884: int **imatrix(long nrl, long nrh, long ncl, long nch)
885: /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
886: {
887: long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
888: int **m;
889:
890: /* allocate pointers to rows */
891: m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
892: if (!m) nrerror("allocation failure 1 in matrix()");
893: m += NR_END;
894: m -= nrl;
895:
896:
897: /* allocate rows and set pointers to them */
898: m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
899: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
900: m[nrl] += NR_END;
901: m[nrl] -= ncl;
902:
903: for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
904:
905: /* return pointer to array of pointers to rows */
906: return m;
907: }
908:
909: /****************** free_imatrix *************************/
910: void free_imatrix(m,nrl,nrh,ncl,nch)
911: int **m;
912: long nch,ncl,nrh,nrl;
913: /* free an int matrix allocated by imatrix() */
914: {
915: free((FREE_ARG) (m[nrl]+ncl-NR_END));
916: free((FREE_ARG) (m+nrl-NR_END));
917: }
918:
919: /******************* matrix *******************************/
920: double **matrix(long nrl, long nrh, long ncl, long nch)
921: {
922: long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
923: double **m;
924:
925: m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
926: if (!m) nrerror("allocation failure 1 in matrix()");
927: m += NR_END;
928: m -= nrl;
929:
930: m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
931: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
932: m[nrl] += NR_END;
933: m[nrl] -= ncl;
934:
935: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
936: return m;
937: /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
938: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
939: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
940: */
941: }
942:
943: /*************************free matrix ************************/
944: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
945: {
946: free((FREE_ARG)(m[nrl]+ncl-NR_END));
947: free((FREE_ARG)(m+nrl-NR_END));
948: }
949:
950: /******************* ma3x *******************************/
951: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
952: {
953: long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
954: double ***m;
955:
956: m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
957: if (!m) nrerror("allocation failure 1 in matrix()");
958: m += NR_END;
959: m -= nrl;
960:
961: m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
962: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
963: m[nrl] += NR_END;
964: m[nrl] -= ncl;
965:
966: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
967:
968: m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
969: if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
970: m[nrl][ncl] += NR_END;
971: m[nrl][ncl] -= nll;
972: for (j=ncl+1; j<=nch; j++)
973: m[nrl][j]=m[nrl][j-1]+nlay;
974:
975: for (i=nrl+1; i<=nrh; i++) {
976: m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
977: for (j=ncl+1; j<=nch; j++)
978: m[i][j]=m[i][j-1]+nlay;
979: }
980: return m;
981: /* gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
982: &(m[i][j][k]) <=> *((*(m+i) + j)+k)
983: */
984: }
985:
986: /*************************free ma3x ************************/
987: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
988: {
989: free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
990: free((FREE_ARG)(m[nrl]+ncl-NR_END));
991: free((FREE_ARG)(m+nrl-NR_END));
992: }
993:
994: /*************** function subdirf ***********/
995: char *subdirf(char fileres[])
996: {
997: /* Caution optionfilefiname is hidden */
998: strcpy(tmpout,optionfilefiname);
999: strcat(tmpout,"/"); /* Add to the right */
1000: strcat(tmpout,fileres);
1001: return tmpout;
1002: }
1003:
1004: /*************** function subdirf2 ***********/
1005: char *subdirf2(char fileres[], char *preop)
1006: {
1007:
1008: /* Caution optionfilefiname is hidden */
1009: strcpy(tmpout,optionfilefiname);
1010: strcat(tmpout,"/");
1011: strcat(tmpout,preop);
1012: strcat(tmpout,fileres);
1013: return tmpout;
1014: }
1015:
1016: /*************** function subdirf3 ***********/
1017: char *subdirf3(char fileres[], char *preop, char *preop2)
1018: {
1019:
1020: /* Caution optionfilefiname is hidden */
1021: strcpy(tmpout,optionfilefiname);
1022: strcat(tmpout,"/");
1023: strcat(tmpout,preop);
1024: strcat(tmpout,preop2);
1025: strcat(tmpout,fileres);
1026: return tmpout;
1027: }
1028:
1029: /***************** f1dim *************************/
1030: extern int ncom;
1031: extern double *pcom,*xicom;
1032: extern double (*nrfunc)(double []);
1033:
1034: double f1dim(double x)
1035: {
1036: int j;
1037: double f;
1038: double *xt;
1039:
1040: xt=vector(1,ncom);
1041: for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
1042: f=(*nrfunc)(xt);
1043: free_vector(xt,1,ncom);
1044: return f;
1045: }
1046:
1047: /*****************brent *************************/
1048: double brent(double ax, double bx, double cx, double (*f)(double), double tol, double *xmin)
1049: {
1050: int iter;
1051: double a,b,d,etemp;
1052: double fu,fv,fw,fx;
1053: double ftemp;
1054: double p,q,r,tol1,tol2,u,v,w,x,xm;
1055: double e=0.0;
1056:
1057: a=(ax < cx ? ax : cx);
1058: b=(ax > cx ? ax : cx);
1059: x=w=v=bx;
1060: fw=fv=fx=(*f)(x);
1061: for (iter=1;iter<=ITMAX;iter++) {
1062: xm=0.5*(a+b);
1063: tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
1064: /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
1065: printf(".");fflush(stdout);
1066: fprintf(ficlog,".");fflush(ficlog);
1067: #ifdef DEBUG
1068: 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);
1069: 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);
1070: /* if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
1071: #endif
1072: if (fabs(x-xm) <= (tol2-0.5*(b-a))){
1073: *xmin=x;
1074: return fx;
1075: }
1076: ftemp=fu;
1077: if (fabs(e) > tol1) {
1078: r=(x-w)*(fx-fv);
1079: q=(x-v)*(fx-fw);
1080: p=(x-v)*q-(x-w)*r;
1081: q=2.0*(q-r);
1082: if (q > 0.0) p = -p;
1083: q=fabs(q);
1084: etemp=e;
1085: e=d;
1086: if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
1087: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1088: else {
1089: d=p/q;
1090: u=x+d;
1091: if (u-a < tol2 || b-u < tol2)
1092: d=SIGN(tol1,xm-x);
1093: }
1094: } else {
1095: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1096: }
1097: u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
1098: fu=(*f)(u);
1099: if (fu <= fx) {
1100: if (u >= x) a=x; else b=x;
1101: SHFT(v,w,x,u)
1102: SHFT(fv,fw,fx,fu)
1103: } else {
1104: if (u < x) a=u; else b=u;
1105: if (fu <= fw || w == x) {
1106: v=w;
1107: w=u;
1108: fv=fw;
1109: fw=fu;
1110: } else if (fu <= fv || v == x || v == w) {
1111: v=u;
1112: fv=fu;
1113: }
1114: }
1115: }
1116: nrerror("Too many iterations in brent");
1117: *xmin=x;
1118: return fx;
1119: }
1120:
1121: /****************** mnbrak ***********************/
1122:
1123: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
1124: double (*func)(double))
1125: {
1126: double ulim,u,r,q, dum;
1127: double fu;
1128:
1129: *fa=(*func)(*ax);
1130: *fb=(*func)(*bx);
1131: if (*fb > *fa) {
1132: SHFT(dum,*ax,*bx,dum)
1133: SHFT(dum,*fb,*fa,dum)
1134: }
1135: *cx=(*bx)+GOLD*(*bx-*ax);
1136: *fc=(*func)(*cx);
1137: while (*fb > *fc) {
1138: r=(*bx-*ax)*(*fb-*fc);
1139: q=(*bx-*cx)*(*fb-*fa);
1140: u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
1141: (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r));
1142: ulim=(*bx)+GLIMIT*(*cx-*bx);
1143: if ((*bx-u)*(u-*cx) > 0.0) {
1144: fu=(*func)(u);
1145: } else if ((*cx-u)*(u-ulim) > 0.0) {
1146: fu=(*func)(u);
1147: if (fu < *fc) {
1148: SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
1149: SHFT(*fb,*fc,fu,(*func)(u))
1150: }
1151: } else if ((u-ulim)*(ulim-*cx) >= 0.0) {
1152: u=ulim;
1153: fu=(*func)(u);
1154: } else {
1155: u=(*cx)+GOLD*(*cx-*bx);
1156: fu=(*func)(u);
1157: }
1158: SHFT(*ax,*bx,*cx,u)
1159: SHFT(*fa,*fb,*fc,fu)
1160: }
1161: }
1162:
1163: /*************** linmin ************************/
1164:
1165: int ncom;
1166: double *pcom,*xicom;
1167: double (*nrfunc)(double []);
1168:
1169: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
1170: {
1171: double brent(double ax, double bx, double cx,
1172: double (*f)(double), double tol, double *xmin);
1173: double f1dim(double x);
1174: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
1175: double *fc, double (*func)(double));
1176: int j;
1177: double xx,xmin,bx,ax;
1178: double fx,fb,fa;
1179:
1180: ncom=n;
1181: pcom=vector(1,n);
1182: xicom=vector(1,n);
1183: nrfunc=func;
1184: for (j=1;j<=n;j++) {
1185: pcom[j]=p[j];
1186: xicom[j]=xi[j];
1187: }
1188: ax=0.0;
1189: xx=1.0;
1190: mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);
1191: *fret=brent(ax,xx,bx,f1dim,TOL,&xmin);
1192: #ifdef DEBUG
1193: printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1194: fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1195: #endif
1196: for (j=1;j<=n;j++) {
1197: xi[j] *= xmin;
1198: p[j] += xi[j];
1199: }
1200: free_vector(xicom,1,n);
1201: free_vector(pcom,1,n);
1202: }
1203:
1204: char *asc_diff_time(long time_sec, char ascdiff[])
1205: {
1206: long sec_left, days, hours, minutes;
1207: days = (time_sec) / (60*60*24);
1208: sec_left = (time_sec) % (60*60*24);
1209: hours = (sec_left) / (60*60) ;
1210: sec_left = (sec_left) %(60*60);
1211: minutes = (sec_left) /60;
1212: sec_left = (sec_left) % (60);
1213: sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);
1214: return ascdiff;
1215: }
1216:
1217: /*************** powell ************************/
1218: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
1219: double (*func)(double []))
1220: {
1221: void linmin(double p[], double xi[], int n, double *fret,
1222: double (*func)(double []));
1223: int i,ibig,j;
1224: double del,t,*pt,*ptt,*xit;
1225: double fp,fptt;
1226: double *xits;
1227: int niterf, itmp;
1228:
1229: pt=vector(1,n);
1230: ptt=vector(1,n);
1231: xit=vector(1,n);
1232: xits=vector(1,n);
1233: *fret=(*func)(p);
1234: for (j=1;j<=n;j++) pt[j]=p[j];
1235: for (*iter=1;;++(*iter)) {
1236: fp=(*fret);
1237: ibig=0;
1238: del=0.0;
1239: last_time=curr_time;
1240: (void) gettimeofday(&curr_time,&tzp);
1241: printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, curr_time.tv_sec-last_time.tv_sec, curr_time.tv_sec-start_time.tv_sec);fflush(stdout);
1242: fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, curr_time.tv_sec-last_time.tv_sec, curr_time.tv_sec-start_time.tv_sec); fflush(ficlog);
1243: /* fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tv_sec-start_time.tv_sec); */
1244: for (i=1;i<=n;i++) {
1245: printf(" %d %.12f",i, p[i]);
1246: fprintf(ficlog," %d %.12lf",i, p[i]);
1247: fprintf(ficrespow," %.12lf", p[i]);
1248: }
1249: printf("\n");
1250: fprintf(ficlog,"\n");
1251: fprintf(ficrespow,"\n");fflush(ficrespow);
1252: if(*iter <=3){
1253: tm = *localtime(&curr_time.tv_sec);
1254: strcpy(strcurr,asctime(&tm));
1255: /* asctime_r(&tm,strcurr); */
1256: forecast_time=curr_time;
1257: itmp = strlen(strcurr);
1258: if(strcurr[itmp-1]=='\n') /* Windows outputs with a new line */
1259: strcurr[itmp-1]='\0';
1260: printf("\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);
1261: fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);
1262: for(niterf=10;niterf<=30;niterf+=10){
1263: forecast_time.tv_sec=curr_time.tv_sec+(niterf-*iter)*(curr_time.tv_sec-last_time.tv_sec);
1264: tmf = *localtime(&forecast_time.tv_sec);
1265: /* asctime_r(&tmf,strfor); */
1266: strcpy(strfor,asctime(&tmf));
1267: itmp = strlen(strfor);
1268: if(strfor[itmp-1]=='\n')
1269: strfor[itmp-1]='\0';
1270: 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(forecast_time.tv_sec-curr_time.tv_sec,tmpout),strfor,strcurr);
1271: 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(forecast_time.tv_sec-curr_time.tv_sec,tmpout),strfor,strcurr);
1272: }
1273: }
1274: for (i=1;i<=n;i++) {
1275: for (j=1;j<=n;j++) xit[j]=xi[j][i];
1276: fptt=(*fret);
1277: #ifdef DEBUG
1278: printf("fret=%lf \n",*fret);
1279: fprintf(ficlog,"fret=%lf \n",*fret);
1280: #endif
1281: printf("%d",i);fflush(stdout);
1282: fprintf(ficlog,"%d",i);fflush(ficlog);
1283: linmin(p,xit,n,fret,func);
1284: if (fabs(fptt-(*fret)) > del) {
1285: del=fabs(fptt-(*fret));
1286: ibig=i;
1287: }
1288: #ifdef DEBUG
1289: printf("%d %.12e",i,(*fret));
1290: fprintf(ficlog,"%d %.12e",i,(*fret));
1291: for (j=1;j<=n;j++) {
1292: xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
1293: printf(" x(%d)=%.12e",j,xit[j]);
1294: fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1295: }
1296: for(j=1;j<=n;j++) {
1297: printf(" p=%.12e",p[j]);
1298: fprintf(ficlog," p=%.12e",p[j]);
1299: }
1300: printf("\n");
1301: fprintf(ficlog,"\n");
1302: #endif
1303: }
1304: if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
1305: #ifdef DEBUG
1306: int k[2],l;
1307: k[0]=1;
1308: k[1]=-1;
1309: printf("Max: %.12e",(*func)(p));
1310: fprintf(ficlog,"Max: %.12e",(*func)(p));
1311: for (j=1;j<=n;j++) {
1312: printf(" %.12e",p[j]);
1313: fprintf(ficlog," %.12e",p[j]);
1314: }
1315: printf("\n");
1316: fprintf(ficlog,"\n");
1317: for(l=0;l<=1;l++) {
1318: for (j=1;j<=n;j++) {
1319: ptt[j]=p[j]+(p[j]-pt[j])*k[l];
1320: printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1321: fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1322: }
1323: printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1324: fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1325: }
1326: #endif
1327:
1328:
1329: free_vector(xit,1,n);
1330: free_vector(xits,1,n);
1331: free_vector(ptt,1,n);
1332: free_vector(pt,1,n);
1333: return;
1334: }
1335: if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
1336: for (j=1;j<=n;j++) {
1337: ptt[j]=2.0*p[j]-pt[j];
1338: xit[j]=p[j]-pt[j];
1339: pt[j]=p[j];
1340: }
1341: fptt=(*func)(ptt);
1342: if (fptt < fp) {
1343: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt);
1344: if (t < 0.0) {
1345: linmin(p,xit,n,fret,func);
1346: for (j=1;j<=n;j++) {
1347: xi[j][ibig]=xi[j][n];
1348: xi[j][n]=xit[j];
1349: }
1350: #ifdef DEBUG
1351: printf("Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1352: fprintf(ficlog,"Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1353: for(j=1;j<=n;j++){
1354: printf(" %.12e",xit[j]);
1355: fprintf(ficlog," %.12e",xit[j]);
1356: }
1357: printf("\n");
1358: fprintf(ficlog,"\n");
1359: #endif
1360: }
1361: }
1362: }
1363: }
1364:
1365: /**** Prevalence limit (stable or period prevalence) ****************/
1366:
1367: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
1368: {
1369: /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1370: matrix by transitions matrix until convergence is reached */
1371:
1372: int i, ii,j,k;
1373: double min, max, maxmin, maxmax,sumnew=0.;
1374: /* double **matprod2(); */ /* test */
1375: double **out, cov[NCOVMAX+1], **pmij();
1376: double **newm;
1377: double agefin, delaymax=50 ; /* Max number of years to converge */
1378:
1379: for (ii=1;ii<=nlstate+ndeath;ii++)
1380: for (j=1;j<=nlstate+ndeath;j++){
1381: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1382: }
1383:
1384: cov[1]=1.;
1385:
1386: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1387: for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1388: newm=savm;
1389: /* Covariates have to be included here again */
1390: cov[2]=agefin;
1391:
1392: for (k=1; k<=cptcovn;k++) {
1393: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1394: /*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]]);*/
1395: }
1396: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1397: /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
1398: /* cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]] * nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]]; */
1399:
1400: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
1401: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
1402: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1403: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1404: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1405: out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1406:
1407: savm=oldm;
1408: oldm=newm;
1409: maxmax=0.;
1410: for(j=1;j<=nlstate;j++){
1411: min=1.;
1412: max=0.;
1413: for(i=1; i<=nlstate; i++) {
1414: sumnew=0;
1415: for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
1416: prlim[i][j]= newm[i][j]/(1-sumnew);
1417: /*printf(" prevalim i=%d, j=%d, prmlim[%d][%d]=%f, agefin=%d \n", i, j, i, j, prlim[i][j],(int)agefin);*/
1418: max=FMAX(max,prlim[i][j]);
1419: min=FMIN(min,prlim[i][j]);
1420: }
1421: maxmin=max-min;
1422: maxmax=FMAX(maxmax,maxmin);
1423: }
1424: if(maxmax < ftolpl){
1425: return prlim;
1426: }
1427: }
1428: }
1429:
1430: /*************** transition probabilities ***************/
1431:
1432: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1433: {
1434: /* According to parameters values stored in x and the covariate's values stored in cov,
1435: computes the probability to be observed in state j being in state i by appying the
1436: model to the ncovmodel covariates (including constant and age).
1437: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
1438: and, according on how parameters are entered, the position of the coefficient xij(nc) of the
1439: ncth covariate in the global vector x is given by the formula:
1440: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
1441: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
1442: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
1443: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1444: Outputs ps[i][j] the probability to be observed in j being in j according to
1445: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1446: */
1447: double s1, lnpijopii;
1448: /*double t34;*/
1449: int i,j,j1, nc, ii, jj;
1450:
1451: for(i=1; i<= nlstate; i++){
1452: for(j=1; j<i;j++){
1453: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1454: /*lnpijopii += param[i][j][nc]*cov[nc];*/
1455: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
1456: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1457: }
1458: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1459: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1460: }
1461: for(j=i+1; j<=nlstate+ndeath;j++){
1462: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1463: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
1464: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
1465: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1466: }
1467: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1468: }
1469: }
1470:
1471: for(i=1; i<= nlstate; i++){
1472: s1=0;
1473: for(j=1; j<i; j++){
1474: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1475: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1476: }
1477: for(j=i+1; j<=nlstate+ndeath; j++){
1478: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1479: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1480: }
1481: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1482: ps[i][i]=1./(s1+1.);
1483: /* Computing other pijs */
1484: for(j=1; j<i; j++)
1485: ps[i][j]= exp(ps[i][j])*ps[i][i];
1486: for(j=i+1; j<=nlstate+ndeath; j++)
1487: ps[i][j]= exp(ps[i][j])*ps[i][i];
1488: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
1489: } /* end i */
1490:
1491: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
1492: for(jj=1; jj<= nlstate+ndeath; jj++){
1493: ps[ii][jj]=0;
1494: ps[ii][ii]=1;
1495: }
1496: }
1497:
1498:
1499: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
1500: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */
1501: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
1502: /* } */
1503: /* printf("\n "); */
1504: /* } */
1505: /* printf("\n ");printf("%lf ",cov[2]);*/
1506: /*
1507: for(i=1; i<= npar; i++) printf("%f ",x[i]);
1508: goto end;*/
1509: return ps;
1510: }
1511:
1512: /**************** Product of 2 matrices ******************/
1513:
1514: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1515: {
1516: /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
1517: b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
1518: /* in, b, out are matrice of pointers which should have been initialized
1519: before: only the contents of out is modified. The function returns
1520: a pointer to pointers identical to out */
1521: int i, j, k;
1522: for(i=nrl; i<= nrh; i++)
1523: for(k=ncolol; k<=ncoloh; k++){
1524: out[i][k]=0.;
1525: for(j=ncl; j<=nch; j++)
1526: out[i][k] +=in[i][j]*b[j][k];
1527: }
1528: return out;
1529: }
1530:
1531:
1532: /************* Higher Matrix Product ***************/
1533:
1534: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
1535: {
1536: /* Computes the transition matrix starting at age 'age' over
1537: 'nhstepm*hstepm*stepm' months (i.e. until
1538: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
1539: nhstepm*hstepm matrices.
1540: Output is stored in matrix po[i][j][h] for h every 'hstepm' step
1541: (typically every 2 years instead of every month which is too big
1542: for the memory).
1543: Model is determined by parameters x and covariates have to be
1544: included manually here.
1545:
1546: */
1547:
1548: int i, j, d, h, k;
1549: double **out, cov[NCOVMAX+1];
1550: double **newm;
1551:
1552: /* Hstepm could be zero and should return the unit matrix */
1553: for (i=1;i<=nlstate+ndeath;i++)
1554: for (j=1;j<=nlstate+ndeath;j++){
1555: oldm[i][j]=(i==j ? 1.0 : 0.0);
1556: po[i][j][0]=(i==j ? 1.0 : 0.0);
1557: }
1558: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1559: for(h=1; h <=nhstepm; h++){
1560: for(d=1; d <=hstepm; d++){
1561: newm=savm;
1562: /* Covariates have to be included here again */
1563: cov[1]=1.;
1564: cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
1565: for (k=1; k<=cptcovn;k++)
1566: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1567: for (k=1; k<=cptcovage;k++)
1568: cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
1569: for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1570: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
1571:
1572:
1573: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
1574: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1575: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
1576: pmij(pmmij,cov,ncovmodel,x,nlstate));
1577: savm=oldm;
1578: oldm=newm;
1579: }
1580: for(i=1; i<=nlstate+ndeath; i++)
1581: for(j=1;j<=nlstate+ndeath;j++) {
1582: po[i][j][h]=newm[i][j];
1583: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1584: }
1585: /*printf("h=%d ",h);*/
1586: } /* end h */
1587: /* printf("\n H=%d \n",h); */
1588: return po;
1589: }
1590:
1591:
1592: /*************** log-likelihood *************/
1593: double func( double *x)
1594: {
1595: int i, ii, j, k, mi, d, kk;
1596: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1597: double **out;
1598: double sw; /* Sum of weights */
1599: double lli; /* Individual log likelihood */
1600: int s1, s2;
1601: double bbh, survp;
1602: long ipmx;
1603: /*extern weight */
1604: /* We are differentiating ll according to initial status */
1605: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
1606: /*for(i=1;i<imx;i++)
1607: printf(" %d\n",s[4][i]);
1608: */
1609: cov[1]=1.;
1610:
1611: for(k=1; k<=nlstate; k++) ll[k]=0.;
1612:
1613: if(mle==1){
1614: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1615: /* Computes the values of the ncovmodel covariates of the model
1616: depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
1617: Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
1618: to be observed in j being in i according to the model.
1619: */
1620: for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1621: cov[2+k]=covar[Tvar[k]][i];
1622: }
1623: /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4]
1624: is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]
1625: has been calculated etc */
1626: for(mi=1; mi<= wav[i]-1; mi++){
1627: for (ii=1;ii<=nlstate+ndeath;ii++)
1628: for (j=1;j<=nlstate+ndeath;j++){
1629: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1630: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1631: }
1632: for(d=0; d<dh[mi][i]; d++){
1633: newm=savm;
1634: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1635: for (kk=1; kk<=cptcovage;kk++) {
1636: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; /* Tage[kk] gives the data-covariate associated with age */
1637: }
1638: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1639: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1640: savm=oldm;
1641: oldm=newm;
1642: } /* end mult */
1643:
1644: /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
1645: /* But now since version 0.9 we anticipate for bias at large stepm.
1646: * If stepm is larger than one month (smallest stepm) and if the exact delay
1647: * (in months) between two waves is not a multiple of stepm, we rounded to
1648: * the nearest (and in case of equal distance, to the lowest) interval but now
1649: * we keep into memory the bias bh[mi][i] and also the previous matrix product
1650: * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
1651: * probability in order to take into account the bias as a fraction of the way
1652: * from savm to out if bh is negative or even beyond if bh is positive. bh varies
1653: * -stepm/2 to stepm/2 .
1654: * For stepm=1 the results are the same as for previous versions of Imach.
1655: * For stepm > 1 the results are less biased than in previous versions.
1656: */
1657: s1=s[mw[mi][i]][i];
1658: s2=s[mw[mi+1][i]][i];
1659: bbh=(double)bh[mi][i]/(double)stepm;
1660: /* bias bh is positive if real duration
1661: * is higher than the multiple of stepm and negative otherwise.
1662: */
1663: /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
1664: if( s2 > nlstate){
1665: /* i.e. if s2 is a death state and if the date of death is known
1666: then the contribution to the likelihood is the probability to
1667: die between last step unit time and current step unit time,
1668: which is also equal to probability to die before dh
1669: minus probability to die before dh-stepm .
1670: In version up to 0.92 likelihood was computed
1671: as if date of death was unknown. Death was treated as any other
1672: health state: the date of the interview describes the actual state
1673: and not the date of a change in health state. The former idea was
1674: to consider that at each interview the state was recorded
1675: (healthy, disable or death) and IMaCh was corrected; but when we
1676: introduced the exact date of death then we should have modified
1677: the contribution of an exact death to the likelihood. This new
1678: contribution is smaller and very dependent of the step unit
1679: stepm. It is no more the probability to die between last interview
1680: and month of death but the probability to survive from last
1681: interview up to one month before death multiplied by the
1682: probability to die within a month. Thanks to Chris
1683: Jackson for correcting this bug. Former versions increased
1684: mortality artificially. The bad side is that we add another loop
1685: which slows down the processing. The difference can be up to 10%
1686: lower mortality.
1687: */
1688: lli=log(out[s1][s2] - savm[s1][s2]);
1689:
1690:
1691: } else if (s2==-2) {
1692: for (j=1,survp=0. ; j<=nlstate; j++)
1693: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1694: /*survp += out[s1][j]; */
1695: lli= log(survp);
1696: }
1697:
1698: else if (s2==-4) {
1699: for (j=3,survp=0. ; j<=nlstate; j++)
1700: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1701: lli= log(survp);
1702: }
1703:
1704: else if (s2==-5) {
1705: for (j=1,survp=0. ; j<=2; j++)
1706: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1707: lli= log(survp);
1708: }
1709:
1710: else{
1711: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1712: /* 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 */
1713: }
1714: /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
1715: /*if(lli ==000.0)*/
1716: /*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); */
1717: ipmx +=1;
1718: sw += weight[i];
1719: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1720: } /* end of wave */
1721: } /* end of individual */
1722: } else if(mle==2){
1723: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1724: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1725: for(mi=1; mi<= wav[i]-1; mi++){
1726: for (ii=1;ii<=nlstate+ndeath;ii++)
1727: for (j=1;j<=nlstate+ndeath;j++){
1728: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1729: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1730: }
1731: for(d=0; d<=dh[mi][i]; d++){
1732: newm=savm;
1733: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1734: for (kk=1; kk<=cptcovage;kk++) {
1735: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1736: }
1737: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1738: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1739: savm=oldm;
1740: oldm=newm;
1741: } /* end mult */
1742:
1743: s1=s[mw[mi][i]][i];
1744: s2=s[mw[mi+1][i]][i];
1745: bbh=(double)bh[mi][i]/(double)stepm;
1746: 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 */
1747: ipmx +=1;
1748: sw += weight[i];
1749: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1750: } /* end of wave */
1751: } /* end of individual */
1752: } else if(mle==3){ /* exponential inter-extrapolation */
1753: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1754: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1755: for(mi=1; mi<= wav[i]-1; mi++){
1756: for (ii=1;ii<=nlstate+ndeath;ii++)
1757: for (j=1;j<=nlstate+ndeath;j++){
1758: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1759: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1760: }
1761: for(d=0; d<dh[mi][i]; d++){
1762: newm=savm;
1763: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1764: for (kk=1; kk<=cptcovage;kk++) {
1765: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1766: }
1767: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1768: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1769: savm=oldm;
1770: oldm=newm;
1771: } /* end mult */
1772:
1773: s1=s[mw[mi][i]][i];
1774: s2=s[mw[mi+1][i]][i];
1775: bbh=(double)bh[mi][i]/(double)stepm;
1776: 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 */
1777: ipmx +=1;
1778: sw += weight[i];
1779: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1780: } /* end of wave */
1781: } /* end of individual */
1782: }else if (mle==4){ /* ml=4 no inter-extrapolation */
1783: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1784: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1785: for(mi=1; mi<= wav[i]-1; mi++){
1786: for (ii=1;ii<=nlstate+ndeath;ii++)
1787: for (j=1;j<=nlstate+ndeath;j++){
1788: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1789: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1790: }
1791: for(d=0; d<dh[mi][i]; d++){
1792: newm=savm;
1793: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1794: for (kk=1; kk<=cptcovage;kk++) {
1795: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1796: }
1797:
1798: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1799: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1800: savm=oldm;
1801: oldm=newm;
1802: } /* end mult */
1803:
1804: s1=s[mw[mi][i]][i];
1805: s2=s[mw[mi+1][i]][i];
1806: if( s2 > nlstate){
1807: lli=log(out[s1][s2] - savm[s1][s2]);
1808: }else{
1809: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
1810: }
1811: ipmx +=1;
1812: sw += weight[i];
1813: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1814: /* 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]); */
1815: } /* end of wave */
1816: } /* end of individual */
1817: }else{ /* ml=5 no inter-extrapolation no jackson =0.8a */
1818: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1819: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1820: for(mi=1; mi<= wav[i]-1; mi++){
1821: for (ii=1;ii<=nlstate+ndeath;ii++)
1822: for (j=1;j<=nlstate+ndeath;j++){
1823: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1824: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1825: }
1826: for(d=0; d<dh[mi][i]; d++){
1827: newm=savm;
1828: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1829: for (kk=1; kk<=cptcovage;kk++) {
1830: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1831: }
1832:
1833: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1834: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1835: savm=oldm;
1836: oldm=newm;
1837: } /* end mult */
1838:
1839: s1=s[mw[mi][i]][i];
1840: s2=s[mw[mi+1][i]][i];
1841: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
1842: ipmx +=1;
1843: sw += weight[i];
1844: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1845: /*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]);*/
1846: } /* end of wave */
1847: } /* end of individual */
1848: } /* End of if */
1849: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
1850: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
1851: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
1852: return -l;
1853: }
1854:
1855: /*************** log-likelihood *************/
1856: double funcone( double *x)
1857: {
1858: /* Same as likeli but slower because of a lot of printf and if */
1859: int i, ii, j, k, mi, d, kk;
1860: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1861: double **out;
1862: double lli; /* Individual log likelihood */
1863: double llt;
1864: int s1, s2;
1865: double bbh, survp;
1866: /*extern weight */
1867: /* We are differentiating ll according to initial status */
1868: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
1869: /*for(i=1;i<imx;i++)
1870: printf(" %d\n",s[4][i]);
1871: */
1872: cov[1]=1.;
1873:
1874: for(k=1; k<=nlstate; k++) ll[k]=0.;
1875:
1876: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1877: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1878: for(mi=1; mi<= wav[i]-1; mi++){
1879: for (ii=1;ii<=nlstate+ndeath;ii++)
1880: for (j=1;j<=nlstate+ndeath;j++){
1881: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1882: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1883: }
1884: for(d=0; d<dh[mi][i]; d++){
1885: newm=savm;
1886: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1887: for (kk=1; kk<=cptcovage;kk++) {
1888: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1889: }
1890: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1891: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1892: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1893: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
1894: /* 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1895: savm=oldm;
1896: oldm=newm;
1897: } /* end mult */
1898:
1899: s1=s[mw[mi][i]][i];
1900: s2=s[mw[mi+1][i]][i];
1901: bbh=(double)bh[mi][i]/(double)stepm;
1902: /* bias is positive if real duration
1903: * is higher than the multiple of stepm and negative otherwise.
1904: */
1905: if( s2 > nlstate && (mle <5) ){ /* Jackson */
1906: lli=log(out[s1][s2] - savm[s1][s2]);
1907: } else if (s2==-2) {
1908: for (j=1,survp=0. ; j<=nlstate; j++)
1909: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1910: lli= log(survp);
1911: }else if (mle==1){
1912: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1913: } else if(mle==2){
1914: 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 */
1915: } else if(mle==3){ /* exponential inter-extrapolation */
1916: 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 */
1917: } else if (mle==4){ /* mle=4 no inter-extrapolation */
1918: lli=log(out[s1][s2]); /* Original formula */
1919: } else{ /* mle=0 back to 1 */
1920: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1921: /*lli=log(out[s1][s2]); */ /* Original formula */
1922: } /* End of if */
1923: ipmx +=1;
1924: sw += weight[i];
1925: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1926: /*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]); */
1927: if(globpr){
1928: fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
1929: %11.6f %11.6f %11.6f ", \
1930: num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
1931: 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
1932: for(k=1,llt=0.,l=0.; k<=nlstate; k++){
1933: llt +=ll[k]*gipmx/gsw;
1934: fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
1935: }
1936: fprintf(ficresilk," %10.6f\n", -llt);
1937: }
1938: } /* end of wave */
1939: } /* end of individual */
1940: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
1941: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
1942: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
1943: if(globpr==0){ /* First time we count the contributions and weights */
1944: gipmx=ipmx;
1945: gsw=sw;
1946: }
1947: return -l;
1948: }
1949:
1950:
1951: /*************** function likelione ***********/
1952: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
1953: {
1954: /* This routine should help understanding what is done with
1955: the selection of individuals/waves and
1956: to check the exact contribution to the likelihood.
1957: Plotting could be done.
1958: */
1959: int k;
1960:
1961: if(*globpri !=0){ /* Just counts and sums, no printings */
1962: strcpy(fileresilk,"ilk");
1963: strcat(fileresilk,fileres);
1964: if((ficresilk=fopen(fileresilk,"w"))==NULL) {
1965: printf("Problem with resultfile: %s\n", fileresilk);
1966: fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
1967: }
1968: 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");
1969: fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
1970: /* i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
1971: for(k=1; k<=nlstate; k++)
1972: fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
1973: fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
1974: }
1975:
1976: *fretone=(*funcone)(p);
1977: if(*globpri !=0){
1978: fclose(ficresilk);
1979: fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
1980: fflush(fichtm);
1981: }
1982: return;
1983: }
1984:
1985:
1986: /*********** Maximum Likelihood Estimation ***************/
1987:
1988: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
1989: {
1990: int i,j, iter;
1991: double **xi;
1992: double fret;
1993: double fretone; /* Only one call to likelihood */
1994: /* char filerespow[FILENAMELENGTH];*/
1995: xi=matrix(1,npar,1,npar);
1996: for (i=1;i<=npar;i++)
1997: for (j=1;j<=npar;j++)
1998: xi[i][j]=(i==j ? 1.0 : 0.0);
1999: printf("Powell\n"); fprintf(ficlog,"Powell\n");
2000: strcpy(filerespow,"pow");
2001: strcat(filerespow,fileres);
2002: if((ficrespow=fopen(filerespow,"w"))==NULL) {
2003: printf("Problem with resultfile: %s\n", filerespow);
2004: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
2005: }
2006: fprintf(ficrespow,"# Powell\n# iter -2*LL");
2007: for (i=1;i<=nlstate;i++)
2008: for(j=1;j<=nlstate+ndeath;j++)
2009: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
2010: fprintf(ficrespow,"\n");
2011:
2012: powell(p,xi,npar,ftol,&iter,&fret,func);
2013:
2014: free_matrix(xi,1,npar,1,npar);
2015: fclose(ficrespow);
2016: printf("\n#Number of iterations = %d, -2 Log likelihood = %.12f\n",iter,func(p));
2017: fprintf(ficlog,"\n#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
2018: fprintf(ficres,"#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
2019:
2020: }
2021:
2022: /**** Computes Hessian and covariance matrix ***/
2023: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
2024: {
2025: double **a,**y,*x,pd;
2026: double **hess;
2027: int i, j,jk;
2028: int *indx;
2029:
2030: double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
2031: double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
2032: void lubksb(double **a, int npar, int *indx, double b[]) ;
2033: void ludcmp(double **a, int npar, int *indx, double *d) ;
2034: double gompertz(double p[]);
2035: hess=matrix(1,npar,1,npar);
2036:
2037: printf("\nCalculation of the hessian matrix. Wait...\n");
2038: fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
2039: for (i=1;i<=npar;i++){
2040: printf("%d",i);fflush(stdout);
2041: fprintf(ficlog,"%d",i);fflush(ficlog);
2042:
2043: hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
2044:
2045: /* printf(" %f ",p[i]);
2046: printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
2047: }
2048:
2049: for (i=1;i<=npar;i++) {
2050: for (j=1;j<=npar;j++) {
2051: if (j>i) {
2052: printf(".%d%d",i,j);fflush(stdout);
2053: fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
2054: hess[i][j]=hessij(p,delti,i,j,func,npar);
2055:
2056: hess[j][i]=hess[i][j];
2057: /*printf(" %lf ",hess[i][j]);*/
2058: }
2059: }
2060: }
2061: printf("\n");
2062: fprintf(ficlog,"\n");
2063:
2064: printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
2065: fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
2066:
2067: a=matrix(1,npar,1,npar);
2068: y=matrix(1,npar,1,npar);
2069: x=vector(1,npar);
2070: indx=ivector(1,npar);
2071: for (i=1;i<=npar;i++)
2072: for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
2073: ludcmp(a,npar,indx,&pd);
2074:
2075: for (j=1;j<=npar;j++) {
2076: for (i=1;i<=npar;i++) x[i]=0;
2077: x[j]=1;
2078: lubksb(a,npar,indx,x);
2079: for (i=1;i<=npar;i++){
2080: matcov[i][j]=x[i];
2081: }
2082: }
2083:
2084: printf("\n#Hessian matrix#\n");
2085: fprintf(ficlog,"\n#Hessian matrix#\n");
2086: for (i=1;i<=npar;i++) {
2087: for (j=1;j<=npar;j++) {
2088: printf("%.3e ",hess[i][j]);
2089: fprintf(ficlog,"%.3e ",hess[i][j]);
2090: }
2091: printf("\n");
2092: fprintf(ficlog,"\n");
2093: }
2094:
2095: /* Recompute Inverse */
2096: for (i=1;i<=npar;i++)
2097: for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
2098: ludcmp(a,npar,indx,&pd);
2099:
2100: /* printf("\n#Hessian matrix recomputed#\n");
2101:
2102: for (j=1;j<=npar;j++) {
2103: for (i=1;i<=npar;i++) x[i]=0;
2104: x[j]=1;
2105: lubksb(a,npar,indx,x);
2106: for (i=1;i<=npar;i++){
2107: y[i][j]=x[i];
2108: printf("%.3e ",y[i][j]);
2109: fprintf(ficlog,"%.3e ",y[i][j]);
2110: }
2111: printf("\n");
2112: fprintf(ficlog,"\n");
2113: }
2114: */
2115:
2116: free_matrix(a,1,npar,1,npar);
2117: free_matrix(y,1,npar,1,npar);
2118: free_vector(x,1,npar);
2119: free_ivector(indx,1,npar);
2120: free_matrix(hess,1,npar,1,npar);
2121:
2122:
2123: }
2124:
2125: /*************** hessian matrix ****************/
2126: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
2127: {
2128: int i;
2129: int l=1, lmax=20;
2130: double k1,k2;
2131: double p2[MAXPARM+1]; /* identical to x */
2132: double res;
2133: double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
2134: double fx;
2135: int k=0,kmax=10;
2136: double l1;
2137:
2138: fx=func(x);
2139: for (i=1;i<=npar;i++) p2[i]=x[i];
2140: for(l=0 ; l <=lmax; l++){ /* Enlarging the zone around the Maximum */
2141: l1=pow(10,l);
2142: delts=delt;
2143: for(k=1 ; k <kmax; k=k+1){
2144: delt = delta*(l1*k);
2145: p2[theta]=x[theta] +delt;
2146: k1=func(p2)-fx; /* Might be negative if too close to the theoretical maximum */
2147: p2[theta]=x[theta]-delt;
2148: k2=func(p2)-fx;
2149: /*res= (k1-2.0*fx+k2)/delt/delt; */
2150: res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
2151:
2152: #ifdef DEBUGHESS
2153: 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);
2154: 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);
2155: #endif
2156: /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
2157: if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
2158: k=kmax;
2159: }
2160: else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
2161: k=kmax; l=lmax*10.;
2162: }
2163: else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
2164: delts=delt;
2165: }
2166: }
2167: }
2168: delti[theta]=delts;
2169: return res;
2170:
2171: }
2172:
2173: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
2174: {
2175: int i;
2176: int l=1, l1, lmax=20;
2177: double k1,k2,k3,k4,res,fx;
2178: double p2[MAXPARM+1];
2179: int k;
2180:
2181: fx=func(x);
2182: for (k=1; k<=2; k++) {
2183: for (i=1;i<=npar;i++) p2[i]=x[i];
2184: p2[thetai]=x[thetai]+delti[thetai]/k;
2185: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2186: k1=func(p2)-fx;
2187:
2188: p2[thetai]=x[thetai]+delti[thetai]/k;
2189: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2190: k2=func(p2)-fx;
2191:
2192: p2[thetai]=x[thetai]-delti[thetai]/k;
2193: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2194: k3=func(p2)-fx;
2195:
2196: p2[thetai]=x[thetai]-delti[thetai]/k;
2197: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2198: k4=func(p2)-fx;
2199: res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
2200: #ifdef DEBUG
2201: 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);
2202: 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);
2203: #endif
2204: }
2205: return res;
2206: }
2207:
2208: /************** Inverse of matrix **************/
2209: void ludcmp(double **a, int n, int *indx, double *d)
2210: {
2211: int i,imax,j,k;
2212: double big,dum,sum,temp;
2213: double *vv;
2214:
2215: vv=vector(1,n);
2216: *d=1.0;
2217: for (i=1;i<=n;i++) {
2218: big=0.0;
2219: for (j=1;j<=n;j++)
2220: if ((temp=fabs(a[i][j])) > big) big=temp;
2221: if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
2222: vv[i]=1.0/big;
2223: }
2224: for (j=1;j<=n;j++) {
2225: for (i=1;i<j;i++) {
2226: sum=a[i][j];
2227: for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
2228: a[i][j]=sum;
2229: }
2230: big=0.0;
2231: for (i=j;i<=n;i++) {
2232: sum=a[i][j];
2233: for (k=1;k<j;k++)
2234: sum -= a[i][k]*a[k][j];
2235: a[i][j]=sum;
2236: if ( (dum=vv[i]*fabs(sum)) >= big) {
2237: big=dum;
2238: imax=i;
2239: }
2240: }
2241: if (j != imax) {
2242: for (k=1;k<=n;k++) {
2243: dum=a[imax][k];
2244: a[imax][k]=a[j][k];
2245: a[j][k]=dum;
2246: }
2247: *d = -(*d);
2248: vv[imax]=vv[j];
2249: }
2250: indx[j]=imax;
2251: if (a[j][j] == 0.0) a[j][j]=TINY;
2252: if (j != n) {
2253: dum=1.0/(a[j][j]);
2254: for (i=j+1;i<=n;i++) a[i][j] *= dum;
2255: }
2256: }
2257: free_vector(vv,1,n); /* Doesn't work */
2258: ;
2259: }
2260:
2261: void lubksb(double **a, int n, int *indx, double b[])
2262: {
2263: int i,ii=0,ip,j;
2264: double sum;
2265:
2266: for (i=1;i<=n;i++) {
2267: ip=indx[i];
2268: sum=b[ip];
2269: b[ip]=b[i];
2270: if (ii)
2271: for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
2272: else if (sum) ii=i;
2273: b[i]=sum;
2274: }
2275: for (i=n;i>=1;i--) {
2276: sum=b[i];
2277: for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
2278: b[i]=sum/a[i][i];
2279: }
2280: }
2281:
2282: void pstamp(FILE *fichier)
2283: {
2284: fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
2285: }
2286:
2287: /************ Frequencies ********************/
2288: 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[])
2289: { /* Some frequencies */
2290:
2291: int i, m, jk, k1,i1, j1, bool, z1,j;
2292: int first;
2293: double ***freq; /* Frequencies */
2294: double *pp, **prop;
2295: double pos,posprop, k2, dateintsum=0,k2cpt=0;
2296: char fileresp[FILENAMELENGTH];
2297:
2298: pp=vector(1,nlstate);
2299: prop=matrix(1,nlstate,iagemin,iagemax+3);
2300: strcpy(fileresp,"p");
2301: strcat(fileresp,fileres);
2302: if((ficresp=fopen(fileresp,"w"))==NULL) {
2303: printf("Problem with prevalence resultfile: %s\n", fileresp);
2304: fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
2305: exit(0);
2306: }
2307: freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
2308: j1=0;
2309:
2310: j=cptcoveff;
2311: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2312:
2313: first=1;
2314:
2315: /* for(k1=1; k1<=j ; k1++){ /* Loop on covariates */
2316: /* for(i1=1; i1<=ncodemax[k1];i1++){ /* Now it is 2 */
2317: /* j1++;
2318: */
2319: for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
2320: /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
2321: scanf("%d", i);*/
2322: for (i=-5; i<=nlstate+ndeath; i++)
2323: for (jk=-5; jk<=nlstate+ndeath; jk++)
2324: for(m=iagemin; m <= iagemax+3; m++)
2325: freq[i][jk][m]=0;
2326:
2327: for (i=1; i<=nlstate; i++)
2328: for(m=iagemin; m <= iagemax+3; m++)
2329: prop[i][m]=0;
2330:
2331: dateintsum=0;
2332: k2cpt=0;
2333: for (i=1; i<=imx; i++) {
2334: bool=1;
2335: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
2336: for (z1=1; z1<=cptcoveff; z1++)
2337: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
2338: /* Tests if the value of each of the covariates of i is equal to filter j1 */
2339: bool=0;
2340: /* 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",
2341: bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
2342: j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
2343: /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
2344: }
2345: }
2346:
2347: if (bool==1){
2348: for(m=firstpass; m<=lastpass; m++){
2349: k2=anint[m][i]+(mint[m][i]/12.);
2350: /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
2351: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2352: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2353: if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
2354: if (m<lastpass) {
2355: freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
2356: freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
2357: }
2358:
2359: if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
2360: dateintsum=dateintsum+k2;
2361: k2cpt++;
2362: }
2363: /*}*/
2364: }
2365: }
2366: } /* end i */
2367:
2368: /* fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
2369: pstamp(ficresp);
2370: if (cptcovn>0) {
2371: fprintf(ficresp, "\n#********** Variable ");
2372: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2373: fprintf(ficresp, "**********\n#");
2374: fprintf(ficlog, "\n#********** Variable ");
2375: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2376: fprintf(ficlog, "**********\n#");
2377: }
2378: for(i=1; i<=nlstate;i++)
2379: fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
2380: fprintf(ficresp, "\n");
2381:
2382: for(i=iagemin; i <= iagemax+3; i++){
2383: if(i==iagemax+3){
2384: fprintf(ficlog,"Total");
2385: }else{
2386: if(first==1){
2387: first=0;
2388: printf("See log file for details...\n");
2389: }
2390: fprintf(ficlog,"Age %d", i);
2391: }
2392: for(jk=1; jk <=nlstate ; jk++){
2393: for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
2394: pp[jk] += freq[jk][m][i];
2395: }
2396: for(jk=1; jk <=nlstate ; jk++){
2397: for(m=-1, pos=0; m <=0 ; m++)
2398: pos += freq[jk][m][i];
2399: if(pp[jk]>=1.e-10){
2400: if(first==1){
2401: printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
2402: }
2403: fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
2404: }else{
2405: if(first==1)
2406: printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2407: fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2408: }
2409: }
2410:
2411: for(jk=1; jk <=nlstate ; jk++){
2412: for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
2413: pp[jk] += freq[jk][m][i];
2414: }
2415: for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
2416: pos += pp[jk];
2417: posprop += prop[jk][i];
2418: }
2419: for(jk=1; jk <=nlstate ; jk++){
2420: if(pos>=1.e-5){
2421: if(first==1)
2422: printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2423: fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2424: }else{
2425: if(first==1)
2426: printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2427: fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2428: }
2429: if( i <= iagemax){
2430: if(pos>=1.e-5){
2431: fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
2432: /*probs[i][jk][j1]= pp[jk]/pos;*/
2433: /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
2434: }
2435: else
2436: fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
2437: }
2438: }
2439:
2440: for(jk=-1; jk <=nlstate+ndeath; jk++)
2441: for(m=-1; m <=nlstate+ndeath; m++)
2442: if(freq[jk][m][i] !=0 ) {
2443: if(first==1)
2444: printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
2445: fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
2446: }
2447: if(i <= iagemax)
2448: fprintf(ficresp,"\n");
2449: if(first==1)
2450: printf("Others in log...\n");
2451: fprintf(ficlog,"\n");
2452: }
2453: /*}*/
2454: }
2455: dateintmean=dateintsum/k2cpt;
2456:
2457: fclose(ficresp);
2458: free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
2459: free_vector(pp,1,nlstate);
2460: free_matrix(prop,1,nlstate,iagemin, iagemax+3);
2461: /* End of Freq */
2462: }
2463:
2464: /************ Prevalence ********************/
2465: 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)
2466: {
2467: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
2468: in each health status at the date of interview (if between dateprev1 and dateprev2).
2469: We still use firstpass and lastpass as another selection.
2470: */
2471:
2472: int i, m, jk, k1, i1, j1, bool, z1,j;
2473: double ***freq; /* Frequencies */
2474: double *pp, **prop;
2475: double pos,posprop;
2476: double y2; /* in fractional years */
2477: int iagemin, iagemax;
2478: int first; /** to stop verbosity which is redirected to log file */
2479:
2480: iagemin= (int) agemin;
2481: iagemax= (int) agemax;
2482: /*pp=vector(1,nlstate);*/
2483: prop=matrix(1,nlstate,iagemin,iagemax+3);
2484: /* freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
2485: j1=0;
2486:
2487: /*j=cptcoveff;*/
2488: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2489:
2490: first=1;
2491: for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
2492: /*for(i1=1; i1<=ncodemax[k1];i1++){
2493: j1++;*/
2494:
2495: for (i=1; i<=nlstate; i++)
2496: for(m=iagemin; m <= iagemax+3; m++)
2497: prop[i][m]=0.0;
2498:
2499: for (i=1; i<=imx; i++) { /* Each individual */
2500: bool=1;
2501: if (cptcovn>0) {
2502: for (z1=1; z1<=cptcoveff; z1++)
2503: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
2504: bool=0;
2505: }
2506: if (bool==1) {
2507: for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
2508: y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
2509: if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
2510: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2511: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2512: 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);
2513: if (s[m][i]>0 && s[m][i]<=nlstate) {
2514: /*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]]);*/
2515: prop[s[m][i]][(int)agev[m][i]] += weight[i];
2516: prop[s[m][i]][iagemax+3] += weight[i];
2517: }
2518: }
2519: } /* end selection of waves */
2520: }
2521: }
2522: for(i=iagemin; i <= iagemax+3; i++){
2523: for(jk=1,posprop=0; jk <=nlstate ; jk++) {
2524: posprop += prop[jk][i];
2525: }
2526:
2527: for(jk=1; jk <=nlstate ; jk++){
2528: if( i <= iagemax){
2529: if(posprop>=1.e-5){
2530: probs[i][jk][j1]= prop[jk][i]/posprop;
2531: } else{
2532: if(first==1){
2533: first=0;
2534: 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]);
2535: }
2536: }
2537: }
2538: }/* end jk */
2539: }/* end i */
2540: /*} *//* end i1 */
2541: } /* end j1 */
2542:
2543: /* free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
2544: /*free_vector(pp,1,nlstate);*/
2545: free_matrix(prop,1,nlstate, iagemin,iagemax+3);
2546: } /* End of prevalence */
2547:
2548: /************* Waves Concatenation ***************/
2549:
2550: 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)
2551: {
2552: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
2553: Death is a valid wave (if date is known).
2554: mw[mi][i] is the mi (mi=1 to wav[i]) effective wave of individual i
2555: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
2556: and mw[mi+1][i]. dh depends on stepm.
2557: */
2558:
2559: int i, mi, m;
2560: /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
2561: double sum=0., jmean=0.;*/
2562: int first;
2563: int j, k=0,jk, ju, jl;
2564: double sum=0.;
2565: first=0;
2566: jmin=1e+5;
2567: jmax=-1;
2568: jmean=0.;
2569: for(i=1; i<=imx; i++){
2570: mi=0;
2571: m=firstpass;
2572: while(s[m][i] <= nlstate){
2573: if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
2574: mw[++mi][i]=m;
2575: if(m >=lastpass)
2576: break;
2577: else
2578: m++;
2579: }/* end while */
2580: if (s[m][i] > nlstate){
2581: mi++; /* Death is another wave */
2582: /* if(mi==0) never been interviewed correctly before death */
2583: /* Only death is a correct wave */
2584: mw[mi][i]=m;
2585: }
2586:
2587: wav[i]=mi;
2588: if(mi==0){
2589: nbwarn++;
2590: if(first==0){
2591: printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
2592: first=1;
2593: }
2594: if(first==1){
2595: fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
2596: }
2597: } /* end mi==0 */
2598: } /* End individuals */
2599:
2600: for(i=1; i<=imx; i++){
2601: for(mi=1; mi<wav[i];mi++){
2602: if (stepm <=0)
2603: dh[mi][i]=1;
2604: else{
2605: if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
2606: if (agedc[i] < 2*AGESUP) {
2607: j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
2608: if(j==0) j=1; /* Survives at least one month after exam */
2609: else if(j<0){
2610: nberr++;
2611: 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]);
2612: j=1; /* Temporary Dangerous patch */
2613: 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);
2614: 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]);
2615: 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);
2616: }
2617: k=k+1;
2618: if (j >= jmax){
2619: jmax=j;
2620: ijmax=i;
2621: }
2622: if (j <= jmin){
2623: jmin=j;
2624: ijmin=i;
2625: }
2626: sum=sum+j;
2627: /*if (j<0) printf("j=%d num=%d \n",j,i);*/
2628: /* printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
2629: }
2630: }
2631: else{
2632: j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
2633: /* 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]); */
2634:
2635: k=k+1;
2636: if (j >= jmax) {
2637: jmax=j;
2638: ijmax=i;
2639: }
2640: else if (j <= jmin){
2641: jmin=j;
2642: ijmin=i;
2643: }
2644: /* if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
2645: /*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]);*/
2646: if(j<0){
2647: nberr++;
2648: 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]);
2649: 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]);
2650: }
2651: sum=sum+j;
2652: }
2653: jk= j/stepm;
2654: jl= j -jk*stepm;
2655: ju= j -(jk+1)*stepm;
2656: if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
2657: if(jl==0){
2658: dh[mi][i]=jk;
2659: bh[mi][i]=0;
2660: }else{ /* We want a negative bias in order to only have interpolation ie
2661: * to avoid the price of an extra matrix product in likelihood */
2662: dh[mi][i]=jk+1;
2663: bh[mi][i]=ju;
2664: }
2665: }else{
2666: if(jl <= -ju){
2667: dh[mi][i]=jk;
2668: bh[mi][i]=jl; /* bias is positive if real duration
2669: * is higher than the multiple of stepm and negative otherwise.
2670: */
2671: }
2672: else{
2673: dh[mi][i]=jk+1;
2674: bh[mi][i]=ju;
2675: }
2676: if(dh[mi][i]==0){
2677: dh[mi][i]=1; /* At least one step */
2678: bh[mi][i]=ju; /* At least one step */
2679: /* 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);*/
2680: }
2681: } /* end if mle */
2682: }
2683: } /* end wave */
2684: }
2685: jmean=sum/k;
2686: 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);
2687: 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);
2688: }
2689:
2690: /*********** Tricode ****************************/
2691: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
2692: {
2693: /**< Uses cptcovn+2*cptcovprod as the number of covariates */
2694: /* Tvar[i]=atoi(stre); find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1
2695: /* Boring subroutine which should only output nbcode[Tvar[j]][k]
2696: * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
2697: /* nbcode[Tvar[j]][1]=
2698: */
2699:
2700: int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
2701: int modmaxcovj=0; /* Modality max of covariates j */
2702: int cptcode=0; /* Modality max of covariates j */
2703: int modmincovj=0; /* Modality min of covariates j */
2704:
2705:
2706: cptcoveff=0;
2707:
2708: for (k=-1; k < maxncov; k++) Ndum[k]=0;
2709: for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
2710:
2711: /* Loop on covariates without age and products */
2712: for (j=1; j<=(cptcovs); j++) { /* model V1 + V2*age+ V3 + V3*V4 : V1 + V3 = 2 only */
2713: for (i=1; i<=imx; i++) { /* Lopp on individuals: reads the data file to get the maximum value of the
2714: modality of this covariate Vj*/
2715: ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
2716: * If product of Vn*Vm, still boolean *:
2717: * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
2718: * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0 */
2719: /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
2720: modality of the nth covariate of individual i. */
2721: if (ij > modmaxcovj)
2722: modmaxcovj=ij;
2723: else if (ij < modmincovj)
2724: modmincovj=ij;
2725: if ((ij < -1) && (ij > NCOVMAX)){
2726: printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
2727: exit(1);
2728: }else
2729: Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
2730: /* If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
2731: /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
2732: /* getting the maximum value of the modality of the covariate
2733: (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
2734: female is 1, then modmaxcovj=1.*/
2735: }
2736: printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
2737: cptcode=modmaxcovj;
2738: /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
2739: /*for (i=0; i<=cptcode; i++) {*/
2740: for (i=modmincovj; i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
2741: printf("Frequencies of covariates %d V%d %d\n", j, Tvar[j], Ndum[i]);
2742: if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
2743: ncodemax[j]++; /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
2744: }
2745: /* In fact ncodemax[j]=2 (dichotom. variables only) but it could be more for
2746: historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
2747: } /* Ndum[-1] number of undefined modalities */
2748:
2749: /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
2750: /* For covariate j, modalities could be 1, 2, 3, 4. If Ndum[2]=0 ncodemax[j] is not 4 but 3 */
2751: /* If Ndum[3}= 635; Ndum[4]=0; Ndum[5]=0; Ndum[6]=27; Ndum[7]=125;
2752: modmincovj=3; modmaxcovj = 7;
2753: There are only 3 modalities non empty (or 2 if 27 is too few) : ncodemax[j]=3;
2754: which will be coded 0, 1, 2 which in binary on 3-1 digits are 0=00 1=01, 2=10; defining two dummy
2755: variables V1_1 and V1_2.
2756: nbcode[Tvar[j]][ij]=k;
2757: nbcode[Tvar[j]][1]=0;
2758: nbcode[Tvar[j]][2]=1;
2759: nbcode[Tvar[j]][3]=2;
2760: */
2761: ij=1; /* ij is similar to i but can jumps over null modalities */
2762: for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
2763: for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
2764: /*recode from 0 */
2765: if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
2766: nbcode[Tvar[j]][ij]=k; /* stores the modality in an array nbcode.
2767: k is a modality. If we have model=V1+V1*sex
2768: then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
2769: ij++;
2770: }
2771: if (ij > ncodemax[j]) break;
2772: } /* end of loop on */
2773: } /* end of loop on modality */
2774: } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/
2775:
2776: for (k=-1; k< maxncov; k++) Ndum[k]=0;
2777:
2778: for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */
2779: /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
2780: ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
2781: Ndum[ij]++;
2782: }
2783:
2784: ij=1;
2785: for (i=0; i<= maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
2786: /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
2787: if((Ndum[i]!=0) && (i<=ncovcol)){
2788: /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
2789: Tvaraff[ij]=i; /*For printing (unclear) */
2790: ij++;
2791: }else
2792: Tvaraff[ij]=0;
2793: }
2794: ij--;
2795: cptcoveff=ij; /*Number of total covariates*/
2796:
2797: }
2798:
2799:
2800: /*********** Health Expectancies ****************/
2801:
2802: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
2803:
2804: {
2805: /* Health expectancies, no variances */
2806: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2;
2807: int nhstepma, nstepma; /* Decreasing with age */
2808: double age, agelim, hf;
2809: double ***p3mat;
2810: double eip;
2811:
2812: pstamp(ficreseij);
2813: fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
2814: fprintf(ficreseij,"# Age");
2815: for(i=1; i<=nlstate;i++){
2816: for(j=1; j<=nlstate;j++){
2817: fprintf(ficreseij," e%1d%1d ",i,j);
2818: }
2819: fprintf(ficreseij," e%1d. ",i);
2820: }
2821: fprintf(ficreseij,"\n");
2822:
2823:
2824: if(estepm < stepm){
2825: printf ("Problem %d lower than %d\n",estepm, stepm);
2826: }
2827: else hstepm=estepm;
2828: /* We compute the life expectancy from trapezoids spaced every estepm months
2829: * This is mainly to measure the difference between two models: for example
2830: * if stepm=24 months pijx are given only every 2 years and by summing them
2831: * we are calculating an estimate of the Life Expectancy assuming a linear
2832: * progression in between and thus overestimating or underestimating according
2833: * to the curvature of the survival function. If, for the same date, we
2834: * estimate the model with stepm=1 month, we can keep estepm to 24 months
2835: * to compare the new estimate of Life expectancy with the same linear
2836: * hypothesis. A more precise result, taking into account a more precise
2837: * curvature will be obtained if estepm is as small as stepm. */
2838:
2839: /* For example we decided to compute the life expectancy with the smallest unit */
2840: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
2841: nhstepm is the number of hstepm from age to agelim
2842: nstepm is the number of stepm from age to agelin.
2843: Look at hpijx to understand the reason of that which relies in memory size
2844: and note for a fixed period like estepm months */
2845: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
2846: survival function given by stepm (the optimization length). Unfortunately it
2847: means that if the survival funtion is printed only each two years of age and if
2848: you sum them up and add 1 year (area under the trapezoids) you won't get the same
2849: results. So we changed our mind and took the option of the best precision.
2850: */
2851: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
2852:
2853: agelim=AGESUP;
2854: /* If stepm=6 months */
2855: /* Computed by stepm unit matrices, product of hstepm matrices, stored
2856: in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
2857:
2858: /* nhstepm age range expressed in number of stepm */
2859: nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
2860: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
2861: /* if (stepm >= YEARM) hstepm=1;*/
2862: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
2863: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
2864:
2865: for (age=bage; age<=fage; age ++){
2866: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
2867: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
2868: /* if (stepm >= YEARM) hstepm=1;*/
2869: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
2870:
2871: /* If stepm=6 months */
2872: /* Computed by stepm unit matrices, product of hstepma matrices, stored
2873: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
2874:
2875: hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
2876:
2877: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
2878:
2879: printf("%d|",(int)age);fflush(stdout);
2880: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
2881:
2882: /* Computing expectancies */
2883: for(i=1; i<=nlstate;i++)
2884: for(j=1; j<=nlstate;j++)
2885: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
2886: eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
2887:
2888: /* 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]);*/
2889:
2890: }
2891:
2892: fprintf(ficreseij,"%3.0f",age );
2893: for(i=1; i<=nlstate;i++){
2894: eip=0;
2895: for(j=1; j<=nlstate;j++){
2896: eip +=eij[i][j][(int)age];
2897: fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
2898: }
2899: fprintf(ficreseij,"%9.4f", eip );
2900: }
2901: fprintf(ficreseij,"\n");
2902:
2903: }
2904: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
2905: printf("\n");
2906: fprintf(ficlog,"\n");
2907:
2908: }
2909:
2910: 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[] )
2911:
2912: {
2913: /* Covariances of health expectancies eij and of total life expectancies according
2914: to initial status i, ei. .
2915: */
2916: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
2917: int nhstepma, nstepma; /* Decreasing with age */
2918: double age, agelim, hf;
2919: double ***p3matp, ***p3matm, ***varhe;
2920: double **dnewm,**doldm;
2921: double *xp, *xm;
2922: double **gp, **gm;
2923: double ***gradg, ***trgradg;
2924: int theta;
2925:
2926: double eip, vip;
2927:
2928: varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
2929: xp=vector(1,npar);
2930: xm=vector(1,npar);
2931: dnewm=matrix(1,nlstate*nlstate,1,npar);
2932: doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
2933:
2934: pstamp(ficresstdeij);
2935: fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
2936: fprintf(ficresstdeij,"# Age");
2937: for(i=1; i<=nlstate;i++){
2938: for(j=1; j<=nlstate;j++)
2939: fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
2940: fprintf(ficresstdeij," e%1d. ",i);
2941: }
2942: fprintf(ficresstdeij,"\n");
2943:
2944: pstamp(ficrescveij);
2945: fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
2946: fprintf(ficrescveij,"# Age");
2947: for(i=1; i<=nlstate;i++)
2948: for(j=1; j<=nlstate;j++){
2949: cptj= (j-1)*nlstate+i;
2950: for(i2=1; i2<=nlstate;i2++)
2951: for(j2=1; j2<=nlstate;j2++){
2952: cptj2= (j2-1)*nlstate+i2;
2953: if(cptj2 <= cptj)
2954: fprintf(ficrescveij," %1d%1d,%1d%1d",i,j,i2,j2);
2955: }
2956: }
2957: fprintf(ficrescveij,"\n");
2958:
2959: if(estepm < stepm){
2960: printf ("Problem %d lower than %d\n",estepm, stepm);
2961: }
2962: else hstepm=estepm;
2963: /* We compute the life expectancy from trapezoids spaced every estepm months
2964: * This is mainly to measure the difference between two models: for example
2965: * if stepm=24 months pijx are given only every 2 years and by summing them
2966: * we are calculating an estimate of the Life Expectancy assuming a linear
2967: * progression in between and thus overestimating or underestimating according
2968: * to the curvature of the survival function. If, for the same date, we
2969: * estimate the model with stepm=1 month, we can keep estepm to 24 months
2970: * to compare the new estimate of Life expectancy with the same linear
2971: * hypothesis. A more precise result, taking into account a more precise
2972: * curvature will be obtained if estepm is as small as stepm. */
2973:
2974: /* For example we decided to compute the life expectancy with the smallest unit */
2975: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
2976: nhstepm is the number of hstepm from age to agelim
2977: nstepm is the number of stepm from age to agelin.
2978: Look at hpijx to understand the reason of that which relies in memory size
2979: and note for a fixed period like estepm months */
2980: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
2981: survival function given by stepm (the optimization length). Unfortunately it
2982: means that if the survival funtion is printed only each two years of age and if
2983: you sum them up and add 1 year (area under the trapezoids) you won't get the same
2984: results. So we changed our mind and took the option of the best precision.
2985: */
2986: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
2987:
2988: /* If stepm=6 months */
2989: /* nhstepm age range expressed in number of stepm */
2990: agelim=AGESUP;
2991: nstepm=(int) rint((agelim-bage)*YEARM/stepm);
2992: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
2993: /* if (stepm >= YEARM) hstepm=1;*/
2994: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
2995:
2996: p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
2997: p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
2998: gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
2999: trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
3000: gp=matrix(0,nhstepm,1,nlstate*nlstate);
3001: gm=matrix(0,nhstepm,1,nlstate*nlstate);
3002:
3003: for (age=bage; age<=fage; age ++){
3004: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3005: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3006: /* if (stepm >= YEARM) hstepm=1;*/
3007: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3008:
3009: /* If stepm=6 months */
3010: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3011: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3012:
3013: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3014:
3015: /* Computing Variances of health expectancies */
3016: /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
3017: decrease memory allocation */
3018: for(theta=1; theta <=npar; theta++){
3019: for(i=1; i<=npar; i++){
3020: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3021: xm[i] = x[i] - (i==theta ?delti[theta]:0);
3022: }
3023: hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);
3024: hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);
3025:
3026: for(j=1; j<= nlstate; j++){
3027: for(i=1; i<=nlstate; i++){
3028: for(h=0; h<=nhstepm-1; h++){
3029: gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
3030: gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
3031: }
3032: }
3033: }
3034:
3035: for(ij=1; ij<= nlstate*nlstate; ij++)
3036: for(h=0; h<=nhstepm-1; h++){
3037: gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
3038: }
3039: }/* End theta */
3040:
3041:
3042: for(h=0; h<=nhstepm-1; h++)
3043: for(j=1; j<=nlstate*nlstate;j++)
3044: for(theta=1; theta <=npar; theta++)
3045: trgradg[h][j][theta]=gradg[h][theta][j];
3046:
3047:
3048: for(ij=1;ij<=nlstate*nlstate;ij++)
3049: for(ji=1;ji<=nlstate*nlstate;ji++)
3050: varhe[ij][ji][(int)age] =0.;
3051:
3052: printf("%d|",(int)age);fflush(stdout);
3053: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3054: for(h=0;h<=nhstepm-1;h++){
3055: for(k=0;k<=nhstepm-1;k++){
3056: matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
3057: matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
3058: for(ij=1;ij<=nlstate*nlstate;ij++)
3059: for(ji=1;ji<=nlstate*nlstate;ji++)
3060: varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
3061: }
3062: }
3063:
3064: /* Computing expectancies */
3065: hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3066: for(i=1; i<=nlstate;i++)
3067: for(j=1; j<=nlstate;j++)
3068: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3069: eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
3070:
3071: /* 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]);*/
3072:
3073: }
3074:
3075: fprintf(ficresstdeij,"%3.0f",age );
3076: for(i=1; i<=nlstate;i++){
3077: eip=0.;
3078: vip=0.;
3079: for(j=1; j<=nlstate;j++){
3080: eip += eij[i][j][(int)age];
3081: for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
3082: vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
3083: fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
3084: }
3085: fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
3086: }
3087: fprintf(ficresstdeij,"\n");
3088:
3089: fprintf(ficrescveij,"%3.0f",age );
3090: for(i=1; i<=nlstate;i++)
3091: for(j=1; j<=nlstate;j++){
3092: cptj= (j-1)*nlstate+i;
3093: for(i2=1; i2<=nlstate;i2++)
3094: for(j2=1; j2<=nlstate;j2++){
3095: cptj2= (j2-1)*nlstate+i2;
3096: if(cptj2 <= cptj)
3097: fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
3098: }
3099: }
3100: fprintf(ficrescveij,"\n");
3101:
3102: }
3103: free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
3104: free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
3105: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
3106: free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
3107: free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3108: free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3109: printf("\n");
3110: fprintf(ficlog,"\n");
3111:
3112: free_vector(xm,1,npar);
3113: free_vector(xp,1,npar);
3114: free_matrix(dnewm,1,nlstate*nlstate,1,npar);
3115: free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
3116: free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
3117: }
3118:
3119: /************ Variance ******************/
3120: 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[])
3121: {
3122: /* Variance of health expectancies */
3123: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
3124: /* double **newm;*/
3125: double **dnewm,**doldm;
3126: double **dnewmp,**doldmp;
3127: int i, j, nhstepm, hstepm, h, nstepm ;
3128: int k, cptcode;
3129: double *xp;
3130: double **gp, **gm; /* for var eij */
3131: double ***gradg, ***trgradg; /*for var eij */
3132: double **gradgp, **trgradgp; /* for var p point j */
3133: double *gpp, *gmp; /* for var p point j */
3134: double **varppt; /* for var p point j nlstate to nlstate+ndeath */
3135: double ***p3mat;
3136: double age,agelim, hf;
3137: double ***mobaverage;
3138: int theta;
3139: char digit[4];
3140: char digitp[25];
3141:
3142: char fileresprobmorprev[FILENAMELENGTH];
3143:
3144: if(popbased==1){
3145: if(mobilav!=0)
3146: strcpy(digitp,"-populbased-mobilav-");
3147: else strcpy(digitp,"-populbased-nomobil-");
3148: }
3149: else
3150: strcpy(digitp,"-stablbased-");
3151:
3152: if (mobilav!=0) {
3153: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3154: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
3155: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
3156: printf(" Error in movingaverage mobilav=%d\n",mobilav);
3157: }
3158: }
3159:
3160: strcpy(fileresprobmorprev,"prmorprev");
3161: sprintf(digit,"%-d",ij);
3162: /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
3163: strcat(fileresprobmorprev,digit); /* Tvar to be done */
3164: strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
3165: strcat(fileresprobmorprev,fileres);
3166: if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
3167: printf("Problem with resultfile: %s\n", fileresprobmorprev);
3168: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
3169: }
3170: printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3171:
3172: fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3173: pstamp(ficresprobmorprev);
3174: 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);
3175: fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
3176: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3177: fprintf(ficresprobmorprev," p.%-d SE",j);
3178: for(i=1; i<=nlstate;i++)
3179: fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
3180: }
3181: fprintf(ficresprobmorprev,"\n");
3182: fprintf(ficgp,"\n# Routine varevsij");
3183: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
3184: 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");
3185: fprintf(fichtm,"\n<br>%s <br>\n",digitp);
3186: /* } */
3187: varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3188: pstamp(ficresvij);
3189: fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n# (weighted average of eij where weights are ");
3190: if(popbased==1)
3191: 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);
3192: else
3193: fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
3194: fprintf(ficresvij,"# Age");
3195: for(i=1; i<=nlstate;i++)
3196: for(j=1; j<=nlstate;j++)
3197: fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
3198: fprintf(ficresvij,"\n");
3199:
3200: xp=vector(1,npar);
3201: dnewm=matrix(1,nlstate,1,npar);
3202: doldm=matrix(1,nlstate,1,nlstate);
3203: dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
3204: doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3205:
3206: gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
3207: gpp=vector(nlstate+1,nlstate+ndeath);
3208: gmp=vector(nlstate+1,nlstate+ndeath);
3209: trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
3210:
3211: if(estepm < stepm){
3212: printf ("Problem %d lower than %d\n",estepm, stepm);
3213: }
3214: else hstepm=estepm;
3215: /* For example we decided to compute the life expectancy with the smallest unit */
3216: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3217: nhstepm is the number of hstepm from age to agelim
3218: nstepm is the number of stepm from age to agelin.
3219: Look at function hpijx to understand why (it is linked to memory size questions) */
3220: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3221: survival function given by stepm (the optimization length). Unfortunately it
3222: means that if the survival funtion is printed every two years of age and if
3223: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3224: results. So we changed our mind and took the option of the best precision.
3225: */
3226: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3227: agelim = AGESUP;
3228: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3229: nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3230: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3231: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3232: gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
3233: gp=matrix(0,nhstepm,1,nlstate);
3234: gm=matrix(0,nhstepm,1,nlstate);
3235:
3236:
3237: for(theta=1; theta <=npar; theta++){
3238: for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
3239: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3240: }
3241: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3242: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3243:
3244: if (popbased==1) {
3245: if(mobilav ==0){
3246: for(i=1; i<=nlstate;i++)
3247: prlim[i][i]=probs[(int)age][i][ij];
3248: }else{ /* mobilav */
3249: for(i=1; i<=nlstate;i++)
3250: prlim[i][i]=mobaverage[(int)age][i][ij];
3251: }
3252: }
3253:
3254: for(j=1; j<= nlstate; j++){
3255: for(h=0; h<=nhstepm; h++){
3256: for(i=1, gp[h][j]=0.;i<=nlstate;i++)
3257: gp[h][j] += prlim[i][i]*p3mat[i][j][h];
3258: }
3259: }
3260: /* This for computing probability of death (h=1 means
3261: computed over hstepm matrices product = hstepm*stepm months)
3262: as a weighted average of prlim.
3263: */
3264: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3265: for(i=1,gpp[j]=0.; i<= nlstate; i++)
3266: gpp[j] += prlim[i][i]*p3mat[i][j][1];
3267: }
3268: /* end probability of death */
3269:
3270: for(i=1; i<=npar; i++) /* Computes gradient x - delta */
3271: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3272: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3273: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3274:
3275: if (popbased==1) {
3276: if(mobilav ==0){
3277: for(i=1; i<=nlstate;i++)
3278: prlim[i][i]=probs[(int)age][i][ij];
3279: }else{ /* mobilav */
3280: for(i=1; i<=nlstate;i++)
3281: prlim[i][i]=mobaverage[(int)age][i][ij];
3282: }
3283: }
3284:
3285: for(j=1; j<= nlstate; j++){ /* Sum of wi * eij = e.j */
3286: for(h=0; h<=nhstepm; h++){
3287: for(i=1, gm[h][j]=0.;i<=nlstate;i++)
3288: gm[h][j] += prlim[i][i]*p3mat[i][j][h];
3289: }
3290: }
3291: /* This for computing probability of death (h=1 means
3292: computed over hstepm matrices product = hstepm*stepm months)
3293: as a weighted average of prlim.
3294: */
3295: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3296: for(i=1,gmp[j]=0.; i<= nlstate; i++)
3297: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3298: }
3299: /* end probability of death */
3300:
3301: for(j=1; j<= nlstate; j++) /* vareij */
3302: for(h=0; h<=nhstepm; h++){
3303: gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
3304: }
3305:
3306: for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
3307: gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
3308: }
3309:
3310: } /* End theta */
3311:
3312: trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
3313:
3314: for(h=0; h<=nhstepm; h++) /* veij */
3315: for(j=1; j<=nlstate;j++)
3316: for(theta=1; theta <=npar; theta++)
3317: trgradg[h][j][theta]=gradg[h][theta][j];
3318:
3319: for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
3320: for(theta=1; theta <=npar; theta++)
3321: trgradgp[j][theta]=gradgp[theta][j];
3322:
3323:
3324: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3325: for(i=1;i<=nlstate;i++)
3326: for(j=1;j<=nlstate;j++)
3327: vareij[i][j][(int)age] =0.;
3328:
3329: for(h=0;h<=nhstepm;h++){
3330: for(k=0;k<=nhstepm;k++){
3331: matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
3332: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
3333: for(i=1;i<=nlstate;i++)
3334: for(j=1;j<=nlstate;j++)
3335: vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
3336: }
3337: }
3338:
3339: /* pptj */
3340: matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
3341: matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
3342: for(j=nlstate+1;j<=nlstate+ndeath;j++)
3343: for(i=nlstate+1;i<=nlstate+ndeath;i++)
3344: varppt[j][i]=doldmp[j][i];
3345: /* end ppptj */
3346: /* x centered again */
3347: hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);
3348: prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
3349:
3350: if (popbased==1) {
3351: if(mobilav ==0){
3352: for(i=1; i<=nlstate;i++)
3353: prlim[i][i]=probs[(int)age][i][ij];
3354: }else{ /* mobilav */
3355: for(i=1; i<=nlstate;i++)
3356: prlim[i][i]=mobaverage[(int)age][i][ij];
3357: }
3358: }
3359:
3360: /* This for computing probability of death (h=1 means
3361: computed over hstepm (estepm) matrices product = hstepm*stepm months)
3362: as a weighted average of prlim.
3363: */
3364: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3365: for(i=1,gmp[j]=0.;i<= nlstate; i++)
3366: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3367: }
3368: /* end probability of death */
3369:
3370: fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
3371: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3372: fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
3373: for(i=1; i<=nlstate;i++){
3374: fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
3375: }
3376: }
3377: fprintf(ficresprobmorprev,"\n");
3378:
3379: fprintf(ficresvij,"%.0f ",age );
3380: for(i=1; i<=nlstate;i++)
3381: for(j=1; j<=nlstate;j++){
3382: fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
3383: }
3384: fprintf(ficresvij,"\n");
3385: free_matrix(gp,0,nhstepm,1,nlstate);
3386: free_matrix(gm,0,nhstepm,1,nlstate);
3387: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
3388: free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
3389: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3390: } /* End age */
3391: free_vector(gpp,nlstate+1,nlstate+ndeath);
3392: free_vector(gmp,nlstate+1,nlstate+ndeath);
3393: free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
3394: free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
3395: fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
3396: /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
3397: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
3398: /* fprintf(ficgp,"\n plot \"%s\" u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
3399: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
3400: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
3401: fprintf(ficgp,"\n plot \"%s\" u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
3402: fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)) t \"95\%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
3403: fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
3404: fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
3405: 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);
3406: /* 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);
3407: */
3408: /* fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
3409: fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
3410:
3411: free_vector(xp,1,npar);
3412: free_matrix(doldm,1,nlstate,1,nlstate);
3413: free_matrix(dnewm,1,nlstate,1,npar);
3414: free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3415: free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
3416: free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3417: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3418: fclose(ficresprobmorprev);
3419: fflush(ficgp);
3420: fflush(fichtm);
3421: } /* end varevsij */
3422:
3423: /************ Variance of prevlim ******************/
3424: 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[])
3425: {
3426: /* Variance of prevalence limit */
3427: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
3428: double **newm;
3429: double **dnewm,**doldm;
3430: int i, j, nhstepm, hstepm;
3431: int k, cptcode;
3432: double *xp;
3433: double *gp, *gm;
3434: double **gradg, **trgradg;
3435: double age,agelim;
3436: int theta;
3437:
3438: pstamp(ficresvpl);
3439: fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
3440: fprintf(ficresvpl,"# Age");
3441: for(i=1; i<=nlstate;i++)
3442: fprintf(ficresvpl," %1d-%1d",i,i);
3443: fprintf(ficresvpl,"\n");
3444:
3445: xp=vector(1,npar);
3446: dnewm=matrix(1,nlstate,1,npar);
3447: doldm=matrix(1,nlstate,1,nlstate);
3448:
3449: hstepm=1*YEARM; /* Every year of age */
3450: hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
3451: agelim = AGESUP;
3452: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3453: nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3454: if (stepm >= YEARM) hstepm=1;
3455: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
3456: gradg=matrix(1,npar,1,nlstate);
3457: gp=vector(1,nlstate);
3458: gm=vector(1,nlstate);
3459:
3460: for(theta=1; theta <=npar; theta++){
3461: for(i=1; i<=npar; i++){ /* Computes gradient */
3462: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3463: }
3464: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3465: for(i=1;i<=nlstate;i++)
3466: gp[i] = prlim[i][i];
3467:
3468: for(i=1; i<=npar; i++) /* Computes gradient */
3469: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3470: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3471: for(i=1;i<=nlstate;i++)
3472: gm[i] = prlim[i][i];
3473:
3474: for(i=1;i<=nlstate;i++)
3475: gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
3476: } /* End theta */
3477:
3478: trgradg =matrix(1,nlstate,1,npar);
3479:
3480: for(j=1; j<=nlstate;j++)
3481: for(theta=1; theta <=npar; theta++)
3482: trgradg[j][theta]=gradg[theta][j];
3483:
3484: for(i=1;i<=nlstate;i++)
3485: varpl[i][(int)age] =0.;
3486: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
3487: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
3488: for(i=1;i<=nlstate;i++)
3489: varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
3490:
3491: fprintf(ficresvpl,"%.0f ",age );
3492: for(i=1; i<=nlstate;i++)
3493: fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
3494: fprintf(ficresvpl,"\n");
3495: free_vector(gp,1,nlstate);
3496: free_vector(gm,1,nlstate);
3497: free_matrix(gradg,1,npar,1,nlstate);
3498: free_matrix(trgradg,1,nlstate,1,npar);
3499: } /* End age */
3500:
3501: free_vector(xp,1,npar);
3502: free_matrix(doldm,1,nlstate,1,npar);
3503: free_matrix(dnewm,1,nlstate,1,nlstate);
3504:
3505: }
3506:
3507: /************ Variance of one-step probabilities ******************/
3508: 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[])
3509: {
3510: int i, j=0, i1, k1, l1, t, tj;
3511: int k2, l2, j1, z1;
3512: int k=0,l, cptcode;
3513: int first=1, first1, first2;
3514: double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
3515: double **dnewm,**doldm;
3516: double *xp;
3517: double *gp, *gm;
3518: double **gradg, **trgradg;
3519: double **mu;
3520: double age,agelim, cov[NCOVMAX+1];
3521: double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
3522: int theta;
3523: char fileresprob[FILENAMELENGTH];
3524: char fileresprobcov[FILENAMELENGTH];
3525: char fileresprobcor[FILENAMELENGTH];
3526: double ***varpij;
3527:
3528: strcpy(fileresprob,"prob");
3529: strcat(fileresprob,fileres);
3530: if((ficresprob=fopen(fileresprob,"w"))==NULL) {
3531: printf("Problem with resultfile: %s\n", fileresprob);
3532: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
3533: }
3534: strcpy(fileresprobcov,"probcov");
3535: strcat(fileresprobcov,fileres);
3536: if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
3537: printf("Problem with resultfile: %s\n", fileresprobcov);
3538: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
3539: }
3540: strcpy(fileresprobcor,"probcor");
3541: strcat(fileresprobcor,fileres);
3542: if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
3543: printf("Problem with resultfile: %s\n", fileresprobcor);
3544: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
3545: }
3546: printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3547: fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3548: printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3549: fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3550: printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3551: fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3552: pstamp(ficresprob);
3553: fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
3554: fprintf(ficresprob,"# Age");
3555: pstamp(ficresprobcov);
3556: fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
3557: fprintf(ficresprobcov,"# Age");
3558: pstamp(ficresprobcor);
3559: fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
3560: fprintf(ficresprobcor,"# Age");
3561:
3562:
3563: for(i=1; i<=nlstate;i++)
3564: for(j=1; j<=(nlstate+ndeath);j++){
3565: fprintf(ficresprob," p%1d-%1d (SE)",i,j);
3566: fprintf(ficresprobcov," p%1d-%1d ",i,j);
3567: fprintf(ficresprobcor," p%1d-%1d ",i,j);
3568: }
3569: /* fprintf(ficresprob,"\n");
3570: fprintf(ficresprobcov,"\n");
3571: fprintf(ficresprobcor,"\n");
3572: */
3573: xp=vector(1,npar);
3574: dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3575: doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
3576: mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
3577: varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
3578: first=1;
3579: fprintf(ficgp,"\n# Routine varprob");
3580: fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
3581: fprintf(fichtm,"\n");
3582:
3583: fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
3584: fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
3585: file %s<br>\n",optionfilehtmcov);
3586: fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
3587: and drawn. It helps understanding how is the covariance between two incidences.\
3588: They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
3589: 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. \
3590: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
3591: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
3592: standard deviations wide on each axis. <br>\
3593: Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
3594: and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
3595: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
3596:
3597: cov[1]=1;
3598: /* tj=cptcoveff; */
3599: tj = (int) pow(2,cptcoveff);
3600: if (cptcovn<1) {tj=1;ncodemax[1]=1;}
3601: j1=0;
3602: for(j1=1; j1<=tj;j1++){
3603: /*for(i1=1; i1<=ncodemax[t];i1++){ */
3604: /*j1++;*/
3605: if (cptcovn>0) {
3606: fprintf(ficresprob, "\n#********** Variable ");
3607: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3608: fprintf(ficresprob, "**********\n#\n");
3609: fprintf(ficresprobcov, "\n#********** Variable ");
3610: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3611: fprintf(ficresprobcov, "**********\n#\n");
3612:
3613: fprintf(ficgp, "\n#********** Variable ");
3614: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3615: fprintf(ficgp, "**********\n#\n");
3616:
3617:
3618: fprintf(fichtmcov, "\n<hr size=\"2\" color=\"#EC5E5E\">********** Variable ");
3619: for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3620: fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
3621:
3622: fprintf(ficresprobcor, "\n#********** Variable ");
3623: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3624: fprintf(ficresprobcor, "**********\n#");
3625: }
3626:
3627: gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
3628: trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3629: gp=vector(1,(nlstate)*(nlstate+ndeath));
3630: gm=vector(1,(nlstate)*(nlstate+ndeath));
3631: for (age=bage; age<=fage; age ++){
3632: cov[2]=age;
3633: for (k=1; k<=cptcovn;k++) {
3634: cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
3635: * 1 1 1 1 1
3636: * 2 2 1 1 1
3637: * 3 1 2 1 1
3638: */
3639: /* nbcode[1][1]=0 nbcode[1][2]=1;*/
3640: }
3641: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
3642: for (k=1; k<=cptcovprod;k++)
3643: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
3644:
3645:
3646: for(theta=1; theta <=npar; theta++){
3647: for(i=1; i<=npar; i++)
3648: xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
3649:
3650: pmij(pmmij,cov,ncovmodel,xp,nlstate);
3651:
3652: k=0;
3653: for(i=1; i<= (nlstate); i++){
3654: for(j=1; j<=(nlstate+ndeath);j++){
3655: k=k+1;
3656: gp[k]=pmmij[i][j];
3657: }
3658: }
3659:
3660: for(i=1; i<=npar; i++)
3661: xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
3662:
3663: pmij(pmmij,cov,ncovmodel,xp,nlstate);
3664: k=0;
3665: for(i=1; i<=(nlstate); i++){
3666: for(j=1; j<=(nlstate+ndeath);j++){
3667: k=k+1;
3668: gm[k]=pmmij[i][j];
3669: }
3670: }
3671:
3672: for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
3673: gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];
3674: }
3675:
3676: for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
3677: for(theta=1; theta <=npar; theta++)
3678: trgradg[j][theta]=gradg[theta][j];
3679:
3680: matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
3681: matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
3682:
3683: pmij(pmmij,cov,ncovmodel,x,nlstate);
3684:
3685: k=0;
3686: for(i=1; i<=(nlstate); i++){
3687: for(j=1; j<=(nlstate+ndeath);j++){
3688: k=k+1;
3689: mu[k][(int) age]=pmmij[i][j];
3690: }
3691: }
3692: for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
3693: for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
3694: varpij[i][j][(int)age] = doldm[i][j];
3695:
3696: /*printf("\n%d ",(int)age);
3697: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
3698: printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
3699: fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
3700: }*/
3701:
3702: fprintf(ficresprob,"\n%d ",(int)age);
3703: fprintf(ficresprobcov,"\n%d ",(int)age);
3704: fprintf(ficresprobcor,"\n%d ",(int)age);
3705:
3706: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
3707: fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
3708: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
3709: fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
3710: fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
3711: }
3712: i=0;
3713: for (k=1; k<=(nlstate);k++){
3714: for (l=1; l<=(nlstate+ndeath);l++){
3715: i++;
3716: fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
3717: fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
3718: for (j=1; j<=i;j++){
3719: /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
3720: fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
3721: fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
3722: }
3723: }
3724: }/* end of loop for state */
3725: } /* end of loop for age */
3726: free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
3727: free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
3728: free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
3729: free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
3730:
3731: /* Confidence intervalle of pij */
3732: /*
3733: fprintf(ficgp,"\nunset parametric;unset label");
3734: fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
3735: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
3736: 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);
3737: fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
3738: fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
3739: fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
3740: */
3741:
3742: /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
3743: first1=1;first2=2;
3744: for (k2=1; k2<=(nlstate);k2++){
3745: for (l2=1; l2<=(nlstate+ndeath);l2++){
3746: if(l2==k2) continue;
3747: j=(k2-1)*(nlstate+ndeath)+l2;
3748: for (k1=1; k1<=(nlstate);k1++){
3749: for (l1=1; l1<=(nlstate+ndeath);l1++){
3750: if(l1==k1) continue;
3751: i=(k1-1)*(nlstate+ndeath)+l1;
3752: if(i<=j) continue;
3753: for (age=bage; age<=fage; age ++){
3754: if ((int)age %5==0){
3755: v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
3756: v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
3757: cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
3758: mu1=mu[i][(int) age]/stepm*YEARM ;
3759: mu2=mu[j][(int) age]/stepm*YEARM;
3760: c12=cv12/sqrt(v1*v2);
3761: /* Computing eigen value of matrix of covariance */
3762: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
3763: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
3764: if ((lc2 <0) || (lc1 <0) ){
3765: if(first2==1){
3766: first1=0;
3767: 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);
3768: }
3769: 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);
3770: /* lc1=fabs(lc1); */ /* If we want to have them positive */
3771: /* lc2=fabs(lc2); */
3772: }
3773:
3774: /* Eigen vectors */
3775: v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
3776: /*v21=sqrt(1.-v11*v11); *//* error */
3777: v21=(lc1-v1)/cv12*v11;
3778: v12=-v21;
3779: v22=v11;
3780: tnalp=v21/v11;
3781: if(first1==1){
3782: first1=0;
3783: 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);
3784: }
3785: 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);
3786: /*printf(fignu*/
3787: /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
3788: /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
3789: if(first==1){
3790: first=0;
3791: fprintf(ficgp,"\nset parametric;unset label");
3792: 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);
3793: fprintf(ficgp,"\nset ter png small size 320, 240");
3794: fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
3795: :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
3796: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
3797: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
3798: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
3799: fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
3800: fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
3801: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
3802: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
3803: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
3804: 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",\
3805: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
3806: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
3807: }else{
3808: first=0;
3809: fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
3810: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
3811: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
3812: 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",\
3813: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
3814: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
3815: }/* if first */
3816: } /* age mod 5 */
3817: } /* end loop age */
3818: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
3819: first=1;
3820: } /*l12 */
3821: } /* k12 */
3822: } /*l1 */
3823: }/* k1 */
3824: /* } /* loop covariates */
3825: }
3826: free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
3827: free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
3828: free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
3829: free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
3830: free_vector(xp,1,npar);
3831: fclose(ficresprob);
3832: fclose(ficresprobcov);
3833: fclose(ficresprobcor);
3834: fflush(ficgp);
3835: fflush(fichtmcov);
3836: }
3837:
3838:
3839: /******************* Printing html file ***********/
3840: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
3841: int lastpass, int stepm, int weightopt, char model[],\
3842: int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
3843: int popforecast, int estepm ,\
3844: double jprev1, double mprev1,double anprev1, \
3845: double jprev2, double mprev2,double anprev2){
3846: int jj1, k1, i1, cpt;
3847:
3848: fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
3849: <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
3850: </ul>");
3851: fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
3852: - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
3853: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
3854: fprintf(fichtm,"\
3855: - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
3856: stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
3857: fprintf(fichtm,"\
3858: - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
3859: subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
3860: fprintf(fichtm,"\
3861: - (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): \
3862: <a href=\"%s\">%s</a> <br>\n",
3863: estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
3864: fprintf(fichtm,"\
3865: - Population projections by age and states: \
3866: <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
3867:
3868: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
3869:
3870: m=pow(2,cptcoveff);
3871: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
3872:
3873: jj1=0;
3874: for(k1=1; k1<=m;k1++){
3875: for(i1=1; i1<=ncodemax[k1];i1++){
3876: jj1++;
3877: if (cptcovn > 0) {
3878: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
3879: for (cpt=1; cpt<=cptcoveff;cpt++)
3880: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
3881: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
3882: }
3883: /* Pij */
3884: 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> \
3885: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
3886: /* Quasi-incidences */
3887: fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
3888: 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> \
3889: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
3890: /* Period (stable) prevalence in each health state */
3891: for(cpt=1; cpt<nlstate;cpt++){
3892: fprintf(fichtm,"<br>- Period (stable) prevalence in each health state : <a href=\"%s%d_%d.png\">%s%d_%d.png</a><br> \
3893: <img src=\"%s%d_%d.png\">",subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
3894: }
3895: for(cpt=1; cpt<=nlstate;cpt++) {
3896: fprintf(fichtm,"\n<br>- Life expectancy by health state (%d) at initial age and its decomposition into health expectancies : <a href=\"%s%d%d.png\">%s%d%d.png</a> <br> \
3897: <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
3898: }
3899: } /* end i1 */
3900: }/* End k1 */
3901: fprintf(fichtm,"</ul>");
3902:
3903:
3904: fprintf(fichtm,"\
3905: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
3906: - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
3907:
3908: fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
3909: subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
3910: fprintf(fichtm,"\
3911: - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
3912: subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
3913:
3914: fprintf(fichtm,"\
3915: - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
3916: subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
3917: fprintf(fichtm,"\
3918: - 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): \
3919: <a href=\"%s\">%s</a> <br>\n</li>",
3920: estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
3921: fprintf(fichtm,"\
3922: - (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): \
3923: <a href=\"%s\">%s</a> <br>\n</li>",
3924: estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
3925: fprintf(fichtm,"\
3926: - 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",
3927: estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
3928: fprintf(fichtm,"\
3929: - 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",
3930: estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
3931: fprintf(fichtm,"\
3932: - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
3933: subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
3934:
3935: /* if(popforecast==1) fprintf(fichtm,"\n */
3936: /* - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
3937: /* - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
3938: /* <br>",fileres,fileres,fileres,fileres); */
3939: /* else */
3940: /* 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); */
3941: fflush(fichtm);
3942: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
3943:
3944: m=pow(2,cptcoveff);
3945: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
3946:
3947: jj1=0;
3948: for(k1=1; k1<=m;k1++){
3949: for(i1=1; i1<=ncodemax[k1];i1++){
3950: jj1++;
3951: if (cptcovn > 0) {
3952: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
3953: for (cpt=1; cpt<=cptcoveff;cpt++)
3954: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
3955: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
3956: }
3957: for(cpt=1; cpt<=nlstate;cpt++) {
3958: fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
3959: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
3960: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);
3961: }
3962: fprintf(fichtm,"\n<br>- Total life expectancy by age and \
3963: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
3964: true period expectancies (those weighted with period prevalences are also\
3965: drawn in addition to the population based expectancies computed using\
3966: observed and cahotic prevalences: %s%d.png<br>\
3967: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
3968: } /* end i1 */
3969: }/* End k1 */
3970: fprintf(fichtm,"</ul>");
3971: fflush(fichtm);
3972: }
3973:
3974: /******************* Gnuplot file **************/
3975: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
3976:
3977: char dirfileres[132],optfileres[132];
3978: int m0,cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
3979: int ng=0;
3980: /* if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
3981: /* printf("Problem with file %s",optionfilegnuplot); */
3982: /* fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
3983: /* } */
3984:
3985: /*#ifdef windows */
3986: fprintf(ficgp,"cd \"%s\" \n",pathc);
3987: /*#endif */
3988: m=pow(2,cptcoveff);
3989:
3990: strcpy(dirfileres,optionfilefiname);
3991: strcpy(optfileres,"vpl");
3992: /* 1eme*/
3993: for (cpt=1; cpt<= nlstate ; cpt ++) {
3994: for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
3995: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
3996: fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
3997: fprintf(ficgp,"set xlabel \"Age\" \n\
3998: set ylabel \"Probability\" \n\
3999: set ter png small size 320, 240\n\
4000: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
4001:
4002: for (i=1; i<= nlstate ; i ++) {
4003: if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
4004: else fprintf(ficgp," \%%*lf (\%%*lf)");
4005: }
4006: 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);
4007: for (i=1; i<= nlstate ; i ++) {
4008: if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
4009: else fprintf(ficgp," \%%*lf (\%%*lf)");
4010: }
4011: 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);
4012: for (i=1; i<= nlstate ; i ++) {
4013: if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
4014: else fprintf(ficgp," \%%*lf (\%%*lf)");
4015: }
4016: 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));
4017: }
4018: }
4019: /*2 eme*/
4020:
4021: for (k1=1; k1<= m ; k1 ++) {
4022: fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
4023: fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
4024:
4025: for (i=1; i<= nlstate+1 ; i ++) {
4026: k=2*i;
4027: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4028: for (j=1; j<= nlstate+1 ; j ++) {
4029: if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
4030: else fprintf(ficgp," \%%*lf (\%%*lf)");
4031: }
4032: if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
4033: else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
4034: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4035: for (j=1; j<= nlstate+1 ; j ++) {
4036: if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
4037: else fprintf(ficgp," \%%*lf (\%%*lf)");
4038: }
4039: fprintf(ficgp,"\" t\"\" w l lt 0,");
4040: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4041: for (j=1; j<= nlstate+1 ; j ++) {
4042: if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
4043: else fprintf(ficgp," \%%*lf (\%%*lf)");
4044: }
4045: if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
4046: else fprintf(ficgp,"\" t\"\" w l lt 0,");
4047: }
4048: }
4049:
4050: /*3eme*/
4051:
4052: for (k1=1; k1<= m ; k1 ++) {
4053: for (cpt=1; cpt<= nlstate ; cpt ++) {
4054: /* k=2+nlstate*(2*cpt-2); */
4055: k=2+(nlstate+1)*(cpt-1);
4056: fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
4057: fprintf(ficgp,"set ter png small size 320, 240\n\
4058: 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);
4059: /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4060: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4061: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4062: fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4063: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4064: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4065:
4066: */
4067: for (i=1; i< nlstate ; i ++) {
4068: 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);
4069: /* 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);*/
4070:
4071: }
4072: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
4073: }
4074: }
4075:
4076: /* CV preval stable (period) */
4077: for (k1=1; k1<= m ; k1 ++) {
4078: for (cpt=1; cpt<=nlstate ; cpt ++) {
4079: k=3;
4080: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
4081: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
4082: set ter png small size 320, 240\n\
4083: unset log y\n\
4084: plot [%.f:%.f] \"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",ageminpar,agemaxpar,subdirf2(fileres,"pij"),k1,k+cpt+1,k+1);
4085:
4086: for (i=1; i< nlstate ; i ++)
4087: fprintf(ficgp,"+$%d",k+i+1);
4088: fprintf(ficgp,")) t\"prev(%d,%d)\" w l",cpt,cpt+1);
4089:
4090: l=3+(nlstate+ndeath)*cpt;
4091: fprintf(ficgp,",\"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",subdirf2(fileres,"pij"),k1,l+cpt+1,l+1);
4092: for (i=1; i< nlstate ; i ++) {
4093: l=3+(nlstate+ndeath)*cpt;
4094: fprintf(ficgp,"+$%d",l+i+1);
4095: }
4096: fprintf(ficgp,")) t\"prev(%d,%d)\" w l\n",cpt+1,cpt+1);
4097: }
4098: }
4099:
4100: /* proba elementaires */
4101: for(i=1,jk=1; i <=nlstate; i++){
4102: for(k=1; k <=(nlstate+ndeath); k++){
4103: if (k != i) {
4104: for(j=1; j <=ncovmodel; j++){
4105: fprintf(ficgp,"p%d=%f ",jk,p[jk]);
4106: jk++;
4107: fprintf(ficgp,"\n");
4108: }
4109: }
4110: }
4111: }
4112: /*goto avoid;*/
4113: for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
4114: for(jk=1; jk <=m; jk++) {
4115: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);
4116: if (ng==2)
4117: fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
4118: else
4119: fprintf(ficgp,"\nset title \"Probability\"\n");
4120: fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot [%.f:%.f] ",ageminpar,agemaxpar);
4121: i=1;
4122: for(k2=1; k2<=nlstate; k2++) {
4123: k3=i;
4124: for(k=1; k<=(nlstate+ndeath); k++) {
4125: if (k != k2){
4126: if(ng==2)
4127: fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
4128: else
4129: fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
4130: ij=1;/* To be checked else nbcode[0][0] wrong */
4131: for(j=3; j <=ncovmodel; j++) {
4132: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /\* Bug valgrind *\/ */
4133: /* /\*fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);*\/ */
4134: /* ij++; */
4135: /* } */
4136: /* else */
4137: fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4138: }
4139: fprintf(ficgp,")/(1");
4140:
4141: for(k1=1; k1 <=nlstate; k1++){
4142: fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
4143: ij=1;
4144: for(j=3; j <=ncovmodel; j++){
4145: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { */
4146: /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]); */
4147: /* ij++; */
4148: /* } */
4149: /* else */
4150: fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4151: }
4152: fprintf(ficgp,")");
4153: }
4154: fprintf(ficgp,") t \"p%d%d\" ", k2,k);
4155: if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
4156: i=i+ncovmodel;
4157: }
4158: } /* end k */
4159: } /* end k2 */
4160: } /* end jk */
4161: } /* end ng */
4162: avoid:
4163: fflush(ficgp);
4164: } /* end gnuplot */
4165:
4166:
4167: /*************** Moving average **************/
4168: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
4169:
4170: int i, cpt, cptcod;
4171: int modcovmax =1;
4172: int mobilavrange, mob;
4173: double age;
4174:
4175: modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
4176: a covariate has 2 modalities */
4177: if (cptcovn<1) modcovmax=1; /* At least 1 pass */
4178:
4179: if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
4180: if(mobilav==1) mobilavrange=5; /* default */
4181: else mobilavrange=mobilav;
4182: for (age=bage; age<=fage; age++)
4183: for (i=1; i<=nlstate;i++)
4184: for (cptcod=1;cptcod<=modcovmax;cptcod++)
4185: mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
4186: /* We keep the original values on the extreme ages bage, fage and for
4187: fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
4188: we use a 5 terms etc. until the borders are no more concerned.
4189: */
4190: for (mob=3;mob <=mobilavrange;mob=mob+2){
4191: for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
4192: for (i=1; i<=nlstate;i++){
4193: for (cptcod=1;cptcod<=modcovmax;cptcod++){
4194: mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
4195: for (cpt=1;cpt<=(mob-1)/2;cpt++){
4196: mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
4197: mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
4198: }
4199: mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
4200: }
4201: }
4202: }/* end age */
4203: }/* end mob */
4204: }else return -1;
4205: return 0;
4206: }/* End movingaverage */
4207:
4208:
4209: /************** Forecasting ******************/
4210: 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){
4211: /* proj1, year, month, day of starting projection
4212: agemin, agemax range of age
4213: dateprev1 dateprev2 range of dates during which prevalence is computed
4214: anproj2 year of en of projection (same day and month as proj1).
4215: */
4216: int yearp, stepsize, hstepm, nhstepm, j, k, c, cptcod, i, h, i1;
4217: int *popage;
4218: double agec; /* generic age */
4219: double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
4220: double *popeffectif,*popcount;
4221: double ***p3mat;
4222: double ***mobaverage;
4223: char fileresf[FILENAMELENGTH];
4224:
4225: agelim=AGESUP;
4226: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4227:
4228: strcpy(fileresf,"f");
4229: strcat(fileresf,fileres);
4230: if((ficresf=fopen(fileresf,"w"))==NULL) {
4231: printf("Problem with forecast resultfile: %s\n", fileresf);
4232: fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
4233: }
4234: printf("Computing forecasting: result on file '%s' \n", fileresf);
4235: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
4236:
4237: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4238:
4239: if (mobilav!=0) {
4240: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4241: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4242: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4243: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4244: }
4245: }
4246:
4247: stepsize=(int) (stepm+YEARM-1)/YEARM;
4248: if (stepm<=12) stepsize=1;
4249: if(estepm < stepm){
4250: printf ("Problem %d lower than %d\n",estepm, stepm);
4251: }
4252: else hstepm=estepm;
4253:
4254: hstepm=hstepm/stepm;
4255: yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp and
4256: fractional in yp1 */
4257: anprojmean=yp;
4258: yp2=modf((yp1*12),&yp);
4259: mprojmean=yp;
4260: yp1=modf((yp2*30.5),&yp);
4261: jprojmean=yp;
4262: if(jprojmean==0) jprojmean=1;
4263: if(mprojmean==0) jprojmean=1;
4264:
4265: i1=cptcoveff;
4266: if (cptcovn < 1){i1=1;}
4267:
4268: fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
4269:
4270: fprintf(ficresf,"#****** Routine prevforecast **\n");
4271:
4272: /* if (h==(int)(YEARM*yearp)){ */
4273: for(cptcov=1, k=0;cptcov<=i1;cptcov++){
4274: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4275: k=k+1;
4276: fprintf(ficresf,"\n#******");
4277: for(j=1;j<=cptcoveff;j++) {
4278: 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]]);
4279: }
4280: fprintf(ficresf,"******\n");
4281: fprintf(ficresf,"# Covariate valuofcovar yearproj age");
4282: for(j=1; j<=nlstate+ndeath;j++){
4283: for(i=1; i<=nlstate;i++)
4284: fprintf(ficresf," p%d%d",i,j);
4285: fprintf(ficresf," p.%d",j);
4286: }
4287: for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
4288: fprintf(ficresf,"\n");
4289: fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);
4290:
4291: for (agec=fage; agec>=(ageminpar-1); agec--){
4292: nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
4293: nhstepm = nhstepm/hstepm;
4294: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4295: oldm=oldms;savm=savms;
4296: hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
4297:
4298: for (h=0; h<=nhstepm; h++){
4299: if (h*hstepm/YEARM*stepm ==yearp) {
4300: fprintf(ficresf,"\n");
4301: for(j=1;j<=cptcoveff;j++)
4302: fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4303: fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
4304: }
4305: for(j=1; j<=nlstate+ndeath;j++) {
4306: ppij=0.;
4307: for(i=1; i<=nlstate;i++) {
4308: if (mobilav==1)
4309: ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
4310: else {
4311: ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
4312: }
4313: if (h*hstepm/YEARM*stepm== yearp) {
4314: fprintf(ficresf," %.3f", p3mat[i][j][h]);
4315: }
4316: } /* end i */
4317: if (h*hstepm/YEARM*stepm==yearp) {
4318: fprintf(ficresf," %.3f", ppij);
4319: }
4320: }/* end j */
4321: } /* end h */
4322: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4323: } /* end agec */
4324: } /* end yearp */
4325: } /* end cptcod */
4326: } /* end cptcov */
4327:
4328: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4329:
4330: fclose(ficresf);
4331: }
4332:
4333: /************** Forecasting *****not tested NB*************/
4334: 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){
4335:
4336: int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
4337: int *popage;
4338: double calagedatem, agelim, kk1, kk2;
4339: double *popeffectif,*popcount;
4340: double ***p3mat,***tabpop,***tabpopprev;
4341: double ***mobaverage;
4342: char filerespop[FILENAMELENGTH];
4343:
4344: tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4345: tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4346: agelim=AGESUP;
4347: calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
4348:
4349: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4350:
4351:
4352: strcpy(filerespop,"pop");
4353: strcat(filerespop,fileres);
4354: if((ficrespop=fopen(filerespop,"w"))==NULL) {
4355: printf("Problem with forecast resultfile: %s\n", filerespop);
4356: fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
4357: }
4358: printf("Computing forecasting: result on file '%s' \n", filerespop);
4359: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
4360:
4361: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4362:
4363: if (mobilav!=0) {
4364: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4365: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4366: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4367: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4368: }
4369: }
4370:
4371: stepsize=(int) (stepm+YEARM-1)/YEARM;
4372: if (stepm<=12) stepsize=1;
4373:
4374: agelim=AGESUP;
4375:
4376: hstepm=1;
4377: hstepm=hstepm/stepm;
4378:
4379: if (popforecast==1) {
4380: if((ficpop=fopen(popfile,"r"))==NULL) {
4381: printf("Problem with population file : %s\n",popfile);exit(0);
4382: fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
4383: }
4384: popage=ivector(0,AGESUP);
4385: popeffectif=vector(0,AGESUP);
4386: popcount=vector(0,AGESUP);
4387:
4388: i=1;
4389: while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
4390:
4391: imx=i;
4392: for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
4393: }
4394:
4395: for(cptcov=1,k=0;cptcov<=i2;cptcov++){
4396: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4397: k=k+1;
4398: fprintf(ficrespop,"\n#******");
4399: for(j=1;j<=cptcoveff;j++) {
4400: fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4401: }
4402: fprintf(ficrespop,"******\n");
4403: fprintf(ficrespop,"# Age");
4404: for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
4405: if (popforecast==1) fprintf(ficrespop," [Population]");
4406:
4407: for (cpt=0; cpt<=0;cpt++) {
4408: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4409:
4410: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4411: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4412: nhstepm = nhstepm/hstepm;
4413:
4414: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4415: oldm=oldms;savm=savms;
4416: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4417:
4418: for (h=0; h<=nhstepm; h++){
4419: if (h==(int) (calagedatem+YEARM*cpt)) {
4420: fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4421: }
4422: for(j=1; j<=nlstate+ndeath;j++) {
4423: kk1=0.;kk2=0;
4424: for(i=1; i<=nlstate;i++) {
4425: if (mobilav==1)
4426: kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
4427: else {
4428: kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
4429: }
4430: }
4431: if (h==(int)(calagedatem+12*cpt)){
4432: tabpop[(int)(agedeb)][j][cptcod]=kk1;
4433: /*fprintf(ficrespop," %.3f", kk1);
4434: if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
4435: }
4436: }
4437: for(i=1; i<=nlstate;i++){
4438: kk1=0.;
4439: for(j=1; j<=nlstate;j++){
4440: kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
4441: }
4442: tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
4443: }
4444:
4445: if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
4446: fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
4447: }
4448: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4449: }
4450: }
4451:
4452: /******/
4453:
4454: for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
4455: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4456: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4457: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4458: nhstepm = nhstepm/hstepm;
4459:
4460: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4461: oldm=oldms;savm=savms;
4462: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4463: for (h=0; h<=nhstepm; h++){
4464: if (h==(int) (calagedatem+YEARM*cpt)) {
4465: fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4466: }
4467: for(j=1; j<=nlstate+ndeath;j++) {
4468: kk1=0.;kk2=0;
4469: for(i=1; i<=nlstate;i++) {
4470: kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];
4471: }
4472: if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);
4473: }
4474: }
4475: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4476: }
4477: }
4478: }
4479: }
4480:
4481: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4482:
4483: if (popforecast==1) {
4484: free_ivector(popage,0,AGESUP);
4485: free_vector(popeffectif,0,AGESUP);
4486: free_vector(popcount,0,AGESUP);
4487: }
4488: free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4489: free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4490: fclose(ficrespop);
4491: } /* End of popforecast */
4492:
4493: int fileappend(FILE *fichier, char *optionfich)
4494: {
4495: if((fichier=fopen(optionfich,"a"))==NULL) {
4496: printf("Problem with file: %s\n", optionfich);
4497: fprintf(ficlog,"Problem with file: %s\n", optionfich);
4498: return (0);
4499: }
4500: fflush(fichier);
4501: return (1);
4502: }
4503:
4504:
4505: /**************** function prwizard **********************/
4506: void prwizard(int ncovmodel, int nlstate, int ndeath, char model[], FILE *ficparo)
4507: {
4508:
4509: /* Wizard to print covariance matrix template */
4510:
4511: char ca[32], cb[32], cc[32];
4512: int i,j, k, l, li, lj, lk, ll, jj, npar, itimes;
4513: int numlinepar;
4514:
4515: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4516: fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4517: for(i=1; i <=nlstate; i++){
4518: jj=0;
4519: for(j=1; j <=nlstate+ndeath; j++){
4520: if(j==i) continue;
4521: jj++;
4522: /*ca[0]= k+'a'-1;ca[1]='\0';*/
4523: printf("%1d%1d",i,j);
4524: fprintf(ficparo,"%1d%1d",i,j);
4525: for(k=1; k<=ncovmodel;k++){
4526: /* printf(" %lf",param[i][j][k]); */
4527: /* fprintf(ficparo," %lf",param[i][j][k]); */
4528: printf(" 0.");
4529: fprintf(ficparo," 0.");
4530: }
4531: printf("\n");
4532: fprintf(ficparo,"\n");
4533: }
4534: }
4535: printf("# Scales (for hessian or gradient estimation)\n");
4536: fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
4537: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
4538: for(i=1; i <=nlstate; i++){
4539: jj=0;
4540: for(j=1; j <=nlstate+ndeath; j++){
4541: if(j==i) continue;
4542: jj++;
4543: fprintf(ficparo,"%1d%1d",i,j);
4544: printf("%1d%1d",i,j);
4545: fflush(stdout);
4546: for(k=1; k<=ncovmodel;k++){
4547: /* printf(" %le",delti3[i][j][k]); */
4548: /* fprintf(ficparo," %le",delti3[i][j][k]); */
4549: printf(" 0.");
4550: fprintf(ficparo," 0.");
4551: }
4552: numlinepar++;
4553: printf("\n");
4554: fprintf(ficparo,"\n");
4555: }
4556: }
4557: printf("# Covariance matrix\n");
4558: /* # 121 Var(a12)\n\ */
4559: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4560: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
4561: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
4562: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
4563: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
4564: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
4565: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4566: fflush(stdout);
4567: fprintf(ficparo,"# Covariance matrix\n");
4568: /* # 121 Var(a12)\n\ */
4569: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4570: /* # ...\n\ */
4571: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4572:
4573: for(itimes=1;itimes<=2;itimes++){
4574: jj=0;
4575: for(i=1; i <=nlstate; i++){
4576: for(j=1; j <=nlstate+ndeath; j++){
4577: if(j==i) continue;
4578: for(k=1; k<=ncovmodel;k++){
4579: jj++;
4580: ca[0]= k+'a'-1;ca[1]='\0';
4581: if(itimes==1){
4582: printf("#%1d%1d%d",i,j,k);
4583: fprintf(ficparo,"#%1d%1d%d",i,j,k);
4584: }else{
4585: printf("%1d%1d%d",i,j,k);
4586: fprintf(ficparo,"%1d%1d%d",i,j,k);
4587: /* printf(" %.5le",matcov[i][j]); */
4588: }
4589: ll=0;
4590: for(li=1;li <=nlstate; li++){
4591: for(lj=1;lj <=nlstate+ndeath; lj++){
4592: if(lj==li) continue;
4593: for(lk=1;lk<=ncovmodel;lk++){
4594: ll++;
4595: if(ll<=jj){
4596: cb[0]= lk +'a'-1;cb[1]='\0';
4597: if(ll<jj){
4598: if(itimes==1){
4599: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4600: fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4601: }else{
4602: printf(" 0.");
4603: fprintf(ficparo," 0.");
4604: }
4605: }else{
4606: if(itimes==1){
4607: printf(" Var(%s%1d%1d)",ca,i,j);
4608: fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
4609: }else{
4610: printf(" 0.");
4611: fprintf(ficparo," 0.");
4612: }
4613: }
4614: }
4615: } /* end lk */
4616: } /* end lj */
4617: } /* end li */
4618: printf("\n");
4619: fprintf(ficparo,"\n");
4620: numlinepar++;
4621: } /* end k*/
4622: } /*end j */
4623: } /* end i */
4624: } /* end itimes */
4625:
4626: } /* end of prwizard */
4627: /******************* Gompertz Likelihood ******************************/
4628: double gompertz(double x[])
4629: {
4630: double A,B,L=0.0,sump=0.,num=0.;
4631: int i,n=0; /* n is the size of the sample */
4632:
4633: for (i=0;i<=imx-1 ; i++) {
4634: sump=sump+weight[i];
4635: /* sump=sump+1;*/
4636: num=num+1;
4637: }
4638:
4639:
4640: /* for (i=0; i<=imx; i++)
4641: 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]);*/
4642:
4643: for (i=1;i<=imx ; i++)
4644: {
4645: if (cens[i] == 1 && wav[i]>1)
4646: A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
4647:
4648: if (cens[i] == 0 && wav[i]>1)
4649: A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
4650: +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);
4651:
4652: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
4653: if (wav[i] > 1 ) { /* ??? */
4654: L=L+A*weight[i];
4655: /* 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]);*/
4656: }
4657: }
4658:
4659: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
4660:
4661: return -2*L*num/sump;
4662: }
4663:
4664: #ifdef GSL
4665: /******************* Gompertz_f Likelihood ******************************/
4666: double gompertz_f(const gsl_vector *v, void *params)
4667: {
4668: double A,B,LL=0.0,sump=0.,num=0.;
4669: double *x= (double *) v->data;
4670: int i,n=0; /* n is the size of the sample */
4671:
4672: for (i=0;i<=imx-1 ; i++) {
4673: sump=sump+weight[i];
4674: /* sump=sump+1;*/
4675: num=num+1;
4676: }
4677:
4678:
4679: /* for (i=0; i<=imx; i++)
4680: 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]);*/
4681: printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
4682: for (i=1;i<=imx ; i++)
4683: {
4684: if (cens[i] == 1 && wav[i]>1)
4685: A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
4686:
4687: if (cens[i] == 0 && wav[i]>1)
4688: A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
4689: +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);
4690:
4691: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
4692: if (wav[i] > 1 ) { /* ??? */
4693: LL=LL+A*weight[i];
4694: /* 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]);*/
4695: }
4696: }
4697:
4698: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
4699: printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
4700:
4701: return -2*LL*num/sump;
4702: }
4703: #endif
4704:
4705: /******************* Printing html file ***********/
4706: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
4707: int lastpass, int stepm, int weightopt, char model[],\
4708: int imx, double p[],double **matcov,double agemortsup){
4709: int i,k;
4710:
4711: fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
4712: fprintf(fichtm," mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
4713: for (i=1;i<=2;i++)
4714: 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]));
4715: fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
4716: fprintf(fichtm,"</ul>");
4717:
4718: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
4719:
4720: 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>");
4721:
4722: for (k=agegomp;k<(agemortsup-2);k++)
4723: 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]);
4724:
4725:
4726: fflush(fichtm);
4727: }
4728:
4729: /******************* Gnuplot file **************/
4730: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4731:
4732: char dirfileres[132],optfileres[132];
4733: int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;
4734: int ng;
4735:
4736:
4737: /*#ifdef windows */
4738: fprintf(ficgp,"cd \"%s\" \n",pathc);
4739: /*#endif */
4740:
4741:
4742: strcpy(dirfileres,optionfilefiname);
4743: strcpy(optfileres,"vpl");
4744: fprintf(ficgp,"set out \"graphmort.png\"\n ");
4745: fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
4746: fprintf(ficgp, "set ter png small size 320, 240\n set log y\n");
4747: /* fprintf(ficgp, "set size 0.65,0.65\n"); */
4748: fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
4749:
4750: }
4751:
4752: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
4753: {
4754:
4755: /*-------- data file ----------*/
4756: FILE *fic;
4757: char dummy[]=" ";
4758: int i, j, n;
4759: int linei, month, year,iout;
4760: char line[MAXLINE], linetmp[MAXLINE];
4761: char stra[80], strb[80];
4762: char *stratrunc;
4763: int lstra;
4764:
4765:
4766: if((fic=fopen(datafile,"r"))==NULL) {
4767: printf("Problem while opening datafile: %s\n", datafile);return 1;
4768: fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
4769: }
4770:
4771: i=1;
4772: linei=0;
4773: while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
4774: linei=linei+1;
4775: for(j=strlen(line); j>=0;j--){ /* Untabifies line */
4776: if(line[j] == '\t')
4777: line[j] = ' ';
4778: }
4779: for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
4780: ;
4781: };
4782: line[j+1]=0; /* Trims blanks at end of line */
4783: if(line[0]=='#'){
4784: fprintf(ficlog,"Comment line\n%s\n",line);
4785: printf("Comment line\n%s\n",line);
4786: continue;
4787: }
4788: trimbb(linetmp,line); /* Trims multiple blanks in line */
4789: for (j=0; line[j]!='\0';j++){
4790: line[j]=linetmp[j];
4791: }
4792:
4793:
4794: for (j=maxwav;j>=1;j--){
4795: cutv(stra, strb, line, ' ');
4796: if(strb[0]=='.') { /* Missing status */
4797: lval=-1;
4798: }else{
4799: errno=0;
4800: lval=strtol(strb,&endptr,10);
4801: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
4802: if( strb[0]=='\0' || (*endptr != '\0')){
4803: 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);
4804: 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);
4805: return 1;
4806: }
4807: }
4808: s[j][i]=lval;
4809:
4810: strcpy(line,stra);
4811: cutv(stra, strb,line,' ');
4812: if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
4813: }
4814: else if(iout=sscanf(strb,"%s.",dummy) != 0){
4815: month=99;
4816: year=9999;
4817: }else{
4818: 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);
4819: 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);
4820: return 1;
4821: }
4822: anint[j][i]= (double) year;
4823: mint[j][i]= (double)month;
4824: strcpy(line,stra);
4825: } /* ENd Waves */
4826:
4827: cutv(stra, strb,line,' ');
4828: if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
4829: }
4830: else if(iout=sscanf(strb,"%s.",dummy) != 0){
4831: month=99;
4832: year=9999;
4833: }else{
4834: 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);
4835: 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);
4836: return 1;
4837: }
4838: andc[i]=(double) year;
4839: moisdc[i]=(double) month;
4840: strcpy(line,stra);
4841:
4842: cutv(stra, strb,line,' ');
4843: if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
4844: }
4845: else if(iout=sscanf(strb,"%s.", dummy) != 0){
4846: month=99;
4847: year=9999;
4848: }else{
4849: 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);
4850: 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);
4851: return 1;
4852: }
4853: if (year==9999) {
4854: 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);
4855: 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);
4856: return 1;
4857:
4858: }
4859: annais[i]=(double)(year);
4860: moisnais[i]=(double)(month);
4861: strcpy(line,stra);
4862:
4863: cutv(stra, strb,line,' ');
4864: errno=0;
4865: dval=strtod(strb,&endptr);
4866: if( strb[0]=='\0' || (*endptr != '\0')){
4867: printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight. Exiting.\n",dval, i,line,linei);
4868: 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);
4869: fflush(ficlog);
4870: return 1;
4871: }
4872: weight[i]=dval;
4873: strcpy(line,stra);
4874:
4875: for (j=ncovcol;j>=1;j--){
4876: cutv(stra, strb,line,' ');
4877: if(strb[0]=='.') { /* Missing status */
4878: lval=-1;
4879: }else{
4880: errno=0;
4881: lval=strtol(strb,&endptr,10);
4882: if( strb[0]=='\0' || (*endptr != '\0')){
4883: 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);
4884: 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);
4885: return 1;
4886: }
4887: }
4888: if(lval <-1 || lval >1){
4889: printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
4890: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
4891: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
4892: For example, for multinomial values like 1, 2 and 3,\n \
4893: build V1=0 V2=0 for the reference value (1),\n \
4894: V1=1 V2=0 for (2) \n \
4895: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
4896: output of IMaCh is often meaningless.\n \
4897: Exiting.\n",lval,linei, i,line,j);
4898: fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
4899: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
4900: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
4901: For example, for multinomial values like 1, 2 and 3,\n \
4902: build V1=0 V2=0 for the reference value (1),\n \
4903: V1=1 V2=0 for (2) \n \
4904: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
4905: output of IMaCh is often meaningless.\n \
4906: Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
4907: return 1;
4908: }
4909: covar[j][i]=(double)(lval);
4910: strcpy(line,stra);
4911: }
4912: lstra=strlen(stra);
4913:
4914: if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
4915: stratrunc = &(stra[lstra-9]);
4916: num[i]=atol(stratrunc);
4917: }
4918: else
4919: num[i]=atol(stra);
4920: /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
4921: 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;}*/
4922:
4923: i=i+1;
4924: } /* End loop reading data */
4925:
4926: *imax=i-1; /* Number of individuals */
4927: fclose(fic);
4928:
4929: return (0);
4930: endread:
4931: printf("Exiting readdata: ");
4932: fclose(fic);
4933: return (1);
4934:
4935:
4936:
4937: }
4938: void removespace(char *str) {
4939: char *p1 = str, *p2 = str;
4940: do
4941: while (*p2 == ' ')
4942: p2++;
4943: while (*p1++ = *p2++);
4944: }
4945:
4946: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
4947: * Model V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age
4948: * - cptcovt total number of covariates of the model nbocc(+)+1 = 8
4949: * - cptcovn or number of covariates k of the models excluding age*products =6
4950: * - cptcovage number of covariates with age*products =2
4951: * - cptcovs number of simple covariates
4952: * - 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
4953: * which is a new column after the 9 (ncovcol) variables.
4954: * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
4955: * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
4956: * Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
4957: * - Tvard[k] p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
4958: */
4959: {
4960: int i, j, k, ks;
4961: int i1, j1, k1, k2;
4962: char modelsav[80];
4963: char stra[80], strb[80], strc[80], strd[80],stre[80];
4964:
4965: /*removespace(model);*/
4966: if (strlen(model) >1){ /* If there is at least 1 covariate */
4967: j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
4968: j=nbocc(model,'+'); /**< j=Number of '+' */
4969: j1=nbocc(model,'*'); /**< j1=Number of '*' */
4970: cptcovs=j+1-j1; /**< Number of simple covariates V1+V2*age+V3 +V3*V4=> V1 + V3 =2 */
4971: cptcovt= j+1; /* Number of total covariates in the model V1 + V2*age+ V3 + V3*V4=> 4*/
4972: /* including age products which are counted in cptcovage.
4973: /* but the covariates which are products must be treated separately: ncovn=4- 2=2 (V1+V3). */
4974: cptcovprod=j1; /**< Number of products V1*V2 +v3*age = 2 */
4975: cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1 */
4976: strcpy(modelsav,model);
4977: if (strstr(model,"AGE") !=0){
4978: printf("Error. AGE must be in lower case 'age' model=%s ",model);
4979: fprintf(ficlog,"Error. AGE must be in lower case model=%s ",model);fflush(ficlog);
4980: return 1;
4981: }
4982: if (strstr(model,"v") !=0){
4983: printf("Error. 'v' must be in upper case 'V' model=%s ",model);
4984: fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
4985: return 1;
4986: }
4987:
4988: /* Design
4989: * V1 V2 V3 V4 V5 V6 V7 V8 V9 Weight
4990: * < ncovcol=8 >
4991: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
4992: * k= 1 2 3 4 5 6 7 8
4993: * cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
4994: * covar[k,i], value of kth covariate if not including age for individual i:
4995: * covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
4996: * Tvar[k] # of the kth covariate: Tvar[1]=2 Tvar[4]=3 Tvar[8]=8
4997: * if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and
4998: * Tage[++cptcovage]=k
4999: * if products, new covar are created after ncovcol with k1
5000: * Tvar[k]=ncovcol+k1; # of the kth covariate product: Tvar[5]=ncovcol+1=10 Tvar[6]=ncovcol+1=11
5001: * Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
5002: * 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
5003: * Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
5004: * Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
5005: * V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
5006: * < ncovcol=8 >
5007: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 d1 d1 d2 d2
5008: * k= 1 2 3 4 5 6 7 8 9 10 11 12
5009: * Tvar[k]= 2 1 3 3 10 11 8 8 5 6 7 8
5010: * p Tvar[1]@12={2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5011: * p Tprod[1]@2={ 6, 5}
5012: *p Tvard[1][1]@4= {7, 8, 5, 6}
5013: * covar[k][i]= V2 V1 ? V3 V5*V6? V7*V8? ? V8
5014: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
5015: *How to reorganize?
5016: * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
5017: * Tvars {2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5018: * {2, 1, 4, 8, 5, 6, 3, 7}
5019: * Struct []
5020: */
5021:
5022: /* This loop fills the array Tvar from the string 'model'.*/
5023: /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
5024: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 */
5025: /* k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
5026: /* k=3 V4 Tvar[k=3]= 4 (from V4) */
5027: /* k=2 V1 Tvar[k=2]= 1 (from V1) */
5028: /* k=1 Tvar[1]=2 (from V2) */
5029: /* k=5 Tvar[5] */
5030: /* for (k=1; k<=cptcovn;k++) { */
5031: /* cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
5032: /* } */
5033: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
5034: /*
5035: * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
5036: for(k=cptcovt; k>=1;k--) /**< Number of covariates */
5037: Tvar[k]=0;
5038: cptcovage=0;
5039: for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
5040: cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+'
5041: modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */
5042: if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
5043: /* printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
5044: /*scanf("%d",i);*/
5045: if (strchr(strb,'*')) { /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
5046: cutl(strc,strd,strb,'*'); /**< strd*strc Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
5047: if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
5048: /* covar is not filled and then is empty */
5049: cptcovprod--;
5050: cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
5051: Tvar[k]=atoi(stre); /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2 */
5052: cptcovage++; /* Sums the number of covariates which include age as a product */
5053: Tage[cptcovage]=k; /* Tage[1] = 4 */
5054: /*printf("stre=%s ", stre);*/
5055: } else if (strcmp(strd,"age")==0) { /* or age*Vn */
5056: cptcovprod--;
5057: cutl(stre,strb,strc,'V');
5058: Tvar[k]=atoi(stre);
5059: cptcovage++;
5060: Tage[cptcovage]=k;
5061: } else { /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2 strb=V3*V2*/
5062: /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
5063: cptcovn++;
5064: cptcovprodnoage++;k1++;
5065: cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
5066: Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
5067: because this model-covariate is a construction we invent a new column
5068: ncovcol + k1
5069: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
5070: Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
5071: cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
5072: Tprod[k1]=k; /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 */
5073: Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
5074: Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
5075: k2=k2+2;
5076: Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
5077: Tvar[cptcovt+k2+1]=Tvard[k1][2]; /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
5078: for (i=1; i<=lastobs;i++){
5079: /* Computes the new covariate which is a product of
5080: covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
5081: covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
5082: }
5083: } /* End age is not in the model */
5084: } /* End if model includes a product */
5085: else { /* no more sum */
5086: /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
5087: /* scanf("%d",i);*/
5088: cutl(strd,strc,strb,'V');
5089: ks++; /**< Number of simple covariates */
5090: cptcovn++;
5091: Tvar[k]=atoi(strd);
5092: }
5093: strcpy(modelsav,stra); /* modelsav=V2+V1+V4 stra=V2+V1+V4 */
5094: /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
5095: scanf("%d",i);*/
5096: } /* end of loop + */
5097: } /* end model */
5098:
5099: /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
5100: If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
5101:
5102: /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
5103: printf("cptcovprod=%d ", cptcovprod);
5104: fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
5105:
5106: scanf("%d ",i);*/
5107:
5108:
5109: return (0); /* with covar[new additional covariate if product] and Tage if age */
5110: endread:
5111: printf("Exiting decodemodel: ");
5112: return (1);
5113: }
5114:
5115: calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
5116: {
5117: int i, m;
5118:
5119: for (i=1; i<=imx; i++) {
5120: for(m=2; (m<= maxwav); m++) {
5121: if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
5122: anint[m][i]=9999;
5123: s[m][i]=-1;
5124: }
5125: if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
5126: *nberr++;
5127: 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);
5128: 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);
5129: s[m][i]=-1;
5130: }
5131: if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
5132: *nberr++;
5133: 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]);
5134: 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]);
5135: s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
5136: }
5137: }
5138: }
5139:
5140: for (i=1; i<=imx; i++) {
5141: agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
5142: for(m=firstpass; (m<= lastpass); m++){
5143: if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
5144: if (s[m][i] >= nlstate+1) {
5145: if(agedc[i]>0)
5146: if((int)moisdc[i]!=99 && (int)andc[i]!=9999)
5147: agev[m][i]=agedc[i];
5148: /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
5149: else {
5150: if ((int)andc[i]!=9999){
5151: nbwarn++;
5152: printf("Warning negative age at death: %ld line:%d\n",num[i],i);
5153: fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
5154: agev[m][i]=-1;
5155: }
5156: }
5157: }
5158: else if(s[m][i] !=9){ /* Standard case, age in fractional
5159: years but with the precision of a month */
5160: agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
5161: if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
5162: agev[m][i]=1;
5163: else if(agev[m][i] < *agemin){
5164: *agemin=agev[m][i];
5165: printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
5166: }
5167: else if(agev[m][i] >*agemax){
5168: *agemax=agev[m][i];
5169: printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);
5170: }
5171: /*agev[m][i]=anint[m][i]-annais[i];*/
5172: /* agev[m][i] = age[i]+2*m;*/
5173: }
5174: else { /* =9 */
5175: agev[m][i]=1;
5176: s[m][i]=-1;
5177: }
5178: }
5179: else /*= 0 Unknown */
5180: agev[m][i]=1;
5181: }
5182:
5183: }
5184: for (i=1; i<=imx; i++) {
5185: for(m=firstpass; (m<=lastpass); m++){
5186: if (s[m][i] > (nlstate+ndeath)) {
5187: *nberr++;
5188: 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);
5189: 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);
5190: return 1;
5191: }
5192: }
5193: }
5194:
5195: /*for (i=1; i<=imx; i++){
5196: for (m=firstpass; (m<lastpass); m++){
5197: printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
5198: }
5199:
5200: }*/
5201:
5202:
5203: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
5204: fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
5205:
5206: return (0);
5207: endread:
5208: printf("Exiting calandcheckages: ");
5209: return (1);
5210: }
5211:
5212:
5213: /***********************************************/
5214: /**************** Main Program *****************/
5215: /***********************************************/
5216:
5217: int main(int argc, char *argv[])
5218: {
5219: #ifdef GSL
5220: const gsl_multimin_fminimizer_type *T;
5221: size_t iteri = 0, it;
5222: int rval = GSL_CONTINUE;
5223: int status = GSL_SUCCESS;
5224: double ssval;
5225: #endif
5226: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
5227: int i,j, k, n=MAXN,iter,m,size=100,cptcode, cptcod;
5228: int linei, month, year,iout;
5229: int jj, ll, li, lj, lk, imk;
5230: int numlinepar=0; /* Current linenumber of parameter file */
5231: int itimes;
5232: int NDIM=2;
5233: int vpopbased=0;
5234:
5235: char ca[32], cb[32], cc[32];
5236: /* FILE *fichtm; *//* Html File */
5237: /* FILE *ficgp;*/ /*Gnuplot File */
5238: struct stat info;
5239: double agedeb, agefin,hf;
5240: double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
5241:
5242: double fret;
5243: double **xi,tmp,delta;
5244:
5245: double dum; /* Dummy variable */
5246: double ***p3mat;
5247: double ***mobaverage;
5248: int *indx;
5249: char line[MAXLINE], linepar[MAXLINE];
5250: char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
5251: char pathr[MAXLINE], pathimach[MAXLINE];
5252: char **bp, *tok, *val; /* pathtot */
5253: int firstobs=1, lastobs=10;
5254: int sdeb, sfin; /* Status at beginning and end */
5255: int c, h , cpt,l;
5256: int ju,jl, mi;
5257: int i1,j1, jk,aa,bb, stepsize, ij;
5258: int jnais,jdc,jint4,jint1,jint2,jint3,*tab;
5259: int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
5260: int mobilav=0,popforecast=0;
5261: int hstepm, nhstepm;
5262: int agemortsup;
5263: float sumlpop=0.;
5264: double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
5265: double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
5266:
5267: double bage, fage, age, agelim, agebase;
5268: double ftolpl=FTOL;
5269: double **prlim;
5270: double ***param; /* Matrix of parameters */
5271: double *p;
5272: double **matcov; /* Matrix of covariance */
5273: double ***delti3; /* Scale */
5274: double *delti; /* Scale */
5275: double ***eij, ***vareij;
5276: double **varpl; /* Variances of prevalence limits by age */
5277: double *epj, vepp;
5278: double kk1, kk2;
5279: double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
5280: double **ximort;
5281: char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
5282: int *dcwave;
5283:
5284: char z[1]="c", occ;
5285:
5286: /*char *strt;*/
5287: char strtend[80];
5288:
5289: long total_usecs;
5290:
5291: /* setlocale (LC_ALL, ""); */
5292: /* bindtextdomain (PACKAGE, LOCALEDIR); */
5293: /* textdomain (PACKAGE); */
5294: /* setlocale (LC_CTYPE, ""); */
5295: /* setlocale (LC_MESSAGES, ""); */
5296:
5297: /* gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
5298: (void) gettimeofday(&start_time,&tzp);
5299: curr_time=start_time;
5300: tm = *localtime(&start_time.tv_sec);
5301: tmg = *gmtime(&start_time.tv_sec);
5302: strcpy(strstart,asctime(&tm));
5303:
5304: /* printf("Localtime (at start)=%s",strstart); */
5305: /* tp.tv_sec = tp.tv_sec +86400; */
5306: /* tm = *localtime(&start_time.tv_sec); */
5307: /* tmg.tm_year=tmg.tm_year +dsign*dyear; */
5308: /* tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
5309: /* tmg.tm_hour=tmg.tm_hour + 1; */
5310: /* tp.tv_sec = mktime(&tmg); */
5311: /* strt=asctime(&tmg); */
5312: /* printf("Time(after) =%s",strstart); */
5313: /* (void) time (&time_value);
5314: * printf("time=%d,t-=%d\n",time_value,time_value-86400);
5315: * tm = *localtime(&time_value);
5316: * strstart=asctime(&tm);
5317: * printf("tim_value=%d,asctime=%s\n",time_value,strstart);
5318: */
5319:
5320: nberr=0; /* Number of errors and warnings */
5321: nbwarn=0;
5322: getcwd(pathcd, size);
5323:
5324: printf("\n%s\n%s",version,fullversion);
5325: if(argc <=1){
5326: printf("\nEnter the parameter file name: ");
5327: fgets(pathr,FILENAMELENGTH,stdin);
5328: i=strlen(pathr);
5329: if(pathr[i-1]=='\n')
5330: pathr[i-1]='\0';
5331: for (tok = pathr; tok != NULL; ){
5332: printf("Pathr |%s|\n",pathr);
5333: while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
5334: printf("val= |%s| pathr=%s\n",val,pathr);
5335: strcpy (pathtot, val);
5336: if(pathr[0] == '\0') break; /* Dirty */
5337: }
5338: }
5339: else{
5340: strcpy(pathtot,argv[1]);
5341: }
5342: /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
5343: /*cygwin_split_path(pathtot,path,optionfile);
5344: printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
5345: /* cutv(path,optionfile,pathtot,'\\');*/
5346:
5347: /* Split argv[0], imach program to get pathimach */
5348: printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
5349: split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
5350: printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
5351: /* strcpy(pathimach,argv[0]); */
5352: /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
5353: split(pathtot,path,optionfile,optionfilext,optionfilefiname);
5354: printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
5355: chdir(path); /* Can be a relative path */
5356: if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
5357: printf("Current directory %s!\n",pathcd);
5358: strcpy(command,"mkdir ");
5359: strcat(command,optionfilefiname);
5360: if((outcmd=system(command)) != 0){
5361: printf("Problem creating directory or it already exists %s%s, err=%d\n",path,optionfilefiname,outcmd);
5362: /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
5363: /* fclose(ficlog); */
5364: /* exit(1); */
5365: }
5366: /* if((imk=mkdir(optionfilefiname))<0){ */
5367: /* perror("mkdir"); */
5368: /* } */
5369:
5370: /*-------- arguments in the command line --------*/
5371:
5372: /* Log file */
5373: strcat(filelog, optionfilefiname);
5374: strcat(filelog,".log"); /* */
5375: if((ficlog=fopen(filelog,"w"))==NULL) {
5376: printf("Problem with logfile %s\n",filelog);
5377: goto end;
5378: }
5379: fprintf(ficlog,"Log filename:%s\n",filelog);
5380: fprintf(ficlog,"\n%s\n%s",version,fullversion);
5381: fprintf(ficlog,"\nEnter the parameter file name: \n");
5382: fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
5383: path=%s \n\
5384: optionfile=%s\n\
5385: optionfilext=%s\n\
5386: optionfilefiname=%s\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
5387:
5388: printf("Local time (at start):%s",strstart);
5389: fprintf(ficlog,"Local time (at start): %s",strstart);
5390: fflush(ficlog);
5391: /* (void) gettimeofday(&curr_time,&tzp); */
5392: /* printf("Elapsed time %d\n", asc_diff_time(curr_time.tv_sec-start_time.tv_sec,tmpout)); */
5393:
5394: /* */
5395: strcpy(fileres,"r");
5396: strcat(fileres, optionfilefiname);
5397: strcat(fileres,".txt"); /* Other files have txt extension */
5398:
5399: /*---------arguments file --------*/
5400:
5401: if((ficpar=fopen(optionfile,"r"))==NULL) {
5402: printf("Problem with optionfile %s with errno=%s\n",optionfile,strerror(errno));
5403: fprintf(ficlog,"Problem with optionfile %s with errno=%s\n",optionfile,strerror(errno));
5404: fflush(ficlog);
5405: /* goto end; */
5406: exit(70);
5407: }
5408:
5409:
5410:
5411: strcpy(filereso,"o");
5412: strcat(filereso,fileres);
5413: if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
5414: printf("Problem with Output resultfile: %s\n", filereso);
5415: fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
5416: fflush(ficlog);
5417: goto end;
5418: }
5419:
5420: /* Reads comments: lines beginning with '#' */
5421: numlinepar=0;
5422: while((c=getc(ficpar))=='#' && c!= EOF){
5423: ungetc(c,ficpar);
5424: fgets(line, MAXLINE, ficpar);
5425: numlinepar++;
5426: fputs(line,stdout);
5427: fputs(line,ficparo);
5428: fputs(line,ficlog);
5429: }
5430: ungetc(c,ficpar);
5431:
5432: 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);
5433: numlinepar++;
5434: 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);
5435: 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);
5436: 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);
5437: fflush(ficlog);
5438: while((c=getc(ficpar))=='#' && c!= EOF){
5439: ungetc(c,ficpar);
5440: fgets(line, MAXLINE, ficpar);
5441: numlinepar++;
5442: fputs(line, stdout);
5443: //puts(line);
5444: fputs(line,ficparo);
5445: fputs(line,ficlog);
5446: }
5447: ungetc(c,ficpar);
5448:
5449:
5450: covar=matrix(0,NCOVMAX,1,n); /**< used in readdata */
5451: cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
5452: /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
5453: v1+v2*age+v2*v3 makes cptcovn = 3
5454: */
5455: if (strlen(model)>1)
5456: 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*/
5457: else
5458: ncovmodel=2;
5459: nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
5460: nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
5461: npar= nforce*ncovmodel; /* Number of parameters like aij*/
5462: if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
5463: 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);
5464: 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);
5465: fflush(stdout);
5466: fclose (ficlog);
5467: goto end;
5468: }
5469: delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5470: delti=delti3[1][1];
5471: /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
5472: if(mle==-1){ /* Print a wizard for help writing covariance matrix */
5473: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
5474: printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
5475: fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
5476: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
5477: fclose (ficparo);
5478: fclose (ficlog);
5479: goto end;
5480: exit(0);
5481: }
5482: else if(mle==-3) {
5483: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
5484: printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
5485: fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
5486: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5487: matcov=matrix(1,npar,1,npar);
5488: }
5489: else{
5490: /* Read guessed parameters */
5491: /* Reads comments: lines beginning with '#' */
5492: while((c=getc(ficpar))=='#' && c!= EOF){
5493: ungetc(c,ficpar);
5494: fgets(line, MAXLINE, ficpar);
5495: numlinepar++;
5496: fputs(line,stdout);
5497: fputs(line,ficparo);
5498: fputs(line,ficlog);
5499: }
5500: ungetc(c,ficpar);
5501:
5502: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5503: for(i=1; i <=nlstate; i++){
5504: j=0;
5505: for(jj=1; jj <=nlstate+ndeath; jj++){
5506: if(jj==i) continue;
5507: j++;
5508: fscanf(ficpar,"%1d%1d",&i1,&j1);
5509: if ((i1 != i) && (j1 != j)){
5510: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
5511: It might be a problem of design; if ncovcol and the model are correct\n \
5512: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
5513: exit(1);
5514: }
5515: fprintf(ficparo,"%1d%1d",i1,j1);
5516: if(mle==1)
5517: printf("%1d%1d",i,j);
5518: fprintf(ficlog,"%1d%1d",i,j);
5519: for(k=1; k<=ncovmodel;k++){
5520: fscanf(ficpar," %lf",¶m[i][j][k]);
5521: if(mle==1){
5522: printf(" %lf",param[i][j][k]);
5523: fprintf(ficlog," %lf",param[i][j][k]);
5524: }
5525: else
5526: fprintf(ficlog," %lf",param[i][j][k]);
5527: fprintf(ficparo," %lf",param[i][j][k]);
5528: }
5529: fscanf(ficpar,"\n");
5530: numlinepar++;
5531: if(mle==1)
5532: printf("\n");
5533: fprintf(ficlog,"\n");
5534: fprintf(ficparo,"\n");
5535: }
5536: }
5537: fflush(ficlog);
5538:
5539: /* Reads scales values */
5540: p=param[1][1];
5541:
5542: /* Reads comments: lines beginning with '#' */
5543: while((c=getc(ficpar))=='#' && c!= EOF){
5544: ungetc(c,ficpar);
5545: fgets(line, MAXLINE, ficpar);
5546: numlinepar++;
5547: fputs(line,stdout);
5548: fputs(line,ficparo);
5549: fputs(line,ficlog);
5550: }
5551: ungetc(c,ficpar);
5552:
5553: for(i=1; i <=nlstate; i++){
5554: for(j=1; j <=nlstate+ndeath-1; j++){
5555: fscanf(ficpar,"%1d%1d",&i1,&j1);
5556: if ((i1-i)*(j1-j)!=0){
5557: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
5558: exit(1);
5559: }
5560: printf("%1d%1d",i,j);
5561: fprintf(ficparo,"%1d%1d",i1,j1);
5562: fprintf(ficlog,"%1d%1d",i1,j1);
5563: for(k=1; k<=ncovmodel;k++){
5564: fscanf(ficpar,"%le",&delti3[i][j][k]);
5565: printf(" %le",delti3[i][j][k]);
5566: fprintf(ficparo," %le",delti3[i][j][k]);
5567: fprintf(ficlog," %le",delti3[i][j][k]);
5568: }
5569: fscanf(ficpar,"\n");
5570: numlinepar++;
5571: printf("\n");
5572: fprintf(ficparo,"\n");
5573: fprintf(ficlog,"\n");
5574: }
5575: }
5576: fflush(ficlog);
5577:
5578: /* Reads covariance matrix */
5579: delti=delti3[1][1];
5580:
5581:
5582: /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
5583:
5584: /* Reads comments: lines beginning with '#' */
5585: while((c=getc(ficpar))=='#' && c!= EOF){
5586: ungetc(c,ficpar);
5587: fgets(line, MAXLINE, ficpar);
5588: numlinepar++;
5589: fputs(line,stdout);
5590: fputs(line,ficparo);
5591: fputs(line,ficlog);
5592: }
5593: ungetc(c,ficpar);
5594:
5595: matcov=matrix(1,npar,1,npar);
5596: for(i=1; i <=npar; i++)
5597: for(j=1; j <=npar; j++) matcov[i][j]=0.;
5598:
5599: for(i=1; i <=npar; i++){
5600: fscanf(ficpar,"%s",str);
5601: if(mle==1)
5602: printf("%s",str);
5603: fprintf(ficlog,"%s",str);
5604: fprintf(ficparo,"%s",str);
5605: for(j=1; j <=i; j++){
5606: fscanf(ficpar," %le",&matcov[i][j]);
5607: if(mle==1){
5608: printf(" %.5le",matcov[i][j]);
5609: }
5610: fprintf(ficlog," %.5le",matcov[i][j]);
5611: fprintf(ficparo," %.5le",matcov[i][j]);
5612: }
5613: fscanf(ficpar,"\n");
5614: numlinepar++;
5615: if(mle==1)
5616: printf("\n");
5617: fprintf(ficlog,"\n");
5618: fprintf(ficparo,"\n");
5619: }
5620: for(i=1; i <=npar; i++)
5621: for(j=i+1;j<=npar;j++)
5622: matcov[i][j]=matcov[j][i];
5623:
5624: if(mle==1)
5625: printf("\n");
5626: fprintf(ficlog,"\n");
5627:
5628: fflush(ficlog);
5629:
5630: /*-------- Rewriting parameter file ----------*/
5631: strcpy(rfileres,"r"); /* "Rparameterfile */
5632: strcat(rfileres,optionfilefiname); /* Parameter file first name*/
5633: strcat(rfileres,"."); /* */
5634: strcat(rfileres,optionfilext); /* Other files have txt extension */
5635: if((ficres =fopen(rfileres,"w"))==NULL) {
5636: printf("Problem writing new parameter file: %s\n", fileres);goto end;
5637: fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
5638: }
5639: fprintf(ficres,"#%s\n",version);
5640: } /* End of mle != -3 */
5641:
5642:
5643: n= lastobs;
5644: num=lvector(1,n);
5645: moisnais=vector(1,n);
5646: annais=vector(1,n);
5647: moisdc=vector(1,n);
5648: andc=vector(1,n);
5649: agedc=vector(1,n);
5650: cod=ivector(1,n);
5651: weight=vector(1,n);
5652: for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
5653: mint=matrix(1,maxwav,1,n);
5654: anint=matrix(1,maxwav,1,n);
5655: s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */
5656: tab=ivector(1,NCOVMAX);
5657: ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
5658:
5659: /* Reads data from file datafile */
5660: if (readdata(datafile, firstobs, lastobs, &imx)==1)
5661: goto end;
5662:
5663: /* Calculation of the number of parameters from char model */
5664: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4
5665: k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
5666: k=3 V4 Tvar[k=3]= 4 (from V4)
5667: k=2 V1 Tvar[k=2]= 1 (from V1)
5668: k=1 Tvar[1]=2 (from V2)
5669: */
5670: Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
5671: /* V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs).
5672: For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4,
5673: Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
5674: */
5675: /* For model-covariate k tells which data-covariate to use but
5676: because this model-covariate is a construction we invent a new column
5677: ncovcol + k1
5678: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
5679: Tvar[3=V1*V4]=4+1 etc */
5680: Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
5681: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
5682: if V2+V1+V1*V4+age*V3+V3*V2 TProd[k1=2]=5 (V3*V2)
5683: */
5684: Tvaraff=ivector(1,NCOVMAX); /* Unclear */
5685: 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
5686: * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd.
5687: * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
5688: Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
5689: 4 covariates (3 plus signs)
5690: Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
5691: */
5692:
5693: if(decodemodel(model, lastobs) == 1)
5694: goto end;
5695:
5696: if((double)(lastobs-imx)/(double)imx > 1.10){
5697: nbwarn++;
5698: 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);
5699: 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);
5700: }
5701: /* if(mle==1){*/
5702: if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
5703: for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
5704: }
5705:
5706: /*-calculation of age at interview from date of interview and age at death -*/
5707: agev=matrix(1,maxwav,1,imx);
5708:
5709: if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
5710: goto end;
5711:
5712:
5713: agegomp=(int)agemin;
5714: free_vector(moisnais,1,n);
5715: free_vector(annais,1,n);
5716: /* free_matrix(mint,1,maxwav,1,n);
5717: free_matrix(anint,1,maxwav,1,n);*/
5718: free_vector(moisdc,1,n);
5719: free_vector(andc,1,n);
5720: /* */
5721:
5722: wav=ivector(1,imx);
5723: dh=imatrix(1,lastpass-firstpass+1,1,imx);
5724: bh=imatrix(1,lastpass-firstpass+1,1,imx);
5725: mw=imatrix(1,lastpass-firstpass+1,1,imx);
5726:
5727: /* Concatenates waves */
5728: concatwav(wav, dh, bh, mw, s, agedc, agev, firstpass, lastpass, imx, nlstate, stepm);
5729: /* */
5730:
5731: /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
5732:
5733: nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
5734: ncodemax[1]=1;
5735: Ndum =ivector(-1,NCOVMAX);
5736: if (ncovmodel > 2)
5737: tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
5738:
5739: codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
5740: /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
5741: h=0;
5742:
5743:
5744: /*if (cptcovn > 0) */
5745:
5746:
5747: m=pow(2,cptcoveff);
5748:
5749: for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
5750: 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 */
5751: for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
5752: for(cpt=1; cpt <=pow(2,k-1); cpt++){ /* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 */
5753: h++;
5754: if (h>m)
5755: h=1;
5756: /**< codtab(h,k) k = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
5757: * h 1 2 3 4
5758: *______________________________
5759: * 1 i=1 1 i=1 1 i=1 1 i=1 1
5760: * 2 2 1 1 1
5761: * 3 i=2 1 2 1 1
5762: * 4 2 2 1 1
5763: * 5 i=3 1 i=2 1 2 1
5764: * 6 2 1 2 1
5765: * 7 i=4 1 2 2 1
5766: * 8 2 2 2 1
5767: * 9 i=5 1 i=3 1 i=2 1 1
5768: * 10 2 1 1 1
5769: * 11 i=6 1 2 1 1
5770: * 12 2 2 1 1
5771: * 13 i=7 1 i=4 1 2 1
5772: * 14 2 1 2 1
5773: * 15 i=8 1 2 2 1
5774: * 16 2 2 2 1
5775: */
5776: codtab[h][k]=j;
5777: /*codtab[h][Tvar[k]]=j;*/
5778: 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]]);
5779: }
5780: }
5781: }
5782: }
5783: /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
5784: codtab[1][2]=1;codtab[2][2]=2; */
5785: /* for(i=1; i <=m ;i++){
5786: for(k=1; k <=cptcovn; k++){
5787: printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
5788: }
5789: printf("\n");
5790: }
5791: scanf("%d",i);*/
5792:
5793: free_ivector(Ndum,-1,NCOVMAX);
5794:
5795:
5796:
5797: /*------------ gnuplot -------------*/
5798: strcpy(optionfilegnuplot,optionfilefiname);
5799: if(mle==-3)
5800: strcat(optionfilegnuplot,"-mort");
5801: strcat(optionfilegnuplot,".gp");
5802:
5803: if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
5804: printf("Problem with file %s",optionfilegnuplot);
5805: }
5806: else{
5807: fprintf(ficgp,"\n# %s\n", version);
5808: fprintf(ficgp,"# %s\n", optionfilegnuplot);
5809: //fprintf(ficgp,"set missing 'NaNq'\n");
5810: fprintf(ficgp,"set datafile missing 'NaNq'\n");
5811: }
5812: /* fclose(ficgp);*/
5813: /*--------- index.htm --------*/
5814:
5815: strcpy(optionfilehtm,optionfilefiname); /* Main html file */
5816: if(mle==-3)
5817: strcat(optionfilehtm,"-mort");
5818: strcat(optionfilehtm,".htm");
5819: if((fichtm=fopen(optionfilehtm,"w"))==NULL) {
5820: printf("Problem with %s \n",optionfilehtm);
5821: exit(0);
5822: }
5823:
5824: strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
5825: strcat(optionfilehtmcov,"-cov.htm");
5826: if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL) {
5827: printf("Problem with %s \n",optionfilehtmcov), exit(0);
5828: }
5829: else{
5830: fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
5831: <hr size=\"2\" color=\"#EC5E5E\"> \n\
5832: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
5833: optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
5834: }
5835:
5836: fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
5837: <hr size=\"2\" color=\"#EC5E5E\"> \n\
5838: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
5839: \n\
5840: <hr size=\"2\" color=\"#EC5E5E\">\
5841: <ul><li><h4>Parameter files</h4>\n\
5842: - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
5843: - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
5844: - Log file of the run: <a href=\"%s\">%s</a><br>\n\
5845: - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
5846: - Date and time at start: %s</ul>\n",\
5847: optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
5848: optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
5849: fileres,fileres,\
5850: filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
5851: fflush(fichtm);
5852:
5853: strcpy(pathr,path);
5854: strcat(pathr,optionfilefiname);
5855: chdir(optionfilefiname); /* Move to directory named optionfile */
5856:
5857: /* Calculates basic frequencies. Computes observed prevalence at single age
5858: and prints on file fileres'p'. */
5859: freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
5860:
5861: fprintf(fichtm,"\n");
5862: fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
5863: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
5864: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
5865: imx,agemin,agemax,jmin,jmax,jmean);
5866: pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
5867: oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
5868: newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
5869: savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
5870: oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
5871:
5872:
5873: /* For Powell, parameters are in a vector p[] starting at p[1]
5874: so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
5875: p=param[1][1]; /* *(*(*(param +1)+1)+0) */
5876:
5877: globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
5878:
5879: if (mle==-3){
5880: ximort=matrix(1,NDIM,1,NDIM);
5881: /* ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
5882: cens=ivector(1,n);
5883: ageexmed=vector(1,n);
5884: agecens=vector(1,n);
5885: dcwave=ivector(1,n);
5886:
5887: for (i=1; i<=imx; i++){
5888: dcwave[i]=-1;
5889: for (m=firstpass; m<=lastpass; m++)
5890: if (s[m][i]>nlstate) {
5891: dcwave[i]=m;
5892: /* printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
5893: break;
5894: }
5895: }
5896:
5897: for (i=1; i<=imx; i++) {
5898: if (wav[i]>0){
5899: ageexmed[i]=agev[mw[1][i]][i];
5900: j=wav[i];
5901: agecens[i]=1.;
5902:
5903: if (ageexmed[i]> 1 && wav[i] > 0){
5904: agecens[i]=agev[mw[j][i]][i];
5905: cens[i]= 1;
5906: }else if (ageexmed[i]< 1)
5907: cens[i]= -1;
5908: if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
5909: cens[i]=0 ;
5910: }
5911: else cens[i]=-1;
5912: }
5913:
5914: for (i=1;i<=NDIM;i++) {
5915: for (j=1;j<=NDIM;j++)
5916: ximort[i][j]=(i == j ? 1.0 : 0.0);
5917: }
5918:
5919: /*p[1]=0.0268; p[NDIM]=0.083;*/
5920: /*printf("%lf %lf", p[1], p[2]);*/
5921:
5922:
5923: #ifdef GSL
5924: printf("GSL optimization\n"); fprintf(ficlog,"Powell\n");
5925: #elsedef
5926: printf("Powell\n"); fprintf(ficlog,"Powell\n");
5927: #endif
5928: strcpy(filerespow,"pow-mort");
5929: strcat(filerespow,fileres);
5930: if((ficrespow=fopen(filerespow,"w"))==NULL) {
5931: printf("Problem with resultfile: %s\n", filerespow);
5932: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
5933: }
5934: #ifdef GSL
5935: fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
5936: #elsedef
5937: fprintf(ficrespow,"# Powell\n# iter -2*LL");
5938: #endif
5939: /* for (i=1;i<=nlstate;i++)
5940: for(j=1;j<=nlstate+ndeath;j++)
5941: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
5942: */
5943: fprintf(ficrespow,"\n");
5944: #ifdef GSL
5945: /* gsl starts here */
5946: T = gsl_multimin_fminimizer_nmsimplex;
5947: gsl_multimin_fminimizer *sfm = NULL;
5948: gsl_vector *ss, *x;
5949: gsl_multimin_function minex_func;
5950:
5951: /* Initial vertex size vector */
5952: ss = gsl_vector_alloc (NDIM);
5953:
5954: if (ss == NULL){
5955: GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
5956: }
5957: /* Set all step sizes to 1 */
5958: gsl_vector_set_all (ss, 0.001);
5959:
5960: /* Starting point */
5961:
5962: x = gsl_vector_alloc (NDIM);
5963:
5964: if (x == NULL){
5965: gsl_vector_free(ss);
5966: GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
5967: }
5968:
5969: /* Initialize method and iterate */
5970: /* p[1]=0.0268; p[NDIM]=0.083; */
5971: /* gsl_vector_set(x, 0, 0.0268); */
5972: /* gsl_vector_set(x, 1, 0.083); */
5973: gsl_vector_set(x, 0, p[1]);
5974: gsl_vector_set(x, 1, p[2]);
5975:
5976: minex_func.f = &gompertz_f;
5977: minex_func.n = NDIM;
5978: minex_func.params = (void *)&p; /* ??? */
5979:
5980: sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
5981: gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
5982:
5983: printf("Iterations beginning .....\n\n");
5984: printf("Iter. # Intercept Slope -Log Likelihood Simplex size\n");
5985:
5986: iteri=0;
5987: while (rval == GSL_CONTINUE){
5988: iteri++;
5989: status = gsl_multimin_fminimizer_iterate(sfm);
5990:
5991: if (status) printf("error: %s\n", gsl_strerror (status));
5992: fflush(0);
5993:
5994: if (status)
5995: break;
5996:
5997: rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
5998: ssval = gsl_multimin_fminimizer_size (sfm);
5999:
6000: if (rval == GSL_SUCCESS)
6001: printf ("converged to a local maximum at\n");
6002:
6003: printf("%5d ", iteri);
6004: for (it = 0; it < NDIM; it++){
6005: printf ("%10.5f ", gsl_vector_get (sfm->x, it));
6006: }
6007: printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
6008: }
6009:
6010: printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
6011:
6012: gsl_vector_free(x); /* initial values */
6013: gsl_vector_free(ss); /* inital step size */
6014: for (it=0; it<NDIM; it++){
6015: p[it+1]=gsl_vector_get(sfm->x,it);
6016: fprintf(ficrespow," %.12lf", p[it]);
6017: }
6018: gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1) */
6019: #endif
6020: #ifdef POWELL
6021: powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
6022: #endif
6023: fclose(ficrespow);
6024:
6025: hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);
6026:
6027: for(i=1; i <=NDIM; i++)
6028: for(j=i+1;j<=NDIM;j++)
6029: matcov[i][j]=matcov[j][i];
6030:
6031: printf("\nCovariance matrix\n ");
6032: for(i=1; i <=NDIM; i++) {
6033: for(j=1;j<=NDIM;j++){
6034: printf("%f ",matcov[i][j]);
6035: }
6036: printf("\n ");
6037: }
6038:
6039: printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
6040: for (i=1;i<=NDIM;i++)
6041: printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
6042:
6043: lsurv=vector(1,AGESUP);
6044: lpop=vector(1,AGESUP);
6045: tpop=vector(1,AGESUP);
6046: lsurv[agegomp]=100000;
6047:
6048: for (k=agegomp;k<=AGESUP;k++) {
6049: agemortsup=k;
6050: if (p[1]*exp(p[2]*(k-agegomp))>1) break;
6051: }
6052:
6053: for (k=agegomp;k<agemortsup;k++)
6054: lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
6055:
6056: for (k=agegomp;k<agemortsup;k++){
6057: lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
6058: sumlpop=sumlpop+lpop[k];
6059: }
6060:
6061: tpop[agegomp]=sumlpop;
6062: for (k=agegomp;k<(agemortsup-3);k++){
6063: /* tpop[k+1]=2;*/
6064: tpop[k+1]=tpop[k]-lpop[k];
6065: }
6066:
6067:
6068: printf("\nAge lx qx dx Lx Tx e(x)\n");
6069: for (k=agegomp;k<(agemortsup-2);k++)
6070: 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]);
6071:
6072:
6073: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6074: printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6075:
6076: printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
6077: stepm, weightopt,\
6078: model,imx,p,matcov,agemortsup);
6079:
6080: free_vector(lsurv,1,AGESUP);
6081: free_vector(lpop,1,AGESUP);
6082: free_vector(tpop,1,AGESUP);
6083: #ifdef GSL
6084: free_ivector(cens,1,n);
6085: free_vector(agecens,1,n);
6086: free_ivector(dcwave,1,n);
6087: free_matrix(ximort,1,NDIM,1,NDIM);
6088: #endif
6089: } /* Endof if mle==-3 */
6090:
6091: else{ /* For mle >=1 */
6092: globpr=0;/* debug */
6093: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
6094: printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6095: for (k=1; k<=npar;k++)
6096: printf(" %d %8.5f",k,p[k]);
6097: printf("\n");
6098: globpr=1; /* to print the contributions */
6099: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
6100: printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6101: for (k=1; k<=npar;k++)
6102: printf(" %d %8.5f",k,p[k]);
6103: printf("\n");
6104: if(mle>=1){ /* Could be 1 or 2 */
6105: mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
6106: }
6107:
6108: /*--------- results files --------------*/
6109: 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);
6110:
6111:
6112: fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6113: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6114: fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6115: for(i=1,jk=1; i <=nlstate; i++){
6116: for(k=1; k <=(nlstate+ndeath); k++){
6117: if (k != i) {
6118: printf("%d%d ",i,k);
6119: fprintf(ficlog,"%d%d ",i,k);
6120: fprintf(ficres,"%1d%1d ",i,k);
6121: for(j=1; j <=ncovmodel; j++){
6122: printf("%lf ",p[jk]);
6123: fprintf(ficlog,"%lf ",p[jk]);
6124: fprintf(ficres,"%lf ",p[jk]);
6125: jk++;
6126: }
6127: printf("\n");
6128: fprintf(ficlog,"\n");
6129: fprintf(ficres,"\n");
6130: }
6131: }
6132: }
6133: if(mle!=0){
6134: /* Computing hessian and covariance matrix */
6135: ftolhess=ftol; /* Usually correct */
6136: hesscov(matcov, p, npar, delti, ftolhess, func);
6137: }
6138: fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
6139: printf("# Scales (for hessian or gradient estimation)\n");
6140: fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
6141: for(i=1,jk=1; i <=nlstate; i++){
6142: for(j=1; j <=nlstate+ndeath; j++){
6143: if (j!=i) {
6144: fprintf(ficres,"%1d%1d",i,j);
6145: printf("%1d%1d",i,j);
6146: fprintf(ficlog,"%1d%1d",i,j);
6147: for(k=1; k<=ncovmodel;k++){
6148: printf(" %.5e",delti[jk]);
6149: fprintf(ficlog," %.5e",delti[jk]);
6150: fprintf(ficres," %.5e",delti[jk]);
6151: jk++;
6152: }
6153: printf("\n");
6154: fprintf(ficlog,"\n");
6155: fprintf(ficres,"\n");
6156: }
6157: }
6158: }
6159:
6160: 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");
6161: if(mle>=1)
6162: 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");
6163: 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");
6164: /* # 121 Var(a12)\n\ */
6165: /* # 122 Cov(b12,a12) Var(b12)\n\ */
6166: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
6167: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
6168: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
6169: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
6170: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
6171: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
6172:
6173:
6174: /* Just to have a covariance matrix which will be more understandable
6175: even is we still don't want to manage dictionary of variables
6176: */
6177: for(itimes=1;itimes<=2;itimes++){
6178: jj=0;
6179: for(i=1; i <=nlstate; i++){
6180: for(j=1; j <=nlstate+ndeath; j++){
6181: if(j==i) continue;
6182: for(k=1; k<=ncovmodel;k++){
6183: jj++;
6184: ca[0]= k+'a'-1;ca[1]='\0';
6185: if(itimes==1){
6186: if(mle>=1)
6187: printf("#%1d%1d%d",i,j,k);
6188: fprintf(ficlog,"#%1d%1d%d",i,j,k);
6189: fprintf(ficres,"#%1d%1d%d",i,j,k);
6190: }else{
6191: if(mle>=1)
6192: printf("%1d%1d%d",i,j,k);
6193: fprintf(ficlog,"%1d%1d%d",i,j,k);
6194: fprintf(ficres,"%1d%1d%d",i,j,k);
6195: }
6196: ll=0;
6197: for(li=1;li <=nlstate; li++){
6198: for(lj=1;lj <=nlstate+ndeath; lj++){
6199: if(lj==li) continue;
6200: for(lk=1;lk<=ncovmodel;lk++){
6201: ll++;
6202: if(ll<=jj){
6203: cb[0]= lk +'a'-1;cb[1]='\0';
6204: if(ll<jj){
6205: if(itimes==1){
6206: if(mle>=1)
6207: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6208: fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6209: fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6210: }else{
6211: if(mle>=1)
6212: printf(" %.5e",matcov[jj][ll]);
6213: fprintf(ficlog," %.5e",matcov[jj][ll]);
6214: fprintf(ficres," %.5e",matcov[jj][ll]);
6215: }
6216: }else{
6217: if(itimes==1){
6218: if(mle>=1)
6219: printf(" Var(%s%1d%1d)",ca,i,j);
6220: fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
6221: fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
6222: }else{
6223: if(mle>=1)
6224: printf(" %.5e",matcov[jj][ll]);
6225: fprintf(ficlog," %.5e",matcov[jj][ll]);
6226: fprintf(ficres," %.5e",matcov[jj][ll]);
6227: }
6228: }
6229: }
6230: } /* end lk */
6231: } /* end lj */
6232: } /* end li */
6233: if(mle>=1)
6234: printf("\n");
6235: fprintf(ficlog,"\n");
6236: fprintf(ficres,"\n");
6237: numlinepar++;
6238: } /* end k*/
6239: } /*end j */
6240: } /* end i */
6241: } /* end itimes */
6242:
6243: fflush(ficlog);
6244: fflush(ficres);
6245:
6246: while((c=getc(ficpar))=='#' && c!= EOF){
6247: ungetc(c,ficpar);
6248: fgets(line, MAXLINE, ficpar);
6249: fputs(line,stdout);
6250: fputs(line,ficparo);
6251: }
6252: ungetc(c,ficpar);
6253:
6254: estepm=0;
6255: fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
6256: if (estepm==0 || estepm < stepm) estepm=stepm;
6257: if (fage <= 2) {
6258: bage = ageminpar;
6259: fage = agemaxpar;
6260: }
6261:
6262: fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
6263: fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6264: fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6265:
6266: while((c=getc(ficpar))=='#' && c!= EOF){
6267: ungetc(c,ficpar);
6268: fgets(line, MAXLINE, ficpar);
6269: fputs(line,stdout);
6270: fputs(line,ficparo);
6271: }
6272: ungetc(c,ficpar);
6273:
6274: 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);
6275: 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);
6276: 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);
6277: printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
6278: 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);
6279:
6280: while((c=getc(ficpar))=='#' && c!= EOF){
6281: ungetc(c,ficpar);
6282: fgets(line, MAXLINE, ficpar);
6283: fputs(line,stdout);
6284: fputs(line,ficparo);
6285: }
6286: ungetc(c,ficpar);
6287:
6288:
6289: dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
6290: dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
6291:
6292: fscanf(ficpar,"pop_based=%d\n",&popbased);
6293: fprintf(ficparo,"pop_based=%d\n",popbased);
6294: fprintf(ficres,"pop_based=%d\n",popbased);
6295:
6296: while((c=getc(ficpar))=='#' && c!= EOF){
6297: ungetc(c,ficpar);
6298: fgets(line, MAXLINE, ficpar);
6299: fputs(line,stdout);
6300: fputs(line,ficparo);
6301: }
6302: ungetc(c,ficpar);
6303:
6304: 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);
6305: 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);
6306: 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);
6307: 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);
6308: 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);
6309: /* day and month of proj2 are not used but only year anproj2.*/
6310:
6311:
6312:
6313: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
6314: /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
6315:
6316: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6317: printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6318:
6319: printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
6320: model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
6321: jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
6322:
6323: /*------------ free_vector -------------*/
6324: /* chdir(path); */
6325:
6326: free_ivector(wav,1,imx);
6327: free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
6328: free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
6329: free_imatrix(mw,1,lastpass-firstpass+1,1,imx);
6330: free_lvector(num,1,n);
6331: free_vector(agedc,1,n);
6332: /*free_matrix(covar,0,NCOVMAX,1,n);*/
6333: /*free_matrix(covar,1,NCOVMAX,1,n);*/
6334: fclose(ficparo);
6335: fclose(ficres);
6336:
6337:
6338: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
6339: #include "prevlim.h" /* Use ficrespl, ficlog */
6340: fclose(ficrespl);
6341:
6342: #ifdef FREEEXIT2
6343: #include "freeexit2.h"
6344: #endif
6345:
6346: /*------------- h Pij x at various ages ------------*/
6347: #include "hpijx.h"
6348: fclose(ficrespij);
6349:
6350: /*-------------- Variance of one-step probabilities---*/
6351: k=1;
6352: varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
6353:
6354:
6355: probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
6356: for(i=1;i<=AGESUP;i++)
6357: for(j=1;j<=NCOVMAX;j++)
6358: for(k=1;k<=NCOVMAX;k++)
6359: probs[i][j][k]=0.;
6360:
6361: /*---------- Forecasting ------------------*/
6362: /*if((stepm == 1) && (strcmp(model,".")==0)){*/
6363: if(prevfcast==1){
6364: /* if(stepm ==1){*/
6365: prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
6366: /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
6367: /* } */
6368: /* else{ */
6369: /* erreur=108; */
6370: /* 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); */
6371: /* 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); */
6372: /* } */
6373: }
6374:
6375:
6376: /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
6377:
6378: prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
6379: /* 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",\
6380: ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
6381: */
6382:
6383: if (mobilav!=0) {
6384: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
6385: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
6386: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
6387: printf(" Error in movingaverage mobilav=%d\n",mobilav);
6388: }
6389: }
6390:
6391:
6392: /*---------- Health expectancies, no variances ------------*/
6393:
6394: strcpy(filerese,"e");
6395: strcat(filerese,fileres);
6396: if((ficreseij=fopen(filerese,"w"))==NULL) {
6397: printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
6398: fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
6399: }
6400: printf("Computing Health Expectancies: result on file '%s' \n", filerese);
6401: fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
6402: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6403: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6404:
6405: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6406: fprintf(ficreseij,"\n#****** ");
6407: for(j=1;j<=cptcoveff;j++) {
6408: fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6409: }
6410: fprintf(ficreseij,"******\n");
6411:
6412: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6413: oldm=oldms;savm=savms;
6414: evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);
6415:
6416: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
6417: /*}*/
6418: }
6419: fclose(ficreseij);
6420:
6421:
6422: /*---------- Health expectancies and variances ------------*/
6423:
6424:
6425: strcpy(filerest,"t");
6426: strcat(filerest,fileres);
6427: if((ficrest=fopen(filerest,"w"))==NULL) {
6428: printf("Problem with total LE resultfile: %s\n", filerest);goto end;
6429: fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
6430: }
6431: printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
6432: fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
6433:
6434:
6435: strcpy(fileresstde,"stde");
6436: strcat(fileresstde,fileres);
6437: if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
6438: printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
6439: fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
6440: }
6441: printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
6442: fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
6443:
6444: strcpy(filerescve,"cve");
6445: strcat(filerescve,fileres);
6446: if((ficrescveij=fopen(filerescve,"w"))==NULL) {
6447: printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
6448: fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
6449: }
6450: printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
6451: fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
6452:
6453: strcpy(fileresv,"v");
6454: strcat(fileresv,fileres);
6455: if((ficresvij=fopen(fileresv,"w"))==NULL) {
6456: printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
6457: fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
6458: }
6459: printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
6460: fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
6461:
6462: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6463: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6464:
6465: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6466: fprintf(ficrest,"\n#****** ");
6467: for(j=1;j<=cptcoveff;j++)
6468: fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6469: fprintf(ficrest,"******\n");
6470:
6471: fprintf(ficresstdeij,"\n#****** ");
6472: fprintf(ficrescveij,"\n#****** ");
6473: for(j=1;j<=cptcoveff;j++) {
6474: fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6475: fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6476: }
6477: fprintf(ficresstdeij,"******\n");
6478: fprintf(ficrescveij,"******\n");
6479:
6480: fprintf(ficresvij,"\n#****** ");
6481: for(j=1;j<=cptcoveff;j++)
6482: fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6483: fprintf(ficresvij,"******\n");
6484:
6485: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6486: oldm=oldms;savm=savms;
6487: cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
6488: /*
6489: */
6490: /* goto endfree; */
6491:
6492: vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6493: pstamp(ficrest);
6494:
6495:
6496: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
6497: oldm=oldms;savm=savms; /* Segmentation fault */
6498: varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart);
6499: 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 ");
6500: if(vpopbased==1)
6501: 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);
6502: else
6503: fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
6504: fprintf(ficrest,"# Age e.. (std) ");
6505: for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
6506: fprintf(ficrest,"\n");
6507:
6508: epj=vector(1,nlstate+1);
6509: for(age=bage; age <=fage ;age++){
6510: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
6511: if (vpopbased==1) {
6512: if(mobilav ==0){
6513: for(i=1; i<=nlstate;i++)
6514: prlim[i][i]=probs[(int)age][i][k];
6515: }else{ /* mobilav */
6516: for(i=1; i<=nlstate;i++)
6517: prlim[i][i]=mobaverage[(int)age][i][k];
6518: }
6519: }
6520:
6521: fprintf(ficrest," %4.0f",age);
6522: for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
6523: for(i=1, epj[j]=0.;i <=nlstate;i++) {
6524: epj[j] += prlim[i][i]*eij[i][j][(int)age];
6525: /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
6526: }
6527: epj[nlstate+1] +=epj[j];
6528: }
6529:
6530: for(i=1, vepp=0.;i <=nlstate;i++)
6531: for(j=1;j <=nlstate;j++)
6532: vepp += vareij[i][j][(int)age];
6533: fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
6534: for(j=1;j <=nlstate;j++){
6535: fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
6536: }
6537: fprintf(ficrest,"\n");
6538: }
6539: }
6540: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
6541: free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
6542: free_vector(epj,1,nlstate+1);
6543: /*}*/
6544: }
6545: free_vector(weight,1,n);
6546: free_imatrix(Tvard,1,NCOVMAX,1,2);
6547: free_imatrix(s,1,maxwav+1,1,n);
6548: free_matrix(anint,1,maxwav,1,n);
6549: free_matrix(mint,1,maxwav,1,n);
6550: free_ivector(cod,1,n);
6551: free_ivector(tab,1,NCOVMAX);
6552: fclose(ficresstdeij);
6553: fclose(ficrescveij);
6554: fclose(ficresvij);
6555: fclose(ficrest);
6556: fclose(ficpar);
6557:
6558: /*------- Variance of period (stable) prevalence------*/
6559:
6560: strcpy(fileresvpl,"vpl");
6561: strcat(fileresvpl,fileres);
6562: if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
6563: printf("Problem with variance of period (stable) prevalence resultfile: %s\n", fileresvpl);
6564: exit(0);
6565: }
6566: printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
6567:
6568: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6569: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6570:
6571: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6572: fprintf(ficresvpl,"\n#****** ");
6573: for(j=1;j<=cptcoveff;j++)
6574: fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6575: fprintf(ficresvpl,"******\n");
6576:
6577: varpl=matrix(1,nlstate,(int) bage, (int) fage);
6578: oldm=oldms;savm=savms;
6579: varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
6580: free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
6581: /*}*/
6582: }
6583:
6584: fclose(ficresvpl);
6585:
6586: /*---------- End : free ----------------*/
6587: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
6588: free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
6589: } /* mle==-3 arrives here for freeing */
6590: endfree:
6591: free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
6592: free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
6593: free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
6594: free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
6595: free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
6596: free_matrix(covar,0,NCOVMAX,1,n);
6597: free_matrix(matcov,1,npar,1,npar);
6598: /*free_vector(delti,1,npar);*/
6599: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
6600: free_matrix(agev,1,maxwav,1,imx);
6601: free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
6602:
6603: free_ivector(ncodemax,1,NCOVMAX);
6604: free_ivector(Tvar,1,NCOVMAX);
6605: free_ivector(Tprod,1,NCOVMAX);
6606: free_ivector(Tvaraff,1,NCOVMAX);
6607: free_ivector(Tage,1,NCOVMAX);
6608:
6609: free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
6610: free_imatrix(codtab,1,100,1,10);
6611: fflush(fichtm);
6612: fflush(ficgp);
6613:
6614:
6615: if((nberr >0) || (nbwarn>0)){
6616: printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
6617: fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
6618: }else{
6619: printf("End of Imach\n");
6620: fprintf(ficlog,"End of Imach\n");
6621: }
6622: printf("See log file on %s\n",filelog);
6623: /* gettimeofday(&end_time, (struct timezone*)0);*/ /* after time */
6624: (void) gettimeofday(&end_time,&tzp);
6625: tm = *localtime(&end_time.tv_sec);
6626: tmg = *gmtime(&end_time.tv_sec);
6627: strcpy(strtend,asctime(&tm));
6628: printf("Local time at start %s\nLocal time at end %s",strstart, strtend);
6629: fprintf(ficlog,"Local time at start %s\nLocal time at end %s\n",strstart, strtend);
6630: printf("Total time used %s\n", asc_diff_time(end_time.tv_sec -start_time.tv_sec,tmpout));
6631:
6632: printf("Total time was %ld Sec.\n", end_time.tv_sec -start_time.tv_sec);
6633: fprintf(ficlog,"Total time used %s\n", asc_diff_time(end_time.tv_sec -start_time.tv_sec,tmpout));
6634: fprintf(ficlog,"Total time was %ld Sec.\n", end_time.tv_sec -start_time.tv_sec);
6635: /* printf("Total time was %d uSec.\n", total_usecs);*/
6636: /* if(fileappend(fichtm,optionfilehtm)){ */
6637: fprintf(fichtm,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
6638: fclose(fichtm);
6639: fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
6640: fclose(fichtmcov);
6641: fclose(ficgp);
6642: fclose(ficlog);
6643: /*------ End -----------*/
6644:
6645:
6646: printf("Before Current directory %s!\n",pathcd);
6647: if(chdir(pathcd) != 0)
6648: printf("Can't move to directory %s!\n",path);
6649: if(getcwd(pathcd,MAXLINE) > 0)
6650: printf("Current directory %s!\n",pathcd);
6651: /*strcat(plotcmd,CHARSEPARATOR);*/
6652: sprintf(plotcmd,"gnuplot");
6653: #ifndef UNIX
6654: sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
6655: #endif
6656: if(!stat(plotcmd,&info)){
6657: printf("Error gnuplot program not found: %s\n",plotcmd);fflush(stdout);
6658: if(!stat(getenv("GNUPLOTBIN"),&info)){
6659: printf("Error gnuplot program not found: %s Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
6660: }else
6661: strcpy(pplotcmd,plotcmd);
6662: #ifdef UNIX
6663: strcpy(plotcmd,GNUPLOTPROGRAM);
6664: if(!stat(plotcmd,&info)){
6665: printf("Error gnuplot program not found: %s\n",plotcmd);fflush(stdout);
6666: }else
6667: strcpy(pplotcmd,plotcmd);
6668: #endif
6669: }else
6670: strcpy(pplotcmd,plotcmd);
6671:
6672: sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
6673: printf("Starting graphs with: %s\n",plotcmd);fflush(stdout);
6674:
6675: if((outcmd=system(plotcmd)) != 0){
6676: printf("\n Problem with gnuplot command %s\n", plotcmd);
6677: printf("\n Trying on same directory\n");
6678: sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
6679: if((outcmd=system(plotcmd)) != 0)
6680: printf("\n Still a problem with gnuplot command %s\n", plotcmd);
6681: }
6682: printf(" Wait...");
6683: while (z[0] != 'q') {
6684: /* chdir(path); */
6685: printf("\nType e to edit output files, g to graph again and q for exiting: ");
6686: scanf("%s",z);
6687: /* if (z[0] == 'c') system("./imach"); */
6688: if (z[0] == 'e') {
6689: #ifdef OSX
6690: sprintf(pplotcmd, "open %s", optionfilehtm);
6691: #elsedef
6692: sprintf(pplotcmd, "%s", optionfilehtm);
6693: #enddef
6694: printf("Starting browser with: %s",plotcmd);fflush(stdout);
6695: system(plotcmd);
6696: }
6697: else if (z[0] == 'g') system(plotcmd);
6698: else if (z[0] == 'q') exit(0);
6699: }
6700: end:
6701: while (z[0] != 'q') {
6702: printf("\nType q for exiting: ");
6703: scanf("%s",z);
6704: }
6705: }
6706:
6707:
6708:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>