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