1: /* $Id: imach.c,v 1.162 2014/09/25 11:43:39 brouard Exp $
2: $State: Exp $
3: $Log: imach.c,v $
4: Revision 1.162 2014/09/25 11:43:39 brouard
5: Summary: temporary backup 0.99!
6:
7: Revision 1.1 2014/09/16 11:06:58 brouard
8: Summary: With some code (wrong) for nlopt
9:
10: Author:
11:
12: Revision 1.161 2014/09/15 20:41:41 brouard
13: Summary: Problem with macro SQR on Intel compiler
14:
15: Revision 1.160 2014/09/02 09:24:05 brouard
16: *** empty log message ***
17:
18: Revision 1.159 2014/09/01 10:34:10 brouard
19: Summary: WIN32
20: Author: Brouard
21:
22: Revision 1.158 2014/08/27 17:11:51 brouard
23: *** empty log message ***
24:
25: Revision 1.157 2014/08/27 16:26:55 brouard
26: Summary: Preparing windows Visual studio version
27: Author: Brouard
28:
29: In order to compile on Visual studio, time.h is now correct and time_t
30: and tm struct should be used. difftime should be used but sometimes I
31: just make the differences in raw time format (time(&now).
32: Trying to suppress #ifdef LINUX
33: Add xdg-open for __linux in order to open default browser.
34:
35: Revision 1.156 2014/08/25 20:10:10 brouard
36: *** empty log message ***
37:
38: Revision 1.155 2014/08/25 18:32:34 brouard
39: Summary: New compile, minor changes
40: Author: Brouard
41:
42: Revision 1.154 2014/06/20 17:32:08 brouard
43: Summary: Outputs now all graphs of convergence to period prevalence
44:
45: Revision 1.153 2014/06/20 16:45:46 brouard
46: Summary: If 3 live state, convergence to period prevalence on same graph
47: Author: Brouard
48:
49: Revision 1.152 2014/06/18 17:54:09 brouard
50: Summary: open browser, use gnuplot on same dir than imach if not found in the path
51:
52: Revision 1.151 2014/06/18 16:43:30 brouard
53: *** empty log message ***
54:
55: Revision 1.150 2014/06/18 16:42:35 brouard
56: Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
57: Author: brouard
58:
59: Revision 1.149 2014/06/18 15:51:14 brouard
60: Summary: Some fixes in parameter files errors
61: Author: Nicolas Brouard
62:
63: Revision 1.148 2014/06/17 17:38:48 brouard
64: Summary: Nothing new
65: Author: Brouard
66:
67: Just a new packaging for OS/X version 0.98nS
68:
69: Revision 1.147 2014/06/16 10:33:11 brouard
70: *** empty log message ***
71:
72: Revision 1.146 2014/06/16 10:20:28 brouard
73: Summary: Merge
74: Author: Brouard
75:
76: Merge, before building revised version.
77:
78: Revision 1.145 2014/06/10 21:23:15 brouard
79: Summary: Debugging with valgrind
80: Author: Nicolas Brouard
81:
82: Lot of changes in order to output the results with some covariates
83: After the Edimburgh REVES conference 2014, it seems mandatory to
84: improve the code.
85: No more memory valgrind error but a lot has to be done in order to
86: continue the work of splitting the code into subroutines.
87: Also, decodemodel has been improved. Tricode is still not
88: optimal. nbcode should be improved. Documentation has been added in
89: the source code.
90:
91: Revision 1.143 2014/01/26 09:45:38 brouard
92: Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
93:
94: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
95: (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
96:
97: Revision 1.142 2014/01/26 03:57:36 brouard
98: Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
99:
100: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
101:
102: Revision 1.141 2014/01/26 02:42:01 brouard
103: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
104:
105: Revision 1.140 2011/09/02 10:37:54 brouard
106: Summary: times.h is ok with mingw32 now.
107:
108: Revision 1.139 2010/06/14 07:50:17 brouard
109: After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
110: I remember having already fixed agemin agemax which are pointers now but not cvs saved.
111:
112: Revision 1.138 2010/04/30 18:19:40 brouard
113: *** empty log message ***
114:
115: Revision 1.137 2010/04/29 18:11:38 brouard
116: (Module): Checking covariates for more complex models
117: than V1+V2. A lot of change to be done. Unstable.
118:
119: Revision 1.136 2010/04/26 20:30:53 brouard
120: (Module): merging some libgsl code. Fixing computation
121: of likelione (using inter/intrapolation if mle = 0) in order to
122: get same likelihood as if mle=1.
123: Some cleaning of code and comments added.
124:
125: Revision 1.135 2009/10/29 15:33:14 brouard
126: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
127:
128: Revision 1.134 2009/10/29 13:18:53 brouard
129: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
130:
131: Revision 1.133 2009/07/06 10:21:25 brouard
132: just nforces
133:
134: Revision 1.132 2009/07/06 08:22:05 brouard
135: Many tings
136:
137: Revision 1.131 2009/06/20 16:22:47 brouard
138: Some dimensions resccaled
139:
140: Revision 1.130 2009/05/26 06:44:34 brouard
141: (Module): Max Covariate is now set to 20 instead of 8. A
142: lot of cleaning with variables initialized to 0. Trying to make
143: V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
144:
145: Revision 1.129 2007/08/31 13:49:27 lievre
146: Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
147:
148: Revision 1.128 2006/06/30 13:02:05 brouard
149: (Module): Clarifications on computing e.j
150:
151: Revision 1.127 2006/04/28 18:11:50 brouard
152: (Module): Yes the sum of survivors was wrong since
153: imach-114 because nhstepm was no more computed in the age
154: loop. Now we define nhstepma in the age loop.
155: (Module): In order to speed up (in case of numerous covariates) we
156: compute health expectancies (without variances) in a first step
157: and then all the health expectancies with variances or standard
158: deviation (needs data from the Hessian matrices) which slows the
159: computation.
160: In the future we should be able to stop the program is only health
161: expectancies and graph are needed without standard deviations.
162:
163: Revision 1.126 2006/04/28 17:23:28 brouard
164: (Module): Yes the sum of survivors was wrong since
165: imach-114 because nhstepm was no more computed in the age
166: loop. Now we define nhstepma in the age loop.
167: Version 0.98h
168:
169: Revision 1.125 2006/04/04 15:20:31 lievre
170: Errors in calculation of health expectancies. Age was not initialized.
171: Forecasting file added.
172:
173: Revision 1.124 2006/03/22 17:13:53 lievre
174: Parameters are printed with %lf instead of %f (more numbers after the comma).
175: The log-likelihood is printed in the log file
176:
177: Revision 1.123 2006/03/20 10:52:43 brouard
178: * imach.c (Module): <title> changed, corresponds to .htm file
179: name. <head> headers where missing.
180:
181: * imach.c (Module): Weights can have a decimal point as for
182: English (a comma might work with a correct LC_NUMERIC environment,
183: otherwise the weight is truncated).
184: Modification of warning when the covariates values are not 0 or
185: 1.
186: Version 0.98g
187:
188: Revision 1.122 2006/03/20 09:45:41 brouard
189: (Module): Weights can have a decimal point as for
190: English (a comma might work with a correct LC_NUMERIC environment,
191: otherwise the weight is truncated).
192: Modification of warning when the covariates values are not 0 or
193: 1.
194: Version 0.98g
195:
196: Revision 1.121 2006/03/16 17:45:01 lievre
197: * imach.c (Module): Comments concerning covariates added
198:
199: * imach.c (Module): refinements in the computation of lli if
200: status=-2 in order to have more reliable computation if stepm is
201: not 1 month. Version 0.98f
202:
203: Revision 1.120 2006/03/16 15:10:38 lievre
204: (Module): refinements in the computation of lli if
205: status=-2 in order to have more reliable computation if stepm is
206: not 1 month. Version 0.98f
207:
208: Revision 1.119 2006/03/15 17:42:26 brouard
209: (Module): Bug if status = -2, the loglikelihood was
210: computed as likelihood omitting the logarithm. Version O.98e
211:
212: Revision 1.118 2006/03/14 18:20:07 brouard
213: (Module): varevsij Comments added explaining the second
214: table of variances if popbased=1 .
215: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
216: (Module): Function pstamp added
217: (Module): Version 0.98d
218:
219: Revision 1.117 2006/03/14 17:16:22 brouard
220: (Module): varevsij Comments added explaining the second
221: table of variances if popbased=1 .
222: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
223: (Module): Function pstamp added
224: (Module): Version 0.98d
225:
226: Revision 1.116 2006/03/06 10:29:27 brouard
227: (Module): Variance-covariance wrong links and
228: varian-covariance of ej. is needed (Saito).
229:
230: Revision 1.115 2006/02/27 12:17:45 brouard
231: (Module): One freematrix added in mlikeli! 0.98c
232:
233: Revision 1.114 2006/02/26 12:57:58 brouard
234: (Module): Some improvements in processing parameter
235: filename with strsep.
236:
237: Revision 1.113 2006/02/24 14:20:24 brouard
238: (Module): Memory leaks checks with valgrind and:
239: datafile was not closed, some imatrix were not freed and on matrix
240: allocation too.
241:
242: Revision 1.112 2006/01/30 09:55:26 brouard
243: (Module): Back to gnuplot.exe instead of wgnuplot.exe
244:
245: Revision 1.111 2006/01/25 20:38:18 brouard
246: (Module): Lots of cleaning and bugs added (Gompertz)
247: (Module): Comments can be added in data file. Missing date values
248: can be a simple dot '.'.
249:
250: Revision 1.110 2006/01/25 00:51:50 brouard
251: (Module): Lots of cleaning and bugs added (Gompertz)
252:
253: Revision 1.109 2006/01/24 19:37:15 brouard
254: (Module): Comments (lines starting with a #) are allowed in data.
255:
256: Revision 1.108 2006/01/19 18:05:42 lievre
257: Gnuplot problem appeared...
258: To be fixed
259:
260: Revision 1.107 2006/01/19 16:20:37 brouard
261: Test existence of gnuplot in imach path
262:
263: Revision 1.106 2006/01/19 13:24:36 brouard
264: Some cleaning and links added in html output
265:
266: Revision 1.105 2006/01/05 20:23:19 lievre
267: *** empty log message ***
268:
269: Revision 1.104 2005/09/30 16:11:43 lievre
270: (Module): sump fixed, loop imx fixed, and simplifications.
271: (Module): If the status is missing at the last wave but we know
272: that the person is alive, then we can code his/her status as -2
273: (instead of missing=-1 in earlier versions) and his/her
274: contributions to the likelihood is 1 - Prob of dying from last
275: health status (= 1-p13= p11+p12 in the easiest case of somebody in
276: the healthy state at last known wave). Version is 0.98
277:
278: Revision 1.103 2005/09/30 15:54:49 lievre
279: (Module): sump fixed, loop imx fixed, and simplifications.
280:
281: Revision 1.102 2004/09/15 17:31:30 brouard
282: Add the possibility to read data file including tab characters.
283:
284: Revision 1.101 2004/09/15 10:38:38 brouard
285: Fix on curr_time
286:
287: Revision 1.100 2004/07/12 18:29:06 brouard
288: Add version for Mac OS X. Just define UNIX in Makefile
289:
290: Revision 1.99 2004/06/05 08:57:40 brouard
291: *** empty log message ***
292:
293: Revision 1.98 2004/05/16 15:05:56 brouard
294: New version 0.97 . First attempt to estimate force of mortality
295: directly from the data i.e. without the need of knowing the health
296: state at each age, but using a Gompertz model: log u =a + b*age .
297: This is the basic analysis of mortality and should be done before any
298: other analysis, in order to test if the mortality estimated from the
299: cross-longitudinal survey is different from the mortality estimated
300: from other sources like vital statistic data.
301:
302: The same imach parameter file can be used but the option for mle should be -3.
303:
304: Agnès, who wrote this part of the code, tried to keep most of the
305: former routines in order to include the new code within the former code.
306:
307: The output is very simple: only an estimate of the intercept and of
308: the slope with 95% confident intervals.
309:
310: Current limitations:
311: A) Even if you enter covariates, i.e. with the
312: model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
313: B) There is no computation of Life Expectancy nor Life Table.
314:
315: Revision 1.97 2004/02/20 13:25:42 lievre
316: Version 0.96d. Population forecasting command line is (temporarily)
317: suppressed.
318:
319: Revision 1.96 2003/07/15 15:38:55 brouard
320: * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
321: rewritten within the same printf. Workaround: many printfs.
322:
323: Revision 1.95 2003/07/08 07:54:34 brouard
324: * imach.c (Repository):
325: (Repository): Using imachwizard code to output a more meaningful covariance
326: matrix (cov(a12,c31) instead of numbers.
327:
328: Revision 1.94 2003/06/27 13:00:02 brouard
329: Just cleaning
330:
331: Revision 1.93 2003/06/25 16:33:55 brouard
332: (Module): On windows (cygwin) function asctime_r doesn't
333: exist so I changed back to asctime which exists.
334: (Module): Version 0.96b
335:
336: Revision 1.92 2003/06/25 16:30:45 brouard
337: (Module): On windows (cygwin) function asctime_r doesn't
338: exist so I changed back to asctime which exists.
339:
340: Revision 1.91 2003/06/25 15:30:29 brouard
341: * imach.c (Repository): Duplicated warning errors corrected.
342: (Repository): Elapsed time after each iteration is now output. It
343: helps to forecast when convergence will be reached. Elapsed time
344: is stamped in powell. We created a new html file for the graphs
345: concerning matrix of covariance. It has extension -cov.htm.
346:
347: Revision 1.90 2003/06/24 12:34:15 brouard
348: (Module): Some bugs corrected for windows. Also, when
349: mle=-1 a template is output in file "or"mypar.txt with the design
350: of the covariance matrix to be input.
351:
352: Revision 1.89 2003/06/24 12:30:52 brouard
353: (Module): Some bugs corrected for windows. Also, when
354: mle=-1 a template is output in file "or"mypar.txt with the design
355: of the covariance matrix to be input.
356:
357: Revision 1.88 2003/06/23 17:54:56 brouard
358: * 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.
359:
360: Revision 1.87 2003/06/18 12:26:01 brouard
361: Version 0.96
362:
363: Revision 1.86 2003/06/17 20:04:08 brouard
364: (Module): Change position of html and gnuplot routines and added
365: routine fileappend.
366:
367: Revision 1.85 2003/06/17 13:12:43 brouard
368: * imach.c (Repository): Check when date of death was earlier that
369: current date of interview. It may happen when the death was just
370: prior to the death. In this case, dh was negative and likelihood
371: was wrong (infinity). We still send an "Error" but patch by
372: assuming that the date of death was just one stepm after the
373: interview.
374: (Repository): Because some people have very long ID (first column)
375: we changed int to long in num[] and we added a new lvector for
376: memory allocation. But we also truncated to 8 characters (left
377: truncation)
378: (Repository): No more line truncation errors.
379:
380: Revision 1.84 2003/06/13 21:44:43 brouard
381: * imach.c (Repository): Replace "freqsummary" at a correct
382: place. It differs from routine "prevalence" which may be called
383: many times. Probs is memory consuming and must be used with
384: parcimony.
385: Version 0.95a3 (should output exactly the same maximization than 0.8a2)
386:
387: Revision 1.83 2003/06/10 13:39:11 lievre
388: *** empty log message ***
389:
390: Revision 1.82 2003/06/05 15:57:20 brouard
391: Add log in imach.c and fullversion number is now printed.
392:
393: */
394: /*
395: Interpolated Markov Chain
396:
397: Short summary of the programme:
398:
399: This program computes Healthy Life Expectancies from
400: cross-longitudinal data. Cross-longitudinal data consist in: -1- a
401: first survey ("cross") where individuals from different ages are
402: interviewed on their health status or degree of disability (in the
403: case of a health survey which is our main interest) -2- at least a
404: second wave of interviews ("longitudinal") which measure each change
405: (if any) in individual health status. Health expectancies are
406: computed from the time spent in each health state according to a
407: model. More health states you consider, more time is necessary to reach the
408: Maximum Likelihood of the parameters involved in the model. The
409: simplest model is the multinomial logistic model where pij is the
410: probability to be observed in state j at the second wave
411: conditional to be observed in state i at the first wave. Therefore
412: the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
413: 'age' is age and 'sex' is a covariate. If you want to have a more
414: complex model than "constant and age", you should modify the program
415: where the markup *Covariates have to be included here again* invites
416: you to do it. More covariates you add, slower the
417: convergence.
418:
419: The advantage of this computer programme, compared to a simple
420: multinomial logistic model, is clear when the delay between waves is not
421: identical for each individual. Also, if a individual missed an
422: intermediate interview, the information is lost, but taken into
423: account using an interpolation or extrapolation.
424:
425: hPijx is the probability to be observed in state i at age x+h
426: conditional to the observed state i at age x. The delay 'h' can be
427: split into an exact number (nh*stepm) of unobserved intermediate
428: states. This elementary transition (by month, quarter,
429: semester or year) is modelled as a multinomial logistic. The hPx
430: matrix is simply the matrix product of nh*stepm elementary matrices
431: and the contribution of each individual to the likelihood is simply
432: hPijx.
433:
434: Also this programme outputs the covariance matrix of the parameters but also
435: of the life expectancies. It also computes the period (stable) prevalence.
436:
437: Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
438: Institut national d'études démographiques, Paris.
439: This software have been partly granted by Euro-REVES, a concerted action
440: from the European Union.
441: It is copyrighted identically to a GNU software product, ie programme and
442: software can be distributed freely for non commercial use. Latest version
443: can be accessed at http://euroreves.ined.fr/imach .
444:
445: Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
446: or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
447:
448: **********************************************************************/
449: /*
450: main
451: read parameterfile
452: read datafile
453: concatwav
454: freqsummary
455: if (mle >= 1)
456: mlikeli
457: print results files
458: if mle==1
459: computes hessian
460: read end of parameter file: agemin, agemax, bage, fage, estepm
461: begin-prev-date,...
462: open gnuplot file
463: open html file
464: period (stable) prevalence | pl_nom 1-1 2-2 etc by covariate
465: for age prevalim() | #****** V1=0 V2=1 V3=1 V4=0 ******
466: | 65 1 0 2 1 3 1 4 0 0.96326 0.03674
467: freexexit2 possible for memory heap.
468:
469: h Pij x | pij_nom ficrestpij
470: # Cov Agex agex+h hpijx with i,j= 1-1 1-2 1-3 2-1 2-2 2-3
471: 1 85 85 1.00000 0.00000 0.00000 0.00000 1.00000 0.00000
472: 1 85 86 0.68299 0.22291 0.09410 0.71093 0.00000 0.28907
473:
474: 1 65 99 0.00364 0.00322 0.99314 0.00350 0.00310 0.99340
475: 1 65 100 0.00214 0.00204 0.99581 0.00206 0.00196 0.99597
476: variance of p one-step probabilities varprob | prob_nom ficresprob #One-step probabilities and stand. devi in ()
477: Standard deviation of one-step probabilities | probcor_nom ficresprobcor #One-step probabilities and correlation matrix
478: Matrix of variance covariance of one-step probabilities | probcov_nom ficresprobcov #One-step probabilities and covariance matrix
479:
480: forecasting if prevfcast==1 prevforecast call prevalence()
481: health expectancies
482: Variance-covariance of DFLE
483: prevalence()
484: movingaverage()
485: varevsij()
486: if popbased==1 varevsij(,popbased)
487: total life expectancies
488: Variance of period (stable) prevalence
489: end
490: */
491:
492:
493:
494:
495: #include <math.h>
496: #include <stdio.h>
497: #include <stdlib.h>
498: #include <string.h>
499:
500: #ifdef _WIN32
501: #include <io.h>
502: #else
503: #include <unistd.h>
504: #endif
505:
506: #include <limits.h>
507: #include <sys/types.h>
508: #include <sys/stat.h>
509: #include <errno.h>
510: /* extern int errno; */
511:
512: /* #ifdef LINUX */
513: /* #include <time.h> */
514: /* #include "timeval.h" */
515: /* #else */
516: /* #include <sys/time.h> */
517: /* #endif */
518:
519: #include <time.h>
520:
521: #ifdef GSL
522: #include <gsl/gsl_errno.h>
523: #include <gsl/gsl_multimin.h>
524: #endif
525:
526: #ifdef NLOPT
527: #include <nlopt.h>
528: typedef struct {
529: double (* function)(double [] );
530: } myfunc_data ;
531: #endif
532:
533: /* #include <libintl.h> */
534: /* #define _(String) gettext (String) */
535:
536: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
537:
538: #define GNUPLOTPROGRAM "gnuplot"
539: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
540: #define FILENAMELENGTH 132
541:
542: #define GLOCK_ERROR_NOPATH -1 /* empty path */
543: #define GLOCK_ERROR_GETCWD -2 /* cannot get cwd */
544:
545: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
546: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
547:
548: #define NINTERVMAX 8
549: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
550: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
551: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
552: #define codtabm(h,k) 1 & (h-1) >> (k-1) ;
553: #define MAXN 20000
554: #define YEARM 12. /**< Number of months per year */
555: #define AGESUP 130
556: #define AGEBASE 40
557: #define AGEGOMP 10. /**< Minimal age for Gompertz adjustment */
558: #ifdef _WIN32
559: #define DIRSEPARATOR '\\'
560: #define CHARSEPARATOR "\\"
561: #define ODIRSEPARATOR '/'
562: #else
563: #define DIRSEPARATOR '/'
564: #define CHARSEPARATOR "/"
565: #define ODIRSEPARATOR '\\'
566: #endif
567:
568: /* $Id: imach.c,v 1.162 2014/09/25 11:43:39 brouard Exp $ */
569: /* $State: Exp $ */
570:
571: char version[]="Imach version 0.99, September 2014,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121)";
572: char fullversion[]="$Revision: 1.162 $ $Date: 2014/09/25 11:43:39 $";
573: char strstart[80];
574: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
575: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings */
576: int nvar=0, nforce=0; /* Number of variables, number of forces */
577: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
578: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
579: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
580: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
581: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
582: int cptcovprodnoage=0; /**< Number of covariate products without age */
583: int cptcoveff=0; /* Total number of covariates to vary for printing results */
584: int cptcov=0; /* Working variable */
585: int npar=NPARMAX;
586: int nlstate=2; /* Number of live states */
587: int ndeath=1; /* Number of dead states */
588: int ncovmodel=0, ncovcol=0; /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
589: int popbased=0;
590:
591: int *wav; /* Number of waves for this individuual 0 is possible */
592: int maxwav=0; /* Maxim number of waves */
593: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
594: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */
595: int gipmx=0, gsw=0; /* Global variables on the number of contributions
596: to the likelihood and the sum of weights (done by funcone)*/
597: int mle=1, weightopt=0;
598: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
599: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
600: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
601: * wave mi and wave mi+1 is not an exact multiple of stepm. */
602: int countcallfunc=0; /* Count the number of calls to func */
603: double jmean=1; /* Mean space between 2 waves */
604: double **matprod2(); /* test */
605: double **oldm, **newm, **savm; /* Working pointers to matrices */
606: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
607: /*FILE *fic ; */ /* Used in readdata only */
608: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
609: FILE *ficlog, *ficrespow;
610: int globpr=0; /* Global variable for printing or not */
611: double fretone; /* Only one call to likelihood */
612: long ipmx=0; /* Number of contributions */
613: double sw; /* Sum of weights */
614: char filerespow[FILENAMELENGTH];
615: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
616: FILE *ficresilk;
617: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
618: FILE *ficresprobmorprev;
619: FILE *fichtm, *fichtmcov; /* Html File */
620: FILE *ficreseij;
621: char filerese[FILENAMELENGTH];
622: FILE *ficresstdeij;
623: char fileresstde[FILENAMELENGTH];
624: FILE *ficrescveij;
625: char filerescve[FILENAMELENGTH];
626: FILE *ficresvij;
627: char fileresv[FILENAMELENGTH];
628: FILE *ficresvpl;
629: char fileresvpl[FILENAMELENGTH];
630: char title[MAXLINE];
631: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH], filerespl[FILENAMELENGTH];
632: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
633: char tmpout[FILENAMELENGTH], tmpout2[FILENAMELENGTH];
634: char command[FILENAMELENGTH];
635: int outcmd=0;
636:
637: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
638:
639: char filelog[FILENAMELENGTH]; /* Log file */
640: char filerest[FILENAMELENGTH];
641: char fileregp[FILENAMELENGTH];
642: char popfile[FILENAMELENGTH];
643:
644: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
645:
646: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
647: /* struct timezone tzp; */
648: /* extern int gettimeofday(); */
649: struct tm tml, *gmtime(), *localtime();
650:
651: extern time_t time();
652:
653: struct tm start_time, end_time, curr_time, last_time, forecast_time;
654: time_t rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
655: struct tm tm;
656:
657: char strcurr[80], strfor[80];
658:
659: char *endptr;
660: long lval;
661: double dval;
662:
663: #define NR_END 1
664: #define FREE_ARG char*
665: #define FTOL 1.0e-10
666:
667: #define NRANSI
668: #define ITMAX 200
669:
670: #define TOL 2.0e-4
671:
672: #define CGOLD 0.3819660
673: #define ZEPS 1.0e-10
674: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
675:
676: #define GOLD 1.618034
677: #define GLIMIT 100.0
678: #define TINY 1.0e-20
679:
680: static double maxarg1,maxarg2;
681: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
682: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
683:
684: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
685: #define rint(a) floor(a+0.5)
686:
687: static double sqrarg;
688: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
689: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
690: int agegomp= AGEGOMP;
691:
692: int imx;
693: int stepm=1;
694: /* Stepm, step in month: minimum step interpolation*/
695:
696: int estepm;
697: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
698:
699: int m,nb;
700: long *num;
701: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
702: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
703: double **pmmij, ***probs;
704: double *ageexmed,*agecens;
705: double dateintmean=0;
706:
707: double *weight;
708: int **s; /* Status */
709: double *agedc;
710: double **covar; /**< covar[j,i], value of jth covariate for individual i,
711: * covar=matrix(0,NCOVMAX,1,n);
712: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; */
713: double idx;
714: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
715: int *Ndum; /** Freq of modality (tricode */
716: int **codtab; /**< codtab=imatrix(1,100,1,10); */
717: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
718: double *lsurv, *lpop, *tpop;
719:
720: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
721: double ftolhess; /**< Tolerance for computing hessian */
722:
723: /**************** split *************************/
724: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
725: {
726: /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
727: the name of the file (name), its extension only (ext) and its first part of the name (finame)
728: */
729: char *ss; /* pointer */
730: int l1, l2; /* length counters */
731:
732: l1 = strlen(path ); /* length of path */
733: if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
734: ss= strrchr( path, DIRSEPARATOR ); /* find last / */
735: if ( ss == NULL ) { /* no directory, so determine current directory */
736: strcpy( name, path ); /* we got the fullname name because no directory */
737: /*if(strrchr(path, ODIRSEPARATOR )==NULL)
738: printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
739: /* get current working directory */
740: /* extern char* getcwd ( char *buf , int len);*/
741: if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
742: return( GLOCK_ERROR_GETCWD );
743: }
744: /* got dirc from getcwd*/
745: printf(" DIRC = %s \n",dirc);
746: } else { /* strip direcotry from path */
747: ss++; /* after this, the filename */
748: l2 = strlen( ss ); /* length of filename */
749: if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
750: strcpy( name, ss ); /* save file name */
751: strncpy( dirc, path, l1 - l2 ); /* now the directory */
752: dirc[l1-l2] = 0; /* add zero */
753: printf(" DIRC2 = %s \n",dirc);
754: }
755: /* We add a separator at the end of dirc if not exists */
756: l1 = strlen( dirc ); /* length of directory */
757: if( dirc[l1-1] != DIRSEPARATOR ){
758: dirc[l1] = DIRSEPARATOR;
759: dirc[l1+1] = 0;
760: printf(" DIRC3 = %s \n",dirc);
761: }
762: ss = strrchr( name, '.' ); /* find last / */
763: if (ss >0){
764: ss++;
765: strcpy(ext,ss); /* save extension */
766: l1= strlen( name);
767: l2= strlen(ss)+1;
768: strncpy( finame, name, l1-l2);
769: finame[l1-l2]= 0;
770: }
771:
772: return( 0 ); /* we're done */
773: }
774:
775:
776: /******************************************/
777:
778: void replace_back_to_slash(char *s, char*t)
779: {
780: int i;
781: int lg=0;
782: i=0;
783: lg=strlen(t);
784: for(i=0; i<= lg; i++) {
785: (s[i] = t[i]);
786: if (t[i]== '\\') s[i]='/';
787: }
788: }
789:
790: char *trimbb(char *out, char *in)
791: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
792: char *s;
793: s=out;
794: while (*in != '\0'){
795: while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
796: in++;
797: }
798: *out++ = *in++;
799: }
800: *out='\0';
801: return s;
802: }
803:
804: char *cutl(char *blocc, char *alocc, char *in, char occ)
805: {
806: /* cuts string in into blocc and alocc where blocc ends before first occurence of char 'occ'
807: and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
808: gives blocc="abcdef2ghi" and alocc="j".
809: If occ is not found blocc is null and alocc is equal to in. Returns blocc
810: */
811: char *s, *t;
812: t=in;s=in;
813: while ((*in != occ) && (*in != '\0')){
814: *alocc++ = *in++;
815: }
816: if( *in == occ){
817: *(alocc)='\0';
818: s=++in;
819: }
820:
821: if (s == t) {/* occ not found */
822: *(alocc-(in-s))='\0';
823: in=s;
824: }
825: while ( *in != '\0'){
826: *blocc++ = *in++;
827: }
828:
829: *blocc='\0';
830: return t;
831: }
832: char *cutv(char *blocc, char *alocc, char *in, char occ)
833: {
834: /* cuts string in into blocc and alocc where blocc ends before last occurence of char 'occ'
835: and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
836: gives blocc="abcdef2ghi" and alocc="j".
837: If occ is not found blocc is null and alocc is equal to in. Returns alocc
838: */
839: char *s, *t;
840: t=in;s=in;
841: while (*in != '\0'){
842: while( *in == occ){
843: *blocc++ = *in++;
844: s=in;
845: }
846: *blocc++ = *in++;
847: }
848: if (s == t) /* occ not found */
849: *(blocc-(in-s))='\0';
850: else
851: *(blocc-(in-s)-1)='\0';
852: in=s;
853: while ( *in != '\0'){
854: *alocc++ = *in++;
855: }
856:
857: *alocc='\0';
858: return s;
859: }
860:
861: int nbocc(char *s, char occ)
862: {
863: int i,j=0;
864: int lg=20;
865: i=0;
866: lg=strlen(s);
867: for(i=0; i<= lg; i++) {
868: if (s[i] == occ ) j++;
869: }
870: return j;
871: }
872:
873: /* void cutv(char *u,char *v, char*t, char occ) */
874: /* { */
875: /* /\* cuts string t into u and v where u ends before last occurence of char 'occ' */
876: /* and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
877: /* gives u="abcdef2ghi" and v="j" *\/ */
878: /* int i,lg,j,p=0; */
879: /* i=0; */
880: /* lg=strlen(t); */
881: /* for(j=0; j<=lg-1; j++) { */
882: /* if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
883: /* } */
884:
885: /* for(j=0; j<p; j++) { */
886: /* (u[j] = t[j]); */
887: /* } */
888: /* u[p]='\0'; */
889:
890: /* for(j=0; j<= lg; j++) { */
891: /* if (j>=(p+1))(v[j-p-1] = t[j]); */
892: /* } */
893: /* } */
894:
895: #ifdef _WIN32
896: char * strsep(char **pp, const char *delim)
897: {
898: char *p, *q;
899:
900: if ((p = *pp) == NULL)
901: return 0;
902: if ((q = strpbrk (p, delim)) != NULL)
903: {
904: *pp = q + 1;
905: *q = '\0';
906: }
907: else
908: *pp = 0;
909: return p;
910: }
911: #endif
912:
913: /********************** nrerror ********************/
914:
915: void nrerror(char error_text[])
916: {
917: fprintf(stderr,"ERREUR ...\n");
918: fprintf(stderr,"%s\n",error_text);
919: exit(EXIT_FAILURE);
920: }
921: /*********************** vector *******************/
922: double *vector(int nl, int nh)
923: {
924: double *v;
925: v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
926: if (!v) nrerror("allocation failure in vector");
927: return v-nl+NR_END;
928: }
929:
930: /************************ free vector ******************/
931: void free_vector(double*v, int nl, int nh)
932: {
933: free((FREE_ARG)(v+nl-NR_END));
934: }
935:
936: /************************ivector *******************************/
937: int *ivector(long nl,long nh)
938: {
939: int *v;
940: v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
941: if (!v) nrerror("allocation failure in ivector");
942: return v-nl+NR_END;
943: }
944:
945: /******************free ivector **************************/
946: void free_ivector(int *v, long nl, long nh)
947: {
948: free((FREE_ARG)(v+nl-NR_END));
949: }
950:
951: /************************lvector *******************************/
952: long *lvector(long nl,long nh)
953: {
954: long *v;
955: v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
956: if (!v) nrerror("allocation failure in ivector");
957: return v-nl+NR_END;
958: }
959:
960: /******************free lvector **************************/
961: void free_lvector(long *v, long nl, long nh)
962: {
963: free((FREE_ARG)(v+nl-NR_END));
964: }
965:
966: /******************* imatrix *******************************/
967: int **imatrix(long nrl, long nrh, long ncl, long nch)
968: /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
969: {
970: long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
971: int **m;
972:
973: /* allocate pointers to rows */
974: m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
975: if (!m) nrerror("allocation failure 1 in matrix()");
976: m += NR_END;
977: m -= nrl;
978:
979:
980: /* allocate rows and set pointers to them */
981: m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
982: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
983: m[nrl] += NR_END;
984: m[nrl] -= ncl;
985:
986: for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
987:
988: /* return pointer to array of pointers to rows */
989: return m;
990: }
991:
992: /****************** free_imatrix *************************/
993: void free_imatrix(m,nrl,nrh,ncl,nch)
994: int **m;
995: long nch,ncl,nrh,nrl;
996: /* free an int matrix allocated by imatrix() */
997: {
998: free((FREE_ARG) (m[nrl]+ncl-NR_END));
999: free((FREE_ARG) (m+nrl-NR_END));
1000: }
1001:
1002: /******************* matrix *******************************/
1003: double **matrix(long nrl, long nrh, long ncl, long nch)
1004: {
1005: long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
1006: double **m;
1007:
1008: m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1009: if (!m) nrerror("allocation failure 1 in matrix()");
1010: m += NR_END;
1011: m -= nrl;
1012:
1013: m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1014: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1015: m[nrl] += NR_END;
1016: m[nrl] -= ncl;
1017:
1018: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1019: return m;
1020: /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
1021: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
1022: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1023: */
1024: }
1025:
1026: /*************************free matrix ************************/
1027: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
1028: {
1029: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1030: free((FREE_ARG)(m+nrl-NR_END));
1031: }
1032:
1033: /******************* ma3x *******************************/
1034: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
1035: {
1036: long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
1037: double ***m;
1038:
1039: m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1040: if (!m) nrerror("allocation failure 1 in matrix()");
1041: m += NR_END;
1042: m -= nrl;
1043:
1044: m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1045: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1046: m[nrl] += NR_END;
1047: m[nrl] -= ncl;
1048:
1049: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1050:
1051: m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
1052: if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
1053: m[nrl][ncl] += NR_END;
1054: m[nrl][ncl] -= nll;
1055: for (j=ncl+1; j<=nch; j++)
1056: m[nrl][j]=m[nrl][j-1]+nlay;
1057:
1058: for (i=nrl+1; i<=nrh; i++) {
1059: m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
1060: for (j=ncl+1; j<=nch; j++)
1061: m[i][j]=m[i][j-1]+nlay;
1062: }
1063: return m;
1064: /* gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
1065: &(m[i][j][k]) <=> *((*(m+i) + j)+k)
1066: */
1067: }
1068:
1069: /*************************free ma3x ************************/
1070: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
1071: {
1072: free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
1073: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1074: free((FREE_ARG)(m+nrl-NR_END));
1075: }
1076:
1077: /*************** function subdirf ***********/
1078: char *subdirf(char fileres[])
1079: {
1080: /* Caution optionfilefiname is hidden */
1081: strcpy(tmpout,optionfilefiname);
1082: strcat(tmpout,"/"); /* Add to the right */
1083: strcat(tmpout,fileres);
1084: return tmpout;
1085: }
1086:
1087: /*************** function subdirf2 ***********/
1088: char *subdirf2(char fileres[], char *preop)
1089: {
1090:
1091: /* Caution optionfilefiname is hidden */
1092: strcpy(tmpout,optionfilefiname);
1093: strcat(tmpout,"/");
1094: strcat(tmpout,preop);
1095: strcat(tmpout,fileres);
1096: return tmpout;
1097: }
1098:
1099: /*************** function subdirf3 ***********/
1100: char *subdirf3(char fileres[], char *preop, char *preop2)
1101: {
1102:
1103: /* Caution optionfilefiname is hidden */
1104: strcpy(tmpout,optionfilefiname);
1105: strcat(tmpout,"/");
1106: strcat(tmpout,preop);
1107: strcat(tmpout,preop2);
1108: strcat(tmpout,fileres);
1109: return tmpout;
1110: }
1111:
1112: char *asc_diff_time(long time_sec, char ascdiff[])
1113: {
1114: long sec_left, days, hours, minutes;
1115: days = (time_sec) / (60*60*24);
1116: sec_left = (time_sec) % (60*60*24);
1117: hours = (sec_left) / (60*60) ;
1118: sec_left = (sec_left) %(60*60);
1119: minutes = (sec_left) /60;
1120: sec_left = (sec_left) % (60);
1121: sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);
1122: return ascdiff;
1123: }
1124:
1125: /***************** f1dim *************************/
1126: extern int ncom;
1127: extern double *pcom,*xicom;
1128: extern double (*nrfunc)(double []);
1129:
1130: double f1dim(double x)
1131: {
1132: int j;
1133: double f;
1134: double *xt;
1135:
1136: xt=vector(1,ncom);
1137: for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
1138: f=(*nrfunc)(xt);
1139: free_vector(xt,1,ncom);
1140: return f;
1141: }
1142:
1143: /*****************brent *************************/
1144: double brent(double ax, double bx, double cx, double (*f)(double), double tol, double *xmin)
1145: {
1146: int iter;
1147: double a,b,d,etemp;
1148: double fu=0,fv,fw,fx;
1149: double ftemp;
1150: double p,q,r,tol1,tol2,u,v,w,x,xm;
1151: double e=0.0;
1152:
1153: a=(ax < cx ? ax : cx);
1154: b=(ax > cx ? ax : cx);
1155: x=w=v=bx;
1156: fw=fv=fx=(*f)(x);
1157: for (iter=1;iter<=ITMAX;iter++) {
1158: xm=0.5*(a+b);
1159: tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
1160: /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
1161: printf(".");fflush(stdout);
1162: fprintf(ficlog,".");fflush(ficlog);
1163: #ifdef DEBUGBRENT
1164: 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);
1165: 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);
1166: /* if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
1167: #endif
1168: if (fabs(x-xm) <= (tol2-0.5*(b-a))){
1169: *xmin=x;
1170: return fx;
1171: }
1172: ftemp=fu;
1173: if (fabs(e) > tol1) {
1174: r=(x-w)*(fx-fv);
1175: q=(x-v)*(fx-fw);
1176: p=(x-v)*q-(x-w)*r;
1177: q=2.0*(q-r);
1178: if (q > 0.0) p = -p;
1179: q=fabs(q);
1180: etemp=e;
1181: e=d;
1182: if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
1183: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1184: else {
1185: d=p/q;
1186: u=x+d;
1187: if (u-a < tol2 || b-u < tol2)
1188: d=SIGN(tol1,xm-x);
1189: }
1190: } else {
1191: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1192: }
1193: u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
1194: fu=(*f)(u);
1195: if (fu <= fx) {
1196: if (u >= x) a=x; else b=x;
1197: SHFT(v,w,x,u)
1198: SHFT(fv,fw,fx,fu)
1199: } else {
1200: if (u < x) a=u; else b=u;
1201: if (fu <= fw || w == x) {
1202: v=w;
1203: w=u;
1204: fv=fw;
1205: fw=fu;
1206: } else if (fu <= fv || v == x || v == w) {
1207: v=u;
1208: fv=fu;
1209: }
1210: }
1211: }
1212: nrerror("Too many iterations in brent");
1213: *xmin=x;
1214: return fx;
1215: }
1216:
1217: /****************** mnbrak ***********************/
1218:
1219: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
1220: double (*func)(double))
1221: {
1222: double ulim,u,r,q, dum;
1223: double fu;
1224:
1225: *fa=(*func)(*ax);
1226: *fb=(*func)(*bx);
1227: if (*fb > *fa) {
1228: SHFT(dum,*ax,*bx,dum)
1229: SHFT(dum,*fb,*fa,dum)
1230: }
1231: *cx=(*bx)+GOLD*(*bx-*ax);
1232: *fc=(*func)(*cx);
1233: while (*fb > *fc) { /* Declining fa, fb, fc */
1234: r=(*bx-*ax)*(*fb-*fc);
1235: q=(*bx-*cx)*(*fb-*fa);
1236: u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
1237: (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscisse of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
1238: ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscisse where function can be evaluated */
1239: if ((*bx-u)*(u-*cx) > 0.0) { /* if u between b and c */
1240: fu=(*func)(u);
1241: } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1242: fu=(*func)(u);
1243: if (fu < *fc) {
1244: SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
1245: SHFT(*fb,*fc,fu,(*func)(u))
1246: }
1247: } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1248: u=ulim;
1249: fu=(*func)(u);
1250: } else {
1251: u=(*cx)+GOLD*(*cx-*bx);
1252: fu=(*func)(u);
1253: }
1254: SHFT(*ax,*bx,*cx,u)
1255: SHFT(*fa,*fb,*fc,fu)
1256: }
1257: }
1258:
1259: /*************** linmin ************************/
1260: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
1261: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
1262: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
1263: the value of func at the returned location p . This is actually all accomplished by calling the
1264: routines mnbrak and brent .*/
1265: int ncom;
1266: double *pcom,*xicom;
1267: double (*nrfunc)(double []);
1268:
1269: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
1270: {
1271: double brent(double ax, double bx, double cx,
1272: double (*f)(double), double tol, double *xmin);
1273: double f1dim(double x);
1274: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
1275: double *fc, double (*func)(double));
1276: int j;
1277: double xx,xmin,bx,ax;
1278: double fx,fb,fa;
1279:
1280: ncom=n;
1281: pcom=vector(1,n);
1282: xicom=vector(1,n);
1283: nrfunc=func;
1284: for (j=1;j<=n;j++) {
1285: pcom[j]=p[j];
1286: xicom[j]=xi[j];
1287: }
1288: ax=0.0;
1289: xx=1.0;
1290: mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Find a bracket a,x,b in direction n=xi ie xicom */
1291: *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Find a minimum P+lambda n in that direction (lambdamin), with TOL between abscisses */
1292: #ifdef DEBUG
1293: printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1294: fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1295: #endif
1296: for (j=1;j<=n;j++) {
1297: xi[j] *= xmin;
1298: p[j] += xi[j];
1299: }
1300: free_vector(xicom,1,n);
1301: free_vector(pcom,1,n);
1302: }
1303:
1304:
1305: /*************** powell ************************/
1306: /*
1307: Minimization of a function func of n variables. Input consists of an initial starting point
1308: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
1309: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
1310: such that failure to decrease by more than this amount on one iteration signals doneness. On
1311: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
1312: function value at p , and iter is the number of iterations taken. The routine linmin is used.
1313: */
1314: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
1315: double (*func)(double []))
1316: {
1317: void linmin(double p[], double xi[], int n, double *fret,
1318: double (*func)(double []));
1319: int i,ibig,j;
1320: double del,t,*pt,*ptt,*xit;
1321: double fp,fptt;
1322: double *xits;
1323: int niterf, itmp;
1324:
1325: pt=vector(1,n);
1326: ptt=vector(1,n);
1327: xit=vector(1,n);
1328: xits=vector(1,n);
1329: *fret=(*func)(p);
1330: for (j=1;j<=n;j++) pt[j]=p[j];
1331: rcurr_time = time(NULL);
1332: for (*iter=1;;++(*iter)) {
1333: fp=(*fret);
1334: ibig=0;
1335: del=0.0;
1336: rlast_time=rcurr_time;
1337: /* (void) gettimeofday(&curr_time,&tzp); */
1338: rcurr_time = time(NULL);
1339: curr_time = *localtime(&rcurr_time);
1340: printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
1341: fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1342: /* fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1343: for (i=1;i<=n;i++) {
1344: printf(" %d %.12f",i, p[i]);
1345: fprintf(ficlog," %d %.12lf",i, p[i]);
1346: fprintf(ficrespow," %.12lf", p[i]);
1347: }
1348: printf("\n");
1349: fprintf(ficlog,"\n");
1350: fprintf(ficrespow,"\n");fflush(ficrespow);
1351: if(*iter <=3){
1352: tml = *localtime(&rcurr_time);
1353: strcpy(strcurr,asctime(&tml));
1354: rforecast_time=rcurr_time;
1355: itmp = strlen(strcurr);
1356: if(strcurr[itmp-1]=='\n') /* Windows outputs with a new line */
1357: strcurr[itmp-1]='\0';
1358: printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1359: fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1360: for(niterf=10;niterf<=30;niterf+=10){
1361: rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
1362: forecast_time = *localtime(&rforecast_time);
1363: strcpy(strfor,asctime(&forecast_time));
1364: itmp = strlen(strfor);
1365: if(strfor[itmp-1]=='\n')
1366: strfor[itmp-1]='\0';
1367: 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);
1368: 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);
1369: }
1370: }
1371: for (i=1;i<=n;i++) {
1372: for (j=1;j<=n;j++) xit[j]=xi[j][i];
1373: fptt=(*fret);
1374: #ifdef DEBUG
1375: printf("fret=%lf \n",*fret);
1376: fprintf(ficlog,"fret=%lf \n",*fret);
1377: #endif
1378: printf("%d",i);fflush(stdout);
1379: fprintf(ficlog,"%d",i);fflush(ficlog);
1380: linmin(p,xit,n,fret,func);
1381: if (fabs(fptt-(*fret)) > del) {
1382: del=fabs(fptt-(*fret));
1383: ibig=i;
1384: }
1385: #ifdef DEBUG
1386: printf("%d %.12e",i,(*fret));
1387: fprintf(ficlog,"%d %.12e",i,(*fret));
1388: for (j=1;j<=n;j++) {
1389: xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
1390: printf(" x(%d)=%.12e",j,xit[j]);
1391: fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1392: }
1393: for(j=1;j<=n;j++) {
1394: printf(" p(%d)=%.12e",j,p[j]);
1395: fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1396: }
1397: printf("\n");
1398: fprintf(ficlog,"\n");
1399: #endif
1400: } /* end i */
1401: if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
1402: #ifdef DEBUG
1403: int k[2],l;
1404: k[0]=1;
1405: k[1]=-1;
1406: printf("Max: %.12e",(*func)(p));
1407: fprintf(ficlog,"Max: %.12e",(*func)(p));
1408: for (j=1;j<=n;j++) {
1409: printf(" %.12e",p[j]);
1410: fprintf(ficlog," %.12e",p[j]);
1411: }
1412: printf("\n");
1413: fprintf(ficlog,"\n");
1414: for(l=0;l<=1;l++) {
1415: for (j=1;j<=n;j++) {
1416: ptt[j]=p[j]+(p[j]-pt[j])*k[l];
1417: printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1418: fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1419: }
1420: printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1421: fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1422: }
1423: #endif
1424:
1425:
1426: free_vector(xit,1,n);
1427: free_vector(xits,1,n);
1428: free_vector(ptt,1,n);
1429: free_vector(pt,1,n);
1430: return;
1431: }
1432: if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
1433: for (j=1;j<=n;j++) { /* Computes an extrapolated point */
1434: ptt[j]=2.0*p[j]-pt[j];
1435: xit[j]=p[j]-pt[j];
1436: pt[j]=p[j];
1437: }
1438: fptt=(*func)(ptt);
1439: if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1440: /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1441: /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1442: /* Let f"(x2) be the 2nd derivative equal everywhere. */
1443: /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
1444: /* will reach at f3 = fm + h^2/2 f"m ; f" = (f1 -2f2 +f3 ) / h**2 */
1445: /* f1-f3 = delta(2h) = 2 h**2 f'' = 2(f1- 2f2 +f3) */
1446: /* Thus we compare delta(2h) with observed f1-f3 */
1447: /* or best gain on one ancient line 'del' with total */
1448: /* gain f1-f2 = f1 - f2 - 'del' with del */
1449: /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1450:
1451: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del);
1452: t= t- del*SQR(fp-fptt);
1453: printf("t1= %.12lf, t2= %.12lf, t=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t);
1454: fprintf(ficlog,"t1= %.12lf, t2= %.12lf, t=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t);
1455: #ifdef DEBUG
1456: printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1457: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1458: fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1459: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1460: printf("tt= %.12lf, t=%.12lf\n",2.0*(fp-2.0*(*fret)+fptt)*(fp-(*fret)-del)*(fp-(*fret)-del)-del*(fp-fptt)*(fp-fptt),t);
1461: fprintf(ficlog, "tt= %.12lf, t=%.12lf\n",2.0*(fp-2.0*(*fret)+fptt)*(fp-(*fret)-del)*(fp-(*fret)-del)-del*(fp-fptt)*(fp-fptt),t);
1462: #endif
1463: if (t < 0.0) { /* Then we use it for last direction */
1464: linmin(p,xit,n,fret,func); /* computes mean on the extrapolated direction.*/
1465: for (j=1;j<=n;j++) {
1466: xi[j][ibig]=xi[j][n]; /* Replace the direction with biggest decrease by n */
1467: xi[j][n]=xit[j]; /* and nth direction by the extrapolated */
1468: }
1469: printf("Gaining to use average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1470: fprintf(ficlog,"Gaining to use average direction of P0 P%d instead of biggest increase direction :\n",n,ibig);
1471:
1472: #ifdef DEBUG
1473: for(j=1;j<=n;j++){
1474: printf(" %.12e",xit[j]);
1475: fprintf(ficlog," %.12e",xit[j]);
1476: }
1477: printf("\n");
1478: fprintf(ficlog,"\n");
1479: #endif
1480: } /* end of t negative */
1481: } /* end if (fptt < fp) */
1482: }
1483: }
1484:
1485: /**** Prevalence limit (stable or period prevalence) ****************/
1486:
1487: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
1488: {
1489: /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1490: matrix by transitions matrix until convergence is reached */
1491:
1492: int i, ii,j,k;
1493: double min, max, maxmin, maxmax,sumnew=0.;
1494: /* double **matprod2(); */ /* test */
1495: double **out, cov[NCOVMAX+1], **pmij();
1496: double **newm;
1497: double agefin, delaymax=50 ; /* Max number of years to converge */
1498:
1499: for (ii=1;ii<=nlstate+ndeath;ii++)
1500: for (j=1;j<=nlstate+ndeath;j++){
1501: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1502: }
1503:
1504: cov[1]=1.;
1505:
1506: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1507: for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1508: newm=savm;
1509: /* Covariates have to be included here again */
1510: cov[2]=agefin;
1511:
1512: for (k=1; k<=cptcovn;k++) {
1513: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1514: /*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]]);*/
1515: }
1516: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1517: /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
1518: /* cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]] * nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]]; */
1519:
1520: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
1521: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
1522: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1523: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1524: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1525: out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1526:
1527: savm=oldm;
1528: oldm=newm;
1529: maxmax=0.;
1530: for(j=1;j<=nlstate;j++){
1531: min=1.;
1532: max=0.;
1533: for(i=1; i<=nlstate; i++) {
1534: sumnew=0;
1535: for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
1536: prlim[i][j]= newm[i][j]/(1-sumnew);
1537: /*printf(" prevalim i=%d, j=%d, prmlim[%d][%d]=%f, agefin=%d \n", i, j, i, j, prlim[i][j],(int)agefin);*/
1538: max=FMAX(max,prlim[i][j]);
1539: min=FMIN(min,prlim[i][j]);
1540: }
1541: maxmin=max-min;
1542: maxmax=FMAX(maxmax,maxmin);
1543: }
1544: if(maxmax < ftolpl){
1545: return prlim;
1546: }
1547: }
1548: }
1549:
1550: /*************** transition probabilities ***************/
1551:
1552: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1553: {
1554: /* According to parameters values stored in x and the covariate's values stored in cov,
1555: computes the probability to be observed in state j being in state i by appying the
1556: model to the ncovmodel covariates (including constant and age).
1557: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
1558: and, according on how parameters are entered, the position of the coefficient xij(nc) of the
1559: ncth covariate in the global vector x is given by the formula:
1560: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
1561: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
1562: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
1563: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1564: Outputs ps[i][j] the probability to be observed in j being in j according to
1565: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1566: */
1567: double s1, lnpijopii;
1568: /*double t34;*/
1569: int i,j,j1, nc, ii, jj;
1570:
1571: for(i=1; i<= nlstate; i++){
1572: for(j=1; j<i;j++){
1573: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1574: /*lnpijopii += param[i][j][nc]*cov[nc];*/
1575: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
1576: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1577: }
1578: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1579: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1580: }
1581: for(j=i+1; j<=nlstate+ndeath;j++){
1582: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1583: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
1584: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
1585: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1586: }
1587: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1588: }
1589: }
1590:
1591: for(i=1; i<= nlstate; i++){
1592: s1=0;
1593: for(j=1; j<i; j++){
1594: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1595: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1596: }
1597: for(j=i+1; j<=nlstate+ndeath; j++){
1598: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1599: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1600: }
1601: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1602: ps[i][i]=1./(s1+1.);
1603: /* Computing other pijs */
1604: for(j=1; j<i; j++)
1605: ps[i][j]= exp(ps[i][j])*ps[i][i];
1606: for(j=i+1; j<=nlstate+ndeath; j++)
1607: ps[i][j]= exp(ps[i][j])*ps[i][i];
1608: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
1609: } /* end i */
1610:
1611: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
1612: for(jj=1; jj<= nlstate+ndeath; jj++){
1613: ps[ii][jj]=0;
1614: ps[ii][ii]=1;
1615: }
1616: }
1617:
1618:
1619: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
1620: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */
1621: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
1622: /* } */
1623: /* printf("\n "); */
1624: /* } */
1625: /* printf("\n ");printf("%lf ",cov[2]);*/
1626: /*
1627: for(i=1; i<= npar; i++) printf("%f ",x[i]);
1628: goto end;*/
1629: return ps;
1630: }
1631:
1632: /**************** Product of 2 matrices ******************/
1633:
1634: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1635: {
1636: /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
1637: b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
1638: /* in, b, out are matrice of pointers which should have been initialized
1639: before: only the contents of out is modified. The function returns
1640: a pointer to pointers identical to out */
1641: int i, j, k;
1642: for(i=nrl; i<= nrh; i++)
1643: for(k=ncolol; k<=ncoloh; k++){
1644: out[i][k]=0.;
1645: for(j=ncl; j<=nch; j++)
1646: out[i][k] +=in[i][j]*b[j][k];
1647: }
1648: return out;
1649: }
1650:
1651:
1652: /************* Higher Matrix Product ***************/
1653:
1654: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
1655: {
1656: /* Computes the transition matrix starting at age 'age' over
1657: 'nhstepm*hstepm*stepm' months (i.e. until
1658: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
1659: nhstepm*hstepm matrices.
1660: Output is stored in matrix po[i][j][h] for h every 'hstepm' step
1661: (typically every 2 years instead of every month which is too big
1662: for the memory).
1663: Model is determined by parameters x and covariates have to be
1664: included manually here.
1665:
1666: */
1667:
1668: int i, j, d, h, k;
1669: double **out, cov[NCOVMAX+1];
1670: double **newm;
1671:
1672: /* Hstepm could be zero and should return the unit matrix */
1673: for (i=1;i<=nlstate+ndeath;i++)
1674: for (j=1;j<=nlstate+ndeath;j++){
1675: oldm[i][j]=(i==j ? 1.0 : 0.0);
1676: po[i][j][0]=(i==j ? 1.0 : 0.0);
1677: }
1678: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1679: for(h=1; h <=nhstepm; h++){
1680: for(d=1; d <=hstepm; d++){
1681: newm=savm;
1682: /* Covariates have to be included here again */
1683: cov[1]=1.;
1684: cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
1685: for (k=1; k<=cptcovn;k++)
1686: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1687: for (k=1; k<=cptcovage;k++)
1688: cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
1689: for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1690: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
1691:
1692:
1693: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
1694: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1695: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
1696: pmij(pmmij,cov,ncovmodel,x,nlstate));
1697: savm=oldm;
1698: oldm=newm;
1699: }
1700: for(i=1; i<=nlstate+ndeath; i++)
1701: for(j=1;j<=nlstate+ndeath;j++) {
1702: po[i][j][h]=newm[i][j];
1703: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1704: }
1705: /*printf("h=%d ",h);*/
1706: } /* end h */
1707: /* printf("\n H=%d \n",h); */
1708: return po;
1709: }
1710:
1711: #ifdef NLOPT
1712: double myfunc(unsigned n, const double *p1, double *grad, void *pd){
1713: double fret;
1714: double *xt;
1715: int j;
1716: myfunc_data *d2 = (myfunc_data *) pd;
1717: /* xt = (p1-1); */
1718: xt=vector(1,n);
1719: for (j=1;j<=n;j++) xt[j]=p1[j-1]; /* xt[1]=p1[0] */
1720:
1721: fret=(d2->function)(xt); /* p xt[1]@8 is fine */
1722: /* fret=(*func)(xt); /\* p xt[1]@8 is fine *\/ */
1723: printf("Function = %.12lf ",fret);
1724: for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]);
1725: printf("\n");
1726: free_vector(xt,1,n);
1727: return fret;
1728: }
1729: #endif
1730:
1731: /*************** log-likelihood *************/
1732: double func( double *x)
1733: {
1734: int i, ii, j, k, mi, d, kk;
1735: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1736: double **out;
1737: double sw; /* Sum of weights */
1738: double lli; /* Individual log likelihood */
1739: int s1, s2;
1740: double bbh, survp;
1741: long ipmx;
1742: /*extern weight */
1743: /* We are differentiating ll according to initial status */
1744: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
1745: /*for(i=1;i<imx;i++)
1746: printf(" %d\n",s[4][i]);
1747: */
1748:
1749: ++countcallfunc;
1750:
1751: cov[1]=1.;
1752:
1753: for(k=1; k<=nlstate; k++) ll[k]=0.;
1754:
1755: if(mle==1){
1756: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1757: /* Computes the values of the ncovmodel covariates of the model
1758: depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
1759: Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
1760: to be observed in j being in i according to the model.
1761: */
1762: for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1763: cov[2+k]=covar[Tvar[k]][i];
1764: }
1765: /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4]
1766: is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]
1767: has been calculated etc */
1768: for(mi=1; mi<= wav[i]-1; mi++){
1769: for (ii=1;ii<=nlstate+ndeath;ii++)
1770: for (j=1;j<=nlstate+ndeath;j++){
1771: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1772: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1773: }
1774: for(d=0; d<dh[mi][i]; d++){
1775: newm=savm;
1776: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1777: for (kk=1; kk<=cptcovage;kk++) {
1778: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; /* Tage[kk] gives the data-covariate associated with age */
1779: }
1780: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1781: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1782: savm=oldm;
1783: oldm=newm;
1784: } /* end mult */
1785:
1786: /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
1787: /* But now since version 0.9 we anticipate for bias at large stepm.
1788: * If stepm is larger than one month (smallest stepm) and if the exact delay
1789: * (in months) between two waves is not a multiple of stepm, we rounded to
1790: * the nearest (and in case of equal distance, to the lowest) interval but now
1791: * we keep into memory the bias bh[mi][i] and also the previous matrix product
1792: * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
1793: * probability in order to take into account the bias as a fraction of the way
1794: * from savm to out if bh is negative or even beyond if bh is positive. bh varies
1795: * -stepm/2 to stepm/2 .
1796: * For stepm=1 the results are the same as for previous versions of Imach.
1797: * For stepm > 1 the results are less biased than in previous versions.
1798: */
1799: s1=s[mw[mi][i]][i];
1800: s2=s[mw[mi+1][i]][i];
1801: bbh=(double)bh[mi][i]/(double)stepm;
1802: /* bias bh is positive if real duration
1803: * is higher than the multiple of stepm and negative otherwise.
1804: */
1805: /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
1806: if( s2 > nlstate){
1807: /* i.e. if s2 is a death state and if the date of death is known
1808: then the contribution to the likelihood is the probability to
1809: die between last step unit time and current step unit time,
1810: which is also equal to probability to die before dh
1811: minus probability to die before dh-stepm .
1812: In version up to 0.92 likelihood was computed
1813: as if date of death was unknown. Death was treated as any other
1814: health state: the date of the interview describes the actual state
1815: and not the date of a change in health state. The former idea was
1816: to consider that at each interview the state was recorded
1817: (healthy, disable or death) and IMaCh was corrected; but when we
1818: introduced the exact date of death then we should have modified
1819: the contribution of an exact death to the likelihood. This new
1820: contribution is smaller and very dependent of the step unit
1821: stepm. It is no more the probability to die between last interview
1822: and month of death but the probability to survive from last
1823: interview up to one month before death multiplied by the
1824: probability to die within a month. Thanks to Chris
1825: Jackson for correcting this bug. Former versions increased
1826: mortality artificially. The bad side is that we add another loop
1827: which slows down the processing. The difference can be up to 10%
1828: lower mortality.
1829: */
1830: lli=log(out[s1][s2] - savm[s1][s2]);
1831:
1832:
1833: } else if (s2==-2) {
1834: for (j=1,survp=0. ; j<=nlstate; j++)
1835: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1836: /*survp += out[s1][j]; */
1837: lli= log(survp);
1838: }
1839:
1840: else if (s2==-4) {
1841: for (j=3,survp=0. ; j<=nlstate; j++)
1842: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1843: lli= log(survp);
1844: }
1845:
1846: else if (s2==-5) {
1847: for (j=1,survp=0. ; j<=2; j++)
1848: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1849: lli= log(survp);
1850: }
1851:
1852: else{
1853: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1854: /* 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 */
1855: }
1856: /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
1857: /*if(lli ==000.0)*/
1858: /*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); */
1859: ipmx +=1;
1860: sw += weight[i];
1861: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1862: } /* end of wave */
1863: } /* end of individual */
1864: } else if(mle==2){
1865: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1866: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1867: for(mi=1; mi<= wav[i]-1; mi++){
1868: for (ii=1;ii<=nlstate+ndeath;ii++)
1869: for (j=1;j<=nlstate+ndeath;j++){
1870: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1871: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1872: }
1873: for(d=0; d<=dh[mi][i]; d++){
1874: newm=savm;
1875: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1876: for (kk=1; kk<=cptcovage;kk++) {
1877: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1878: }
1879: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1880: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1881: savm=oldm;
1882: oldm=newm;
1883: } /* end mult */
1884:
1885: s1=s[mw[mi][i]][i];
1886: s2=s[mw[mi+1][i]][i];
1887: bbh=(double)bh[mi][i]/(double)stepm;
1888: 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 */
1889: ipmx +=1;
1890: sw += weight[i];
1891: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1892: } /* end of wave */
1893: } /* end of individual */
1894: } else if(mle==3){ /* exponential inter-extrapolation */
1895: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1896: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1897: for(mi=1; mi<= wav[i]-1; mi++){
1898: for (ii=1;ii<=nlstate+ndeath;ii++)
1899: for (j=1;j<=nlstate+ndeath;j++){
1900: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1901: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1902: }
1903: for(d=0; d<dh[mi][i]; d++){
1904: newm=savm;
1905: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1906: for (kk=1; kk<=cptcovage;kk++) {
1907: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1908: }
1909: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1910: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1911: savm=oldm;
1912: oldm=newm;
1913: } /* end mult */
1914:
1915: s1=s[mw[mi][i]][i];
1916: s2=s[mw[mi+1][i]][i];
1917: bbh=(double)bh[mi][i]/(double)stepm;
1918: lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2])); /* exponential inter-extrapolation */
1919: ipmx +=1;
1920: sw += weight[i];
1921: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1922: } /* end of wave */
1923: } /* end of individual */
1924: }else if (mle==4){ /* ml=4 no inter-extrapolation */
1925: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1926: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1927: for(mi=1; mi<= wav[i]-1; mi++){
1928: for (ii=1;ii<=nlstate+ndeath;ii++)
1929: for (j=1;j<=nlstate+ndeath;j++){
1930: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1931: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1932: }
1933: for(d=0; d<dh[mi][i]; d++){
1934: newm=savm;
1935: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1936: for (kk=1; kk<=cptcovage;kk++) {
1937: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1938: }
1939:
1940: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1941: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1942: savm=oldm;
1943: oldm=newm;
1944: } /* end mult */
1945:
1946: s1=s[mw[mi][i]][i];
1947: s2=s[mw[mi+1][i]][i];
1948: if( s2 > nlstate){
1949: lli=log(out[s1][s2] - savm[s1][s2]);
1950: }else{
1951: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
1952: }
1953: ipmx +=1;
1954: sw += weight[i];
1955: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1956: /* 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]); */
1957: } /* end of wave */
1958: } /* end of individual */
1959: }else{ /* ml=5 no inter-extrapolation no jackson =0.8a */
1960: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1961: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1962: for(mi=1; mi<= wav[i]-1; mi++){
1963: for (ii=1;ii<=nlstate+ndeath;ii++)
1964: for (j=1;j<=nlstate+ndeath;j++){
1965: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1966: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1967: }
1968: for(d=0; d<dh[mi][i]; d++){
1969: newm=savm;
1970: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1971: for (kk=1; kk<=cptcovage;kk++) {
1972: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1973: }
1974:
1975: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1976: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1977: savm=oldm;
1978: oldm=newm;
1979: } /* end mult */
1980:
1981: s1=s[mw[mi][i]][i];
1982: s2=s[mw[mi+1][i]][i];
1983: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
1984: ipmx +=1;
1985: sw += weight[i];
1986: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1987: /*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]);*/
1988: } /* end of wave */
1989: } /* end of individual */
1990: } /* End of if */
1991: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
1992: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
1993: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
1994: return -l;
1995: }
1996:
1997: /*************** log-likelihood *************/
1998: double funcone( double *x)
1999: {
2000: /* Same as likeli but slower because of a lot of printf and if */
2001: int i, ii, j, k, mi, d, kk;
2002: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
2003: double **out;
2004: double lli; /* Individual log likelihood */
2005: double llt;
2006: int s1, s2;
2007: double bbh, survp;
2008: /*extern weight */
2009: /* We are differentiating ll according to initial status */
2010: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2011: /*for(i=1;i<imx;i++)
2012: printf(" %d\n",s[4][i]);
2013: */
2014: cov[1]=1.;
2015:
2016: for(k=1; k<=nlstate; k++) ll[k]=0.;
2017:
2018: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2019: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2020: for(mi=1; mi<= wav[i]-1; mi++){
2021: for (ii=1;ii<=nlstate+ndeath;ii++)
2022: for (j=1;j<=nlstate+ndeath;j++){
2023: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2024: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2025: }
2026: for(d=0; d<dh[mi][i]; d++){
2027: newm=savm;
2028: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2029: for (kk=1; kk<=cptcovage;kk++) {
2030: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2031: }
2032: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
2033: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2034: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2035: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
2036: /* 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
2037: savm=oldm;
2038: oldm=newm;
2039: } /* end mult */
2040:
2041: s1=s[mw[mi][i]][i];
2042: s2=s[mw[mi+1][i]][i];
2043: bbh=(double)bh[mi][i]/(double)stepm;
2044: /* bias is positive if real duration
2045: * is higher than the multiple of stepm and negative otherwise.
2046: */
2047: if( s2 > nlstate && (mle <5) ){ /* Jackson */
2048: lli=log(out[s1][s2] - savm[s1][s2]);
2049: } else if (s2==-2) {
2050: for (j=1,survp=0. ; j<=nlstate; j++)
2051: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2052: lli= log(survp);
2053: }else if (mle==1){
2054: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2055: } else if(mle==2){
2056: 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 */
2057: } else if(mle==3){ /* exponential inter-extrapolation */
2058: 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 */
2059: } else if (mle==4){ /* mle=4 no inter-extrapolation */
2060: lli=log(out[s1][s2]); /* Original formula */
2061: } else{ /* mle=0 back to 1 */
2062: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2063: /*lli=log(out[s1][s2]); */ /* Original formula */
2064: } /* End of if */
2065: ipmx +=1;
2066: sw += weight[i];
2067: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2068: /*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]); */
2069: if(globpr){
2070: fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
2071: %11.6f %11.6f %11.6f ", \
2072: num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
2073: 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
2074: for(k=1,llt=0.,l=0.; k<=nlstate; k++){
2075: llt +=ll[k]*gipmx/gsw;
2076: fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
2077: }
2078: fprintf(ficresilk," %10.6f\n", -llt);
2079: }
2080: } /* end of wave */
2081: } /* end of individual */
2082: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2083: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2084: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2085: if(globpr==0){ /* First time we count the contributions and weights */
2086: gipmx=ipmx;
2087: gsw=sw;
2088: }
2089: return -l;
2090: }
2091:
2092:
2093: /*************** function likelione ***********/
2094: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
2095: {
2096: /* This routine should help understanding what is done with
2097: the selection of individuals/waves and
2098: to check the exact contribution to the likelihood.
2099: Plotting could be done.
2100: */
2101: int k;
2102:
2103: if(*globpri !=0){ /* Just counts and sums, no printings */
2104: strcpy(fileresilk,"ilk");
2105: strcat(fileresilk,fileres);
2106: if((ficresilk=fopen(fileresilk,"w"))==NULL) {
2107: printf("Problem with resultfile: %s\n", fileresilk);
2108: fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
2109: }
2110: 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");
2111: fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
2112: /* i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
2113: for(k=1; k<=nlstate; k++)
2114: fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
2115: fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
2116: }
2117:
2118: *fretone=(*funcone)(p);
2119: if(*globpri !=0){
2120: fclose(ficresilk);
2121: fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
2122: fflush(fichtm);
2123: }
2124: return;
2125: }
2126:
2127:
2128: /*********** Maximum Likelihood Estimation ***************/
2129:
2130: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
2131: {
2132: int i,j, iter;
2133: double **xi;
2134: double fret;
2135: double fretone; /* Only one call to likelihood */
2136: /* char filerespow[FILENAMELENGTH];*/
2137:
2138: #ifdef NLOPT
2139: int creturn;
2140: nlopt_opt opt;
2141: /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
2142: double *lb;
2143: double minf; /* the minimum objective value, upon return */
2144: double * p1; /* Shifted parameters from 0 instead of 1 */
2145: myfunc_data dinst, *d = &dinst;
2146: #endif
2147:
2148:
2149: xi=matrix(1,npar,1,npar);
2150: for (i=1;i<=npar;i++)
2151: for (j=1;j<=npar;j++)
2152: xi[i][j]=(i==j ? 1.0 : 0.0);
2153: printf("Powell\n"); fprintf(ficlog,"Powell\n");
2154: strcpy(filerespow,"pow");
2155: strcat(filerespow,fileres);
2156: if((ficrespow=fopen(filerespow,"w"))==NULL) {
2157: printf("Problem with resultfile: %s\n", filerespow);
2158: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
2159: }
2160: fprintf(ficrespow,"# Powell\n# iter -2*LL");
2161: for (i=1;i<=nlstate;i++)
2162: for(j=1;j<=nlstate+ndeath;j++)
2163: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
2164: fprintf(ficrespow,"\n");
2165: #ifdef POWELL
2166: powell(p,xi,npar,ftol,&iter,&fret,func);
2167: #endif
2168:
2169: #ifdef NLOPT
2170: #ifdef NEWUOA
2171: opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
2172: #else
2173: opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
2174: #endif
2175: lb=vector(0,npar-1);
2176: for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
2177: nlopt_set_lower_bounds(opt, lb);
2178: nlopt_set_initial_step1(opt, 0.1);
2179:
2180: p1= (p+1); /* p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
2181: d->function = func;
2182: printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
2183: nlopt_set_min_objective(opt, myfunc, d);
2184: nlopt_set_xtol_rel(opt, ftol);
2185: if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
2186: printf("nlopt failed! %d\n",creturn);
2187: }
2188: else {
2189: printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
2190: printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
2191: iter=1; /* not equal */
2192: }
2193: nlopt_destroy(opt);
2194: #endif
2195: free_matrix(xi,1,npar,1,npar);
2196: fclose(ficrespow);
2197: printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2198: fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2199: fprintf(ficres,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2200:
2201: }
2202:
2203: /**** Computes Hessian and covariance matrix ***/
2204: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
2205: {
2206: double **a,**y,*x,pd;
2207: double **hess;
2208: int i, j,jk;
2209: int *indx;
2210:
2211: double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
2212: double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
2213: void lubksb(double **a, int npar, int *indx, double b[]) ;
2214: void ludcmp(double **a, int npar, int *indx, double *d) ;
2215: double gompertz(double p[]);
2216: hess=matrix(1,npar,1,npar);
2217:
2218: printf("\nCalculation of the hessian matrix. Wait...\n");
2219: fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
2220: for (i=1;i<=npar;i++){
2221: printf("%d",i);fflush(stdout);
2222: fprintf(ficlog,"%d",i);fflush(ficlog);
2223:
2224: hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
2225:
2226: /* printf(" %f ",p[i]);
2227: printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
2228: }
2229:
2230: for (i=1;i<=npar;i++) {
2231: for (j=1;j<=npar;j++) {
2232: if (j>i) {
2233: printf(".%d%d",i,j);fflush(stdout);
2234: fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
2235: hess[i][j]=hessij(p,delti,i,j,func,npar);
2236:
2237: hess[j][i]=hess[i][j];
2238: /*printf(" %lf ",hess[i][j]);*/
2239: }
2240: }
2241: }
2242: printf("\n");
2243: fprintf(ficlog,"\n");
2244:
2245: printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
2246: fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
2247:
2248: a=matrix(1,npar,1,npar);
2249: y=matrix(1,npar,1,npar);
2250: x=vector(1,npar);
2251: indx=ivector(1,npar);
2252: for (i=1;i<=npar;i++)
2253: for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
2254: ludcmp(a,npar,indx,&pd);
2255:
2256: for (j=1;j<=npar;j++) {
2257: for (i=1;i<=npar;i++) x[i]=0;
2258: x[j]=1;
2259: lubksb(a,npar,indx,x);
2260: for (i=1;i<=npar;i++){
2261: matcov[i][j]=x[i];
2262: }
2263: }
2264:
2265: printf("\n#Hessian matrix#\n");
2266: fprintf(ficlog,"\n#Hessian matrix#\n");
2267: for (i=1;i<=npar;i++) {
2268: for (j=1;j<=npar;j++) {
2269: printf("%.3e ",hess[i][j]);
2270: fprintf(ficlog,"%.3e ",hess[i][j]);
2271: }
2272: printf("\n");
2273: fprintf(ficlog,"\n");
2274: }
2275:
2276: /* Recompute Inverse */
2277: for (i=1;i<=npar;i++)
2278: for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
2279: ludcmp(a,npar,indx,&pd);
2280:
2281: /* printf("\n#Hessian matrix recomputed#\n");
2282:
2283: for (j=1;j<=npar;j++) {
2284: for (i=1;i<=npar;i++) x[i]=0;
2285: x[j]=1;
2286: lubksb(a,npar,indx,x);
2287: for (i=1;i<=npar;i++){
2288: y[i][j]=x[i];
2289: printf("%.3e ",y[i][j]);
2290: fprintf(ficlog,"%.3e ",y[i][j]);
2291: }
2292: printf("\n");
2293: fprintf(ficlog,"\n");
2294: }
2295: */
2296:
2297: free_matrix(a,1,npar,1,npar);
2298: free_matrix(y,1,npar,1,npar);
2299: free_vector(x,1,npar);
2300: free_ivector(indx,1,npar);
2301: free_matrix(hess,1,npar,1,npar);
2302:
2303:
2304: }
2305:
2306: /*************** hessian matrix ****************/
2307: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
2308: {
2309: int i;
2310: int l=1, lmax=20;
2311: double k1,k2;
2312: double p2[MAXPARM+1]; /* identical to x */
2313: double res;
2314: double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
2315: double fx;
2316: int k=0,kmax=10;
2317: double l1;
2318:
2319: fx=func(x);
2320: for (i=1;i<=npar;i++) p2[i]=x[i];
2321: for(l=0 ; l <=lmax; l++){ /* Enlarging the zone around the Maximum */
2322: l1=pow(10,l);
2323: delts=delt;
2324: for(k=1 ; k <kmax; k=k+1){
2325: delt = delta*(l1*k);
2326: p2[theta]=x[theta] +delt;
2327: k1=func(p2)-fx; /* Might be negative if too close to the theoretical maximum */
2328: p2[theta]=x[theta]-delt;
2329: k2=func(p2)-fx;
2330: /*res= (k1-2.0*fx+k2)/delt/delt; */
2331: res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
2332:
2333: #ifdef DEBUGHESS
2334: 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);
2335: 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);
2336: #endif
2337: /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
2338: if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
2339: k=kmax;
2340: }
2341: else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
2342: k=kmax; l=lmax*10.;
2343: }
2344: else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
2345: delts=delt;
2346: }
2347: }
2348: }
2349: delti[theta]=delts;
2350: return res;
2351:
2352: }
2353:
2354: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
2355: {
2356: int i;
2357: int l=1, l1, lmax=20;
2358: double k1,k2,k3,k4,res,fx;
2359: double p2[MAXPARM+1];
2360: int k;
2361:
2362: fx=func(x);
2363: for (k=1; k<=2; k++) {
2364: for (i=1;i<=npar;i++) p2[i]=x[i];
2365: p2[thetai]=x[thetai]+delti[thetai]/k;
2366: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2367: k1=func(p2)-fx;
2368:
2369: p2[thetai]=x[thetai]+delti[thetai]/k;
2370: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2371: k2=func(p2)-fx;
2372:
2373: p2[thetai]=x[thetai]-delti[thetai]/k;
2374: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2375: k3=func(p2)-fx;
2376:
2377: p2[thetai]=x[thetai]-delti[thetai]/k;
2378: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2379: k4=func(p2)-fx;
2380: res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
2381: #ifdef DEBUG
2382: 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);
2383: 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);
2384: #endif
2385: }
2386: return res;
2387: }
2388:
2389: /************** Inverse of matrix **************/
2390: void ludcmp(double **a, int n, int *indx, double *d)
2391: {
2392: int i,imax,j,k;
2393: double big,dum,sum,temp;
2394: double *vv;
2395:
2396: vv=vector(1,n);
2397: *d=1.0;
2398: for (i=1;i<=n;i++) {
2399: big=0.0;
2400: for (j=1;j<=n;j++)
2401: if ((temp=fabs(a[i][j])) > big) big=temp;
2402: if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
2403: vv[i]=1.0/big;
2404: }
2405: for (j=1;j<=n;j++) {
2406: for (i=1;i<j;i++) {
2407: sum=a[i][j];
2408: for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
2409: a[i][j]=sum;
2410: }
2411: big=0.0;
2412: for (i=j;i<=n;i++) {
2413: sum=a[i][j];
2414: for (k=1;k<j;k++)
2415: sum -= a[i][k]*a[k][j];
2416: a[i][j]=sum;
2417: if ( (dum=vv[i]*fabs(sum)) >= big) {
2418: big=dum;
2419: imax=i;
2420: }
2421: }
2422: if (j != imax) {
2423: for (k=1;k<=n;k++) {
2424: dum=a[imax][k];
2425: a[imax][k]=a[j][k];
2426: a[j][k]=dum;
2427: }
2428: *d = -(*d);
2429: vv[imax]=vv[j];
2430: }
2431: indx[j]=imax;
2432: if (a[j][j] == 0.0) a[j][j]=TINY;
2433: if (j != n) {
2434: dum=1.0/(a[j][j]);
2435: for (i=j+1;i<=n;i++) a[i][j] *= dum;
2436: }
2437: }
2438: free_vector(vv,1,n); /* Doesn't work */
2439: ;
2440: }
2441:
2442: void lubksb(double **a, int n, int *indx, double b[])
2443: {
2444: int i,ii=0,ip,j;
2445: double sum;
2446:
2447: for (i=1;i<=n;i++) {
2448: ip=indx[i];
2449: sum=b[ip];
2450: b[ip]=b[i];
2451: if (ii)
2452: for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
2453: else if (sum) ii=i;
2454: b[i]=sum;
2455: }
2456: for (i=n;i>=1;i--) {
2457: sum=b[i];
2458: for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
2459: b[i]=sum/a[i][i];
2460: }
2461: }
2462:
2463: void pstamp(FILE *fichier)
2464: {
2465: fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
2466: }
2467:
2468: /************ Frequencies ********************/
2469: 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[])
2470: { /* Some frequencies */
2471:
2472: int i, m, jk, k1,i1, j1, bool, z1,j;
2473: int first;
2474: double ***freq; /* Frequencies */
2475: double *pp, **prop;
2476: double pos,posprop, k2, dateintsum=0,k2cpt=0;
2477: char fileresp[FILENAMELENGTH];
2478:
2479: pp=vector(1,nlstate);
2480: prop=matrix(1,nlstate,iagemin,iagemax+3);
2481: strcpy(fileresp,"p");
2482: strcat(fileresp,fileres);
2483: if((ficresp=fopen(fileresp,"w"))==NULL) {
2484: printf("Problem with prevalence resultfile: %s\n", fileresp);
2485: fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
2486: exit(0);
2487: }
2488: freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
2489: j1=0;
2490:
2491: j=cptcoveff;
2492: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2493:
2494: first=1;
2495:
2496: /* for(k1=1; k1<=j ; k1++){ /* Loop on covariates */
2497: /* for(i1=1; i1<=ncodemax[k1];i1++){ /* Now it is 2 */
2498: /* j1++;
2499: */
2500: for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
2501: /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
2502: scanf("%d", i);*/
2503: for (i=-5; i<=nlstate+ndeath; i++)
2504: for (jk=-5; jk<=nlstate+ndeath; jk++)
2505: for(m=iagemin; m <= iagemax+3; m++)
2506: freq[i][jk][m]=0;
2507:
2508: for (i=1; i<=nlstate; i++)
2509: for(m=iagemin; m <= iagemax+3; m++)
2510: prop[i][m]=0;
2511:
2512: dateintsum=0;
2513: k2cpt=0;
2514: for (i=1; i<=imx; i++) {
2515: bool=1;
2516: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
2517: for (z1=1; z1<=cptcoveff; z1++)
2518: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
2519: /* Tests if the value of each of the covariates of i is equal to filter j1 */
2520: bool=0;
2521: /* 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",
2522: bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
2523: j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
2524: /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
2525: }
2526: }
2527:
2528: if (bool==1){
2529: for(m=firstpass; m<=lastpass; m++){
2530: k2=anint[m][i]+(mint[m][i]/12.);
2531: /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
2532: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2533: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2534: if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
2535: if (m<lastpass) {
2536: freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
2537: freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
2538: }
2539:
2540: if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
2541: dateintsum=dateintsum+k2;
2542: k2cpt++;
2543: }
2544: /*}*/
2545: }
2546: }
2547: } /* end i */
2548:
2549: /* fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
2550: pstamp(ficresp);
2551: if (cptcovn>0) {
2552: fprintf(ficresp, "\n#********** Variable ");
2553: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2554: fprintf(ficresp, "**********\n#");
2555: fprintf(ficlog, "\n#********** Variable ");
2556: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2557: fprintf(ficlog, "**********\n#");
2558: }
2559: for(i=1; i<=nlstate;i++)
2560: fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
2561: fprintf(ficresp, "\n");
2562:
2563: for(i=iagemin; i <= iagemax+3; i++){
2564: if(i==iagemax+3){
2565: fprintf(ficlog,"Total");
2566: }else{
2567: if(first==1){
2568: first=0;
2569: printf("See log file for details...\n");
2570: }
2571: fprintf(ficlog,"Age %d", i);
2572: }
2573: for(jk=1; jk <=nlstate ; jk++){
2574: for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
2575: pp[jk] += freq[jk][m][i];
2576: }
2577: for(jk=1; jk <=nlstate ; jk++){
2578: for(m=-1, pos=0; m <=0 ; m++)
2579: pos += freq[jk][m][i];
2580: if(pp[jk]>=1.e-10){
2581: if(first==1){
2582: printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
2583: }
2584: fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
2585: }else{
2586: if(first==1)
2587: printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2588: fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2589: }
2590: }
2591:
2592: for(jk=1; jk <=nlstate ; jk++){
2593: for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
2594: pp[jk] += freq[jk][m][i];
2595: }
2596: for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
2597: pos += pp[jk];
2598: posprop += prop[jk][i];
2599: }
2600: for(jk=1; jk <=nlstate ; jk++){
2601: if(pos>=1.e-5){
2602: if(first==1)
2603: printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2604: fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2605: }else{
2606: if(first==1)
2607: printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2608: fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2609: }
2610: if( i <= iagemax){
2611: if(pos>=1.e-5){
2612: fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
2613: /*probs[i][jk][j1]= pp[jk]/pos;*/
2614: /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
2615: }
2616: else
2617: fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
2618: }
2619: }
2620:
2621: for(jk=-1; jk <=nlstate+ndeath; jk++)
2622: for(m=-1; m <=nlstate+ndeath; m++)
2623: if(freq[jk][m][i] !=0 ) {
2624: if(first==1)
2625: printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
2626: fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
2627: }
2628: if(i <= iagemax)
2629: fprintf(ficresp,"\n");
2630: if(first==1)
2631: printf("Others in log...\n");
2632: fprintf(ficlog,"\n");
2633: }
2634: /*}*/
2635: }
2636: dateintmean=dateintsum/k2cpt;
2637:
2638: fclose(ficresp);
2639: free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
2640: free_vector(pp,1,nlstate);
2641: free_matrix(prop,1,nlstate,iagemin, iagemax+3);
2642: /* End of Freq */
2643: }
2644:
2645: /************ Prevalence ********************/
2646: 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)
2647: {
2648: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
2649: in each health status at the date of interview (if between dateprev1 and dateprev2).
2650: We still use firstpass and lastpass as another selection.
2651: */
2652:
2653: int i, m, jk, k1, i1, j1, bool, z1,j;
2654: double ***freq; /* Frequencies */
2655: double *pp, **prop;
2656: double pos,posprop;
2657: double y2; /* in fractional years */
2658: int iagemin, iagemax;
2659: int first; /** to stop verbosity which is redirected to log file */
2660:
2661: iagemin= (int) agemin;
2662: iagemax= (int) agemax;
2663: /*pp=vector(1,nlstate);*/
2664: prop=matrix(1,nlstate,iagemin,iagemax+3);
2665: /* freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
2666: j1=0;
2667:
2668: /*j=cptcoveff;*/
2669: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2670:
2671: first=1;
2672: for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
2673: /*for(i1=1; i1<=ncodemax[k1];i1++){
2674: j1++;*/
2675:
2676: for (i=1; i<=nlstate; i++)
2677: for(m=iagemin; m <= iagemax+3; m++)
2678: prop[i][m]=0.0;
2679:
2680: for (i=1; i<=imx; i++) { /* Each individual */
2681: bool=1;
2682: if (cptcovn>0) {
2683: for (z1=1; z1<=cptcoveff; z1++)
2684: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
2685: bool=0;
2686: }
2687: if (bool==1) {
2688: for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
2689: y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
2690: if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
2691: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2692: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2693: 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);
2694: if (s[m][i]>0 && s[m][i]<=nlstate) {
2695: /*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]]);*/
2696: prop[s[m][i]][(int)agev[m][i]] += weight[i];
2697: prop[s[m][i]][iagemax+3] += weight[i];
2698: }
2699: }
2700: } /* end selection of waves */
2701: }
2702: }
2703: for(i=iagemin; i <= iagemax+3; i++){
2704: for(jk=1,posprop=0; jk <=nlstate ; jk++) {
2705: posprop += prop[jk][i];
2706: }
2707:
2708: for(jk=1; jk <=nlstate ; jk++){
2709: if( i <= iagemax){
2710: if(posprop>=1.e-5){
2711: probs[i][jk][j1]= prop[jk][i]/posprop;
2712: } else{
2713: if(first==1){
2714: first=0;
2715: 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]);
2716: }
2717: }
2718: }
2719: }/* end jk */
2720: }/* end i */
2721: /*} *//* end i1 */
2722: } /* end j1 */
2723:
2724: /* free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
2725: /*free_vector(pp,1,nlstate);*/
2726: free_matrix(prop,1,nlstate, iagemin,iagemax+3);
2727: } /* End of prevalence */
2728:
2729: /************* Waves Concatenation ***************/
2730:
2731: 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)
2732: {
2733: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
2734: Death is a valid wave (if date is known).
2735: mw[mi][i] is the mi (mi=1 to wav[i]) effective wave of individual i
2736: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
2737: and mw[mi+1][i]. dh depends on stepm.
2738: */
2739:
2740: int i, mi, m;
2741: /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
2742: double sum=0., jmean=0.;*/
2743: int first;
2744: int j, k=0,jk, ju, jl;
2745: double sum=0.;
2746: first=0;
2747: jmin=1e+5;
2748: jmax=-1;
2749: jmean=0.;
2750: for(i=1; i<=imx; i++){
2751: mi=0;
2752: m=firstpass;
2753: while(s[m][i] <= nlstate){
2754: if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
2755: mw[++mi][i]=m;
2756: if(m >=lastpass)
2757: break;
2758: else
2759: m++;
2760: }/* end while */
2761: if (s[m][i] > nlstate){
2762: mi++; /* Death is another wave */
2763: /* if(mi==0) never been interviewed correctly before death */
2764: /* Only death is a correct wave */
2765: mw[mi][i]=m;
2766: }
2767:
2768: wav[i]=mi;
2769: if(mi==0){
2770: nbwarn++;
2771: if(first==0){
2772: printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
2773: first=1;
2774: }
2775: if(first==1){
2776: fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
2777: }
2778: } /* end mi==0 */
2779: } /* End individuals */
2780:
2781: for(i=1; i<=imx; i++){
2782: for(mi=1; mi<wav[i];mi++){
2783: if (stepm <=0)
2784: dh[mi][i]=1;
2785: else{
2786: if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
2787: if (agedc[i] < 2*AGESUP) {
2788: j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
2789: if(j==0) j=1; /* Survives at least one month after exam */
2790: else if(j<0){
2791: nberr++;
2792: 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]);
2793: j=1; /* Temporary Dangerous patch */
2794: 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);
2795: 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]);
2796: 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);
2797: }
2798: k=k+1;
2799: if (j >= jmax){
2800: jmax=j;
2801: ijmax=i;
2802: }
2803: if (j <= jmin){
2804: jmin=j;
2805: ijmin=i;
2806: }
2807: sum=sum+j;
2808: /*if (j<0) printf("j=%d num=%d \n",j,i);*/
2809: /* printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
2810: }
2811: }
2812: else{
2813: j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
2814: /* 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]); */
2815:
2816: k=k+1;
2817: if (j >= jmax) {
2818: jmax=j;
2819: ijmax=i;
2820: }
2821: else if (j <= jmin){
2822: jmin=j;
2823: ijmin=i;
2824: }
2825: /* if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
2826: /*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]);*/
2827: if(j<0){
2828: nberr++;
2829: 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]);
2830: 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]);
2831: }
2832: sum=sum+j;
2833: }
2834: jk= j/stepm;
2835: jl= j -jk*stepm;
2836: ju= j -(jk+1)*stepm;
2837: if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
2838: if(jl==0){
2839: dh[mi][i]=jk;
2840: bh[mi][i]=0;
2841: }else{ /* We want a negative bias in order to only have interpolation ie
2842: * to avoid the price of an extra matrix product in likelihood */
2843: dh[mi][i]=jk+1;
2844: bh[mi][i]=ju;
2845: }
2846: }else{
2847: if(jl <= -ju){
2848: dh[mi][i]=jk;
2849: bh[mi][i]=jl; /* bias is positive if real duration
2850: * is higher than the multiple of stepm and negative otherwise.
2851: */
2852: }
2853: else{
2854: dh[mi][i]=jk+1;
2855: bh[mi][i]=ju;
2856: }
2857: if(dh[mi][i]==0){
2858: dh[mi][i]=1; /* At least one step */
2859: bh[mi][i]=ju; /* At least one step */
2860: /* 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);*/
2861: }
2862: } /* end if mle */
2863: }
2864: } /* end wave */
2865: }
2866: jmean=sum/k;
2867: 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);
2868: 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);
2869: }
2870:
2871: /*********** Tricode ****************************/
2872: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
2873: {
2874: /**< Uses cptcovn+2*cptcovprod as the number of covariates */
2875: /* Tvar[i]=atoi(stre); find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1
2876: /* Boring subroutine which should only output nbcode[Tvar[j]][k]
2877: * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
2878: /* nbcode[Tvar[j]][1]=
2879: */
2880:
2881: int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
2882: int modmaxcovj=0; /* Modality max of covariates j */
2883: int cptcode=0; /* Modality max of covariates j */
2884: int modmincovj=0; /* Modality min of covariates j */
2885:
2886:
2887: cptcoveff=0;
2888:
2889: for (k=-1; k < maxncov; k++) Ndum[k]=0;
2890: for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
2891:
2892: /* Loop on covariates without age and products */
2893: for (j=1; j<=(cptcovs); j++) { /* model V1 + V2*age+ V3 + V3*V4 : V1 + V3 = 2 only */
2894: for (i=1; i<=imx; i++) { /* Lopp on individuals: reads the data file to get the maximum value of the
2895: modality of this covariate Vj*/
2896: ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
2897: * If product of Vn*Vm, still boolean *:
2898: * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
2899: * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0 */
2900: /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
2901: modality of the nth covariate of individual i. */
2902: if (ij > modmaxcovj)
2903: modmaxcovj=ij;
2904: else if (ij < modmincovj)
2905: modmincovj=ij;
2906: if ((ij < -1) && (ij > NCOVMAX)){
2907: printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
2908: exit(1);
2909: }else
2910: Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
2911: /* If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
2912: /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
2913: /* getting the maximum value of the modality of the covariate
2914: (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
2915: female is 1, then modmaxcovj=1.*/
2916: }
2917: printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
2918: cptcode=modmaxcovj;
2919: /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
2920: /*for (i=0; i<=cptcode; i++) {*/
2921: for (i=modmincovj; i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
2922: printf("Frequencies of covariates %d V%d %d\n", j, Tvar[j], Ndum[i]);
2923: if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
2924: ncodemax[j]++; /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
2925: }
2926: /* In fact ncodemax[j]=2 (dichotom. variables only) but it could be more for
2927: historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
2928: } /* Ndum[-1] number of undefined modalities */
2929:
2930: /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
2931: /* For covariate j, modalities could be 1, 2, 3, 4. If Ndum[2]=0 ncodemax[j] is not 4 but 3 */
2932: /* If Ndum[3}= 635; Ndum[4]=0; Ndum[5]=0; Ndum[6]=27; Ndum[7]=125;
2933: modmincovj=3; modmaxcovj = 7;
2934: There are only 3 modalities non empty (or 2 if 27 is too few) : ncodemax[j]=3;
2935: which will be coded 0, 1, 2 which in binary on 3-1 digits are 0=00 1=01, 2=10; defining two dummy
2936: variables V1_1 and V1_2.
2937: nbcode[Tvar[j]][ij]=k;
2938: nbcode[Tvar[j]][1]=0;
2939: nbcode[Tvar[j]][2]=1;
2940: nbcode[Tvar[j]][3]=2;
2941: */
2942: ij=1; /* ij is similar to i but can jumps over null modalities */
2943: for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
2944: for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
2945: /*recode from 0 */
2946: if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
2947: nbcode[Tvar[j]][ij]=k; /* stores the modality in an array nbcode.
2948: k is a modality. If we have model=V1+V1*sex
2949: then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
2950: ij++;
2951: }
2952: if (ij > ncodemax[j]) break;
2953: } /* end of loop on */
2954: } /* end of loop on modality */
2955: } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/
2956:
2957: for (k=-1; k< maxncov; k++) Ndum[k]=0;
2958:
2959: for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */
2960: /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
2961: ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
2962: Ndum[ij]++;
2963: }
2964:
2965: ij=1;
2966: for (i=0; i<= maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
2967: /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
2968: if((Ndum[i]!=0) && (i<=ncovcol)){
2969: /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
2970: Tvaraff[ij]=i; /*For printing (unclear) */
2971: ij++;
2972: }else
2973: Tvaraff[ij]=0;
2974: }
2975: ij--;
2976: cptcoveff=ij; /*Number of total covariates*/
2977:
2978: }
2979:
2980:
2981: /*********** Health Expectancies ****************/
2982:
2983: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
2984:
2985: {
2986: /* Health expectancies, no variances */
2987: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2;
2988: int nhstepma, nstepma; /* Decreasing with age */
2989: double age, agelim, hf;
2990: double ***p3mat;
2991: double eip;
2992:
2993: pstamp(ficreseij);
2994: fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
2995: fprintf(ficreseij,"# Age");
2996: for(i=1; i<=nlstate;i++){
2997: for(j=1; j<=nlstate;j++){
2998: fprintf(ficreseij," e%1d%1d ",i,j);
2999: }
3000: fprintf(ficreseij," e%1d. ",i);
3001: }
3002: fprintf(ficreseij,"\n");
3003:
3004:
3005: if(estepm < stepm){
3006: printf ("Problem %d lower than %d\n",estepm, stepm);
3007: }
3008: else hstepm=estepm;
3009: /* We compute the life expectancy from trapezoids spaced every estepm months
3010: * This is mainly to measure the difference between two models: for example
3011: * if stepm=24 months pijx are given only every 2 years and by summing them
3012: * we are calculating an estimate of the Life Expectancy assuming a linear
3013: * progression in between and thus overestimating or underestimating according
3014: * to the curvature of the survival function. If, for the same date, we
3015: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3016: * to compare the new estimate of Life expectancy with the same linear
3017: * hypothesis. A more precise result, taking into account a more precise
3018: * curvature will be obtained if estepm is as small as stepm. */
3019:
3020: /* For example we decided to compute the life expectancy with the smallest unit */
3021: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3022: nhstepm is the number of hstepm from age to agelim
3023: nstepm is the number of stepm from age to agelin.
3024: Look at hpijx to understand the reason of that which relies in memory size
3025: and note for a fixed period like estepm months */
3026: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3027: survival function given by stepm (the optimization length). Unfortunately it
3028: means that if the survival funtion is printed only each two years of age and if
3029: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3030: results. So we changed our mind and took the option of the best precision.
3031: */
3032: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3033:
3034: agelim=AGESUP;
3035: /* If stepm=6 months */
3036: /* Computed by stepm unit matrices, product of hstepm matrices, stored
3037: in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
3038:
3039: /* nhstepm age range expressed in number of stepm */
3040: nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3041: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3042: /* if (stepm >= YEARM) hstepm=1;*/
3043: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3044: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3045:
3046: for (age=bage; age<=fage; age ++){
3047: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3048: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3049: /* if (stepm >= YEARM) hstepm=1;*/
3050: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3051:
3052: /* If stepm=6 months */
3053: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3054: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3055:
3056: hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3057:
3058: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3059:
3060: printf("%d|",(int)age);fflush(stdout);
3061: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3062:
3063: /* Computing expectancies */
3064: for(i=1; i<=nlstate;i++)
3065: for(j=1; j<=nlstate;j++)
3066: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3067: eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
3068:
3069: /* 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]);*/
3070:
3071: }
3072:
3073: fprintf(ficreseij,"%3.0f",age );
3074: for(i=1; i<=nlstate;i++){
3075: eip=0;
3076: for(j=1; j<=nlstate;j++){
3077: eip +=eij[i][j][(int)age];
3078: fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
3079: }
3080: fprintf(ficreseij,"%9.4f", eip );
3081: }
3082: fprintf(ficreseij,"\n");
3083:
3084: }
3085: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3086: printf("\n");
3087: fprintf(ficlog,"\n");
3088:
3089: }
3090:
3091: 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[] )
3092:
3093: {
3094: /* Covariances of health expectancies eij and of total life expectancies according
3095: to initial status i, ei. .
3096: */
3097: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
3098: int nhstepma, nstepma; /* Decreasing with age */
3099: double age, agelim, hf;
3100: double ***p3matp, ***p3matm, ***varhe;
3101: double **dnewm,**doldm;
3102: double *xp, *xm;
3103: double **gp, **gm;
3104: double ***gradg, ***trgradg;
3105: int theta;
3106:
3107: double eip, vip;
3108:
3109: varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
3110: xp=vector(1,npar);
3111: xm=vector(1,npar);
3112: dnewm=matrix(1,nlstate*nlstate,1,npar);
3113: doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
3114:
3115: pstamp(ficresstdeij);
3116: fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
3117: fprintf(ficresstdeij,"# Age");
3118: for(i=1; i<=nlstate;i++){
3119: for(j=1; j<=nlstate;j++)
3120: fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
3121: fprintf(ficresstdeij," e%1d. ",i);
3122: }
3123: fprintf(ficresstdeij,"\n");
3124:
3125: pstamp(ficrescveij);
3126: fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
3127: fprintf(ficrescveij,"# Age");
3128: for(i=1; i<=nlstate;i++)
3129: for(j=1; j<=nlstate;j++){
3130: cptj= (j-1)*nlstate+i;
3131: for(i2=1; i2<=nlstate;i2++)
3132: for(j2=1; j2<=nlstate;j2++){
3133: cptj2= (j2-1)*nlstate+i2;
3134: if(cptj2 <= cptj)
3135: fprintf(ficrescveij," %1d%1d,%1d%1d",i,j,i2,j2);
3136: }
3137: }
3138: fprintf(ficrescveij,"\n");
3139:
3140: if(estepm < stepm){
3141: printf ("Problem %d lower than %d\n",estepm, stepm);
3142: }
3143: else hstepm=estepm;
3144: /* We compute the life expectancy from trapezoids spaced every estepm months
3145: * This is mainly to measure the difference between two models: for example
3146: * if stepm=24 months pijx are given only every 2 years and by summing them
3147: * we are calculating an estimate of the Life Expectancy assuming a linear
3148: * progression in between and thus overestimating or underestimating according
3149: * to the curvature of the survival function. If, for the same date, we
3150: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3151: * to compare the new estimate of Life expectancy with the same linear
3152: * hypothesis. A more precise result, taking into account a more precise
3153: * curvature will be obtained if estepm is as small as stepm. */
3154:
3155: /* For example we decided to compute the life expectancy with the smallest unit */
3156: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3157: nhstepm is the number of hstepm from age to agelim
3158: nstepm is the number of stepm from age to agelin.
3159: Look at hpijx to understand the reason of that which relies in memory size
3160: and note for a fixed period like estepm months */
3161: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3162: survival function given by stepm (the optimization length). Unfortunately it
3163: means that if the survival funtion is printed only each two years of age and if
3164: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3165: results. So we changed our mind and took the option of the best precision.
3166: */
3167: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3168:
3169: /* If stepm=6 months */
3170: /* nhstepm age range expressed in number of stepm */
3171: agelim=AGESUP;
3172: nstepm=(int) rint((agelim-bage)*YEARM/stepm);
3173: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3174: /* if (stepm >= YEARM) hstepm=1;*/
3175: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3176:
3177: p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3178: p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3179: gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
3180: trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
3181: gp=matrix(0,nhstepm,1,nlstate*nlstate);
3182: gm=matrix(0,nhstepm,1,nlstate*nlstate);
3183:
3184: for (age=bage; age<=fage; age ++){
3185: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3186: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3187: /* if (stepm >= YEARM) hstepm=1;*/
3188: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3189:
3190: /* If stepm=6 months */
3191: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3192: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3193:
3194: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3195:
3196: /* Computing Variances of health expectancies */
3197: /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
3198: decrease memory allocation */
3199: for(theta=1; theta <=npar; theta++){
3200: for(i=1; i<=npar; i++){
3201: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3202: xm[i] = x[i] - (i==theta ?delti[theta]:0);
3203: }
3204: hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);
3205: hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);
3206:
3207: for(j=1; j<= nlstate; j++){
3208: for(i=1; i<=nlstate; i++){
3209: for(h=0; h<=nhstepm-1; h++){
3210: gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
3211: gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
3212: }
3213: }
3214: }
3215:
3216: for(ij=1; ij<= nlstate*nlstate; ij++)
3217: for(h=0; h<=nhstepm-1; h++){
3218: gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
3219: }
3220: }/* End theta */
3221:
3222:
3223: for(h=0; h<=nhstepm-1; h++)
3224: for(j=1; j<=nlstate*nlstate;j++)
3225: for(theta=1; theta <=npar; theta++)
3226: trgradg[h][j][theta]=gradg[h][theta][j];
3227:
3228:
3229: for(ij=1;ij<=nlstate*nlstate;ij++)
3230: for(ji=1;ji<=nlstate*nlstate;ji++)
3231: varhe[ij][ji][(int)age] =0.;
3232:
3233: printf("%d|",(int)age);fflush(stdout);
3234: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3235: for(h=0;h<=nhstepm-1;h++){
3236: for(k=0;k<=nhstepm-1;k++){
3237: matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
3238: matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
3239: for(ij=1;ij<=nlstate*nlstate;ij++)
3240: for(ji=1;ji<=nlstate*nlstate;ji++)
3241: varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
3242: }
3243: }
3244:
3245: /* Computing expectancies */
3246: hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3247: for(i=1; i<=nlstate;i++)
3248: for(j=1; j<=nlstate;j++)
3249: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3250: eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
3251:
3252: /* 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]);*/
3253:
3254: }
3255:
3256: fprintf(ficresstdeij,"%3.0f",age );
3257: for(i=1; i<=nlstate;i++){
3258: eip=0.;
3259: vip=0.;
3260: for(j=1; j<=nlstate;j++){
3261: eip += eij[i][j][(int)age];
3262: for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
3263: vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
3264: fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
3265: }
3266: fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
3267: }
3268: fprintf(ficresstdeij,"\n");
3269:
3270: fprintf(ficrescveij,"%3.0f",age );
3271: for(i=1; i<=nlstate;i++)
3272: for(j=1; j<=nlstate;j++){
3273: cptj= (j-1)*nlstate+i;
3274: for(i2=1; i2<=nlstate;i2++)
3275: for(j2=1; j2<=nlstate;j2++){
3276: cptj2= (j2-1)*nlstate+i2;
3277: if(cptj2 <= cptj)
3278: fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
3279: }
3280: }
3281: fprintf(ficrescveij,"\n");
3282:
3283: }
3284: free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
3285: free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
3286: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
3287: free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
3288: free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3289: free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3290: printf("\n");
3291: fprintf(ficlog,"\n");
3292:
3293: free_vector(xm,1,npar);
3294: free_vector(xp,1,npar);
3295: free_matrix(dnewm,1,nlstate*nlstate,1,npar);
3296: free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
3297: free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
3298: }
3299:
3300: /************ Variance ******************/
3301: 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[])
3302: {
3303: /* Variance of health expectancies */
3304: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
3305: /* double **newm;*/
3306: double **dnewm,**doldm;
3307: double **dnewmp,**doldmp;
3308: int i, j, nhstepm, hstepm, h, nstepm ;
3309: int k, cptcode;
3310: double *xp;
3311: double **gp, **gm; /* for var eij */
3312: double ***gradg, ***trgradg; /*for var eij */
3313: double **gradgp, **trgradgp; /* for var p point j */
3314: double *gpp, *gmp; /* for var p point j */
3315: double **varppt; /* for var p point j nlstate to nlstate+ndeath */
3316: double ***p3mat;
3317: double age,agelim, hf;
3318: double ***mobaverage;
3319: int theta;
3320: char digit[4];
3321: char digitp[25];
3322:
3323: char fileresprobmorprev[FILENAMELENGTH];
3324:
3325: if(popbased==1){
3326: if(mobilav!=0)
3327: strcpy(digitp,"-populbased-mobilav-");
3328: else strcpy(digitp,"-populbased-nomobil-");
3329: }
3330: else
3331: strcpy(digitp,"-stablbased-");
3332:
3333: if (mobilav!=0) {
3334: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3335: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
3336: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
3337: printf(" Error in movingaverage mobilav=%d\n",mobilav);
3338: }
3339: }
3340:
3341: strcpy(fileresprobmorprev,"prmorprev");
3342: sprintf(digit,"%-d",ij);
3343: /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
3344: strcat(fileresprobmorprev,digit); /* Tvar to be done */
3345: strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
3346: strcat(fileresprobmorprev,fileres);
3347: if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
3348: printf("Problem with resultfile: %s\n", fileresprobmorprev);
3349: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
3350: }
3351: printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3352:
3353: fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3354: pstamp(ficresprobmorprev);
3355: 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);
3356: fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
3357: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3358: fprintf(ficresprobmorprev," p.%-d SE",j);
3359: for(i=1; i<=nlstate;i++)
3360: fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
3361: }
3362: fprintf(ficresprobmorprev,"\n");
3363: fprintf(ficgp,"\n# Routine varevsij");
3364: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
3365: 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");
3366: fprintf(fichtm,"\n<br>%s <br>\n",digitp);
3367: /* } */
3368: varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3369: pstamp(ficresvij);
3370: fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n# (weighted average of eij where weights are ");
3371: if(popbased==1)
3372: 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);
3373: else
3374: fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
3375: fprintf(ficresvij,"# Age");
3376: for(i=1; i<=nlstate;i++)
3377: for(j=1; j<=nlstate;j++)
3378: fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
3379: fprintf(ficresvij,"\n");
3380:
3381: xp=vector(1,npar);
3382: dnewm=matrix(1,nlstate,1,npar);
3383: doldm=matrix(1,nlstate,1,nlstate);
3384: dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
3385: doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3386:
3387: gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
3388: gpp=vector(nlstate+1,nlstate+ndeath);
3389: gmp=vector(nlstate+1,nlstate+ndeath);
3390: trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
3391:
3392: if(estepm < stepm){
3393: printf ("Problem %d lower than %d\n",estepm, stepm);
3394: }
3395: else hstepm=estepm;
3396: /* For example we decided to compute the life expectancy with the smallest unit */
3397: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3398: nhstepm is the number of hstepm from age to agelim
3399: nstepm is the number of stepm from age to agelin.
3400: Look at function hpijx to understand why (it is linked to memory size questions) */
3401: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3402: survival function given by stepm (the optimization length). Unfortunately it
3403: means that if the survival funtion is printed every two years of age and if
3404: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3405: results. So we changed our mind and took the option of the best precision.
3406: */
3407: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3408: agelim = AGESUP;
3409: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3410: nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3411: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3412: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3413: gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
3414: gp=matrix(0,nhstepm,1,nlstate);
3415: gm=matrix(0,nhstepm,1,nlstate);
3416:
3417:
3418: for(theta=1; theta <=npar; theta++){
3419: for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
3420: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3421: }
3422: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3423: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3424:
3425: if (popbased==1) {
3426: if(mobilav ==0){
3427: for(i=1; i<=nlstate;i++)
3428: prlim[i][i]=probs[(int)age][i][ij];
3429: }else{ /* mobilav */
3430: for(i=1; i<=nlstate;i++)
3431: prlim[i][i]=mobaverage[(int)age][i][ij];
3432: }
3433: }
3434:
3435: for(j=1; j<= nlstate; j++){
3436: for(h=0; h<=nhstepm; h++){
3437: for(i=1, gp[h][j]=0.;i<=nlstate;i++)
3438: gp[h][j] += prlim[i][i]*p3mat[i][j][h];
3439: }
3440: }
3441: /* This for computing probability of death (h=1 means
3442: computed over hstepm matrices product = hstepm*stepm months)
3443: as a weighted average of prlim.
3444: */
3445: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3446: for(i=1,gpp[j]=0.; i<= nlstate; i++)
3447: gpp[j] += prlim[i][i]*p3mat[i][j][1];
3448: }
3449: /* end probability of death */
3450:
3451: for(i=1; i<=npar; i++) /* Computes gradient x - delta */
3452: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3453: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3454: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3455:
3456: if (popbased==1) {
3457: if(mobilav ==0){
3458: for(i=1; i<=nlstate;i++)
3459: prlim[i][i]=probs[(int)age][i][ij];
3460: }else{ /* mobilav */
3461: for(i=1; i<=nlstate;i++)
3462: prlim[i][i]=mobaverage[(int)age][i][ij];
3463: }
3464: }
3465:
3466: for(j=1; j<= nlstate; j++){ /* Sum of wi * eij = e.j */
3467: for(h=0; h<=nhstepm; h++){
3468: for(i=1, gm[h][j]=0.;i<=nlstate;i++)
3469: gm[h][j] += prlim[i][i]*p3mat[i][j][h];
3470: }
3471: }
3472: /* This for computing probability of death (h=1 means
3473: computed over hstepm matrices product = hstepm*stepm months)
3474: as a weighted average of prlim.
3475: */
3476: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3477: for(i=1,gmp[j]=0.; i<= nlstate; i++)
3478: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3479: }
3480: /* end probability of death */
3481:
3482: for(j=1; j<= nlstate; j++) /* vareij */
3483: for(h=0; h<=nhstepm; h++){
3484: gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
3485: }
3486:
3487: for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
3488: gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
3489: }
3490:
3491: } /* End theta */
3492:
3493: trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
3494:
3495: for(h=0; h<=nhstepm; h++) /* veij */
3496: for(j=1; j<=nlstate;j++)
3497: for(theta=1; theta <=npar; theta++)
3498: trgradg[h][j][theta]=gradg[h][theta][j];
3499:
3500: for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
3501: for(theta=1; theta <=npar; theta++)
3502: trgradgp[j][theta]=gradgp[theta][j];
3503:
3504:
3505: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3506: for(i=1;i<=nlstate;i++)
3507: for(j=1;j<=nlstate;j++)
3508: vareij[i][j][(int)age] =0.;
3509:
3510: for(h=0;h<=nhstepm;h++){
3511: for(k=0;k<=nhstepm;k++){
3512: matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
3513: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
3514: for(i=1;i<=nlstate;i++)
3515: for(j=1;j<=nlstate;j++)
3516: vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
3517: }
3518: }
3519:
3520: /* pptj */
3521: matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
3522: matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
3523: for(j=nlstate+1;j<=nlstate+ndeath;j++)
3524: for(i=nlstate+1;i<=nlstate+ndeath;i++)
3525: varppt[j][i]=doldmp[j][i];
3526: /* end ppptj */
3527: /* x centered again */
3528: hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);
3529: prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
3530:
3531: if (popbased==1) {
3532: if(mobilav ==0){
3533: for(i=1; i<=nlstate;i++)
3534: prlim[i][i]=probs[(int)age][i][ij];
3535: }else{ /* mobilav */
3536: for(i=1; i<=nlstate;i++)
3537: prlim[i][i]=mobaverage[(int)age][i][ij];
3538: }
3539: }
3540:
3541: /* This for computing probability of death (h=1 means
3542: computed over hstepm (estepm) matrices product = hstepm*stepm months)
3543: as a weighted average of prlim.
3544: */
3545: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3546: for(i=1,gmp[j]=0.;i<= nlstate; i++)
3547: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3548: }
3549: /* end probability of death */
3550:
3551: fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
3552: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3553: fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
3554: for(i=1; i<=nlstate;i++){
3555: fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
3556: }
3557: }
3558: fprintf(ficresprobmorprev,"\n");
3559:
3560: fprintf(ficresvij,"%.0f ",age );
3561: for(i=1; i<=nlstate;i++)
3562: for(j=1; j<=nlstate;j++){
3563: fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
3564: }
3565: fprintf(ficresvij,"\n");
3566: free_matrix(gp,0,nhstepm,1,nlstate);
3567: free_matrix(gm,0,nhstepm,1,nlstate);
3568: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
3569: free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
3570: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3571: } /* End age */
3572: free_vector(gpp,nlstate+1,nlstate+ndeath);
3573: free_vector(gmp,nlstate+1,nlstate+ndeath);
3574: free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
3575: free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
3576: fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
3577: /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
3578: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
3579: /* fprintf(ficgp,"\n plot \"%s\" u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
3580: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
3581: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
3582: fprintf(ficgp,"\n plot \"%s\" u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
3583: fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)) t \"95\%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
3584: fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
3585: fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
3586: 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);
3587: /* 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);
3588: */
3589: /* fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
3590: fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
3591:
3592: free_vector(xp,1,npar);
3593: free_matrix(doldm,1,nlstate,1,nlstate);
3594: free_matrix(dnewm,1,nlstate,1,npar);
3595: free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3596: free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
3597: free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3598: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3599: fclose(ficresprobmorprev);
3600: fflush(ficgp);
3601: fflush(fichtm);
3602: } /* end varevsij */
3603:
3604: /************ Variance of prevlim ******************/
3605: 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[])
3606: {
3607: /* Variance of prevalence limit */
3608: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
3609: double **newm;
3610: double **dnewm,**doldm;
3611: int i, j, nhstepm, hstepm;
3612: int k, cptcode;
3613: double *xp;
3614: double *gp, *gm;
3615: double **gradg, **trgradg;
3616: double age,agelim;
3617: int theta;
3618:
3619: pstamp(ficresvpl);
3620: fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
3621: fprintf(ficresvpl,"# Age");
3622: for(i=1; i<=nlstate;i++)
3623: fprintf(ficresvpl," %1d-%1d",i,i);
3624: fprintf(ficresvpl,"\n");
3625:
3626: xp=vector(1,npar);
3627: dnewm=matrix(1,nlstate,1,npar);
3628: doldm=matrix(1,nlstate,1,nlstate);
3629:
3630: hstepm=1*YEARM; /* Every year of age */
3631: hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
3632: agelim = AGESUP;
3633: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3634: nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3635: if (stepm >= YEARM) hstepm=1;
3636: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
3637: gradg=matrix(1,npar,1,nlstate);
3638: gp=vector(1,nlstate);
3639: gm=vector(1,nlstate);
3640:
3641: for(theta=1; theta <=npar; theta++){
3642: for(i=1; i<=npar; i++){ /* Computes gradient */
3643: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3644: }
3645: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3646: for(i=1;i<=nlstate;i++)
3647: gp[i] = prlim[i][i];
3648:
3649: for(i=1; i<=npar; i++) /* Computes gradient */
3650: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3651: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3652: for(i=1;i<=nlstate;i++)
3653: gm[i] = prlim[i][i];
3654:
3655: for(i=1;i<=nlstate;i++)
3656: gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
3657: } /* End theta */
3658:
3659: trgradg =matrix(1,nlstate,1,npar);
3660:
3661: for(j=1; j<=nlstate;j++)
3662: for(theta=1; theta <=npar; theta++)
3663: trgradg[j][theta]=gradg[theta][j];
3664:
3665: for(i=1;i<=nlstate;i++)
3666: varpl[i][(int)age] =0.;
3667: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
3668: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
3669: for(i=1;i<=nlstate;i++)
3670: varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
3671:
3672: fprintf(ficresvpl,"%.0f ",age );
3673: for(i=1; i<=nlstate;i++)
3674: fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
3675: fprintf(ficresvpl,"\n");
3676: free_vector(gp,1,nlstate);
3677: free_vector(gm,1,nlstate);
3678: free_matrix(gradg,1,npar,1,nlstate);
3679: free_matrix(trgradg,1,nlstate,1,npar);
3680: } /* End age */
3681:
3682: free_vector(xp,1,npar);
3683: free_matrix(doldm,1,nlstate,1,npar);
3684: free_matrix(dnewm,1,nlstate,1,nlstate);
3685:
3686: }
3687:
3688: /************ Variance of one-step probabilities ******************/
3689: 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[])
3690: {
3691: int i, j=0, i1, k1, l1, t, tj;
3692: int k2, l2, j1, z1;
3693: int k=0,l, cptcode;
3694: int first=1, first1, first2;
3695: double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
3696: double **dnewm,**doldm;
3697: double *xp;
3698: double *gp, *gm;
3699: double **gradg, **trgradg;
3700: double **mu;
3701: double age,agelim, cov[NCOVMAX+1];
3702: double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
3703: int theta;
3704: char fileresprob[FILENAMELENGTH];
3705: char fileresprobcov[FILENAMELENGTH];
3706: char fileresprobcor[FILENAMELENGTH];
3707: double ***varpij;
3708:
3709: strcpy(fileresprob,"prob");
3710: strcat(fileresprob,fileres);
3711: if((ficresprob=fopen(fileresprob,"w"))==NULL) {
3712: printf("Problem with resultfile: %s\n", fileresprob);
3713: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
3714: }
3715: strcpy(fileresprobcov,"probcov");
3716: strcat(fileresprobcov,fileres);
3717: if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
3718: printf("Problem with resultfile: %s\n", fileresprobcov);
3719: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
3720: }
3721: strcpy(fileresprobcor,"probcor");
3722: strcat(fileresprobcor,fileres);
3723: if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
3724: printf("Problem with resultfile: %s\n", fileresprobcor);
3725: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
3726: }
3727: printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3728: fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3729: printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3730: fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3731: printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3732: fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3733: pstamp(ficresprob);
3734: fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
3735: fprintf(ficresprob,"# Age");
3736: pstamp(ficresprobcov);
3737: fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
3738: fprintf(ficresprobcov,"# Age");
3739: pstamp(ficresprobcor);
3740: fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
3741: fprintf(ficresprobcor,"# Age");
3742:
3743:
3744: for(i=1; i<=nlstate;i++)
3745: for(j=1; j<=(nlstate+ndeath);j++){
3746: fprintf(ficresprob," p%1d-%1d (SE)",i,j);
3747: fprintf(ficresprobcov," p%1d-%1d ",i,j);
3748: fprintf(ficresprobcor," p%1d-%1d ",i,j);
3749: }
3750: /* fprintf(ficresprob,"\n");
3751: fprintf(ficresprobcov,"\n");
3752: fprintf(ficresprobcor,"\n");
3753: */
3754: xp=vector(1,npar);
3755: dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3756: doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
3757: mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
3758: varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
3759: first=1;
3760: fprintf(ficgp,"\n# Routine varprob");
3761: fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
3762: fprintf(fichtm,"\n");
3763:
3764: fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
3765: fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
3766: file %s<br>\n",optionfilehtmcov);
3767: fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
3768: and drawn. It helps understanding how is the covariance between two incidences.\
3769: They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
3770: 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. \
3771: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
3772: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
3773: standard deviations wide on each axis. <br>\
3774: Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
3775: and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
3776: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
3777:
3778: cov[1]=1;
3779: /* tj=cptcoveff; */
3780: tj = (int) pow(2,cptcoveff);
3781: if (cptcovn<1) {tj=1;ncodemax[1]=1;}
3782: j1=0;
3783: for(j1=1; j1<=tj;j1++){
3784: /*for(i1=1; i1<=ncodemax[t];i1++){ */
3785: /*j1++;*/
3786: if (cptcovn>0) {
3787: fprintf(ficresprob, "\n#********** Variable ");
3788: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3789: fprintf(ficresprob, "**********\n#\n");
3790: fprintf(ficresprobcov, "\n#********** Variable ");
3791: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3792: fprintf(ficresprobcov, "**********\n#\n");
3793:
3794: fprintf(ficgp, "\n#********** Variable ");
3795: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3796: fprintf(ficgp, "**********\n#\n");
3797:
3798:
3799: fprintf(fichtmcov, "\n<hr size=\"2\" color=\"#EC5E5E\">********** Variable ");
3800: for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3801: fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
3802:
3803: fprintf(ficresprobcor, "\n#********** Variable ");
3804: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3805: fprintf(ficresprobcor, "**********\n#");
3806: }
3807:
3808: gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
3809: trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3810: gp=vector(1,(nlstate)*(nlstate+ndeath));
3811: gm=vector(1,(nlstate)*(nlstate+ndeath));
3812: for (age=bage; age<=fage; age ++){
3813: cov[2]=age;
3814: for (k=1; k<=cptcovn;k++) {
3815: cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
3816: * 1 1 1 1 1
3817: * 2 2 1 1 1
3818: * 3 1 2 1 1
3819: */
3820: /* nbcode[1][1]=0 nbcode[1][2]=1;*/
3821: }
3822: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
3823: for (k=1; k<=cptcovprod;k++)
3824: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
3825:
3826:
3827: for(theta=1; theta <=npar; theta++){
3828: for(i=1; i<=npar; i++)
3829: xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
3830:
3831: pmij(pmmij,cov,ncovmodel,xp,nlstate);
3832:
3833: k=0;
3834: for(i=1; i<= (nlstate); i++){
3835: for(j=1; j<=(nlstate+ndeath);j++){
3836: k=k+1;
3837: gp[k]=pmmij[i][j];
3838: }
3839: }
3840:
3841: for(i=1; i<=npar; i++)
3842: xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
3843:
3844: pmij(pmmij,cov,ncovmodel,xp,nlstate);
3845: k=0;
3846: for(i=1; i<=(nlstate); i++){
3847: for(j=1; j<=(nlstate+ndeath);j++){
3848: k=k+1;
3849: gm[k]=pmmij[i][j];
3850: }
3851: }
3852:
3853: for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
3854: gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];
3855: }
3856:
3857: for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
3858: for(theta=1; theta <=npar; theta++)
3859: trgradg[j][theta]=gradg[theta][j];
3860:
3861: matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
3862: matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
3863:
3864: pmij(pmmij,cov,ncovmodel,x,nlstate);
3865:
3866: k=0;
3867: for(i=1; i<=(nlstate); i++){
3868: for(j=1; j<=(nlstate+ndeath);j++){
3869: k=k+1;
3870: mu[k][(int) age]=pmmij[i][j];
3871: }
3872: }
3873: for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
3874: for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
3875: varpij[i][j][(int)age] = doldm[i][j];
3876:
3877: /*printf("\n%d ",(int)age);
3878: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
3879: printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
3880: fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
3881: }*/
3882:
3883: fprintf(ficresprob,"\n%d ",(int)age);
3884: fprintf(ficresprobcov,"\n%d ",(int)age);
3885: fprintf(ficresprobcor,"\n%d ",(int)age);
3886:
3887: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
3888: fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
3889: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
3890: fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
3891: fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
3892: }
3893: i=0;
3894: for (k=1; k<=(nlstate);k++){
3895: for (l=1; l<=(nlstate+ndeath);l++){
3896: i++;
3897: fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
3898: fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
3899: for (j=1; j<=i;j++){
3900: /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
3901: fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
3902: fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
3903: }
3904: }
3905: }/* end of loop for state */
3906: } /* end of loop for age */
3907: free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
3908: free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
3909: free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
3910: free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
3911:
3912: /* Confidence intervalle of pij */
3913: /*
3914: fprintf(ficgp,"\nunset parametric;unset label");
3915: fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
3916: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
3917: 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);
3918: fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
3919: fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
3920: fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
3921: */
3922:
3923: /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
3924: first1=1;first2=2;
3925: for (k2=1; k2<=(nlstate);k2++){
3926: for (l2=1; l2<=(nlstate+ndeath);l2++){
3927: if(l2==k2) continue;
3928: j=(k2-1)*(nlstate+ndeath)+l2;
3929: for (k1=1; k1<=(nlstate);k1++){
3930: for (l1=1; l1<=(nlstate+ndeath);l1++){
3931: if(l1==k1) continue;
3932: i=(k1-1)*(nlstate+ndeath)+l1;
3933: if(i<=j) continue;
3934: for (age=bage; age<=fage; age ++){
3935: if ((int)age %5==0){
3936: v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
3937: v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
3938: cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
3939: mu1=mu[i][(int) age]/stepm*YEARM ;
3940: mu2=mu[j][(int) age]/stepm*YEARM;
3941: c12=cv12/sqrt(v1*v2);
3942: /* Computing eigen value of matrix of covariance */
3943: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
3944: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
3945: if ((lc2 <0) || (lc1 <0) ){
3946: if(first2==1){
3947: first1=0;
3948: 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);
3949: }
3950: 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);
3951: /* lc1=fabs(lc1); */ /* If we want to have them positive */
3952: /* lc2=fabs(lc2); */
3953: }
3954:
3955: /* Eigen vectors */
3956: v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
3957: /*v21=sqrt(1.-v11*v11); *//* error */
3958: v21=(lc1-v1)/cv12*v11;
3959: v12=-v21;
3960: v22=v11;
3961: tnalp=v21/v11;
3962: if(first1==1){
3963: first1=0;
3964: 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);
3965: }
3966: 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);
3967: /*printf(fignu*/
3968: /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
3969: /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
3970: if(first==1){
3971: first=0;
3972: fprintf(ficgp,"\nset parametric;unset label");
3973: 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);
3974: fprintf(ficgp,"\nset ter png small size 320, 240");
3975: fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
3976: :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
3977: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
3978: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
3979: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
3980: fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
3981: fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
3982: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
3983: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
3984: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
3985: 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",\
3986: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
3987: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
3988: }else{
3989: first=0;
3990: fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
3991: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
3992: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
3993: 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",\
3994: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
3995: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
3996: }/* if first */
3997: } /* age mod 5 */
3998: } /* end loop age */
3999: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4000: first=1;
4001: } /*l12 */
4002: } /* k12 */
4003: } /*l1 */
4004: }/* k1 */
4005: /* } /* loop covariates */
4006: }
4007: free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
4008: free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
4009: free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4010: free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
4011: free_vector(xp,1,npar);
4012: fclose(ficresprob);
4013: fclose(ficresprobcov);
4014: fclose(ficresprobcor);
4015: fflush(ficgp);
4016: fflush(fichtmcov);
4017: }
4018:
4019:
4020: /******************* Printing html file ***********/
4021: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
4022: int lastpass, int stepm, int weightopt, char model[],\
4023: int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
4024: int popforecast, int estepm ,\
4025: double jprev1, double mprev1,double anprev1, \
4026: double jprev2, double mprev2,double anprev2){
4027: int jj1, k1, i1, cpt;
4028:
4029: fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
4030: <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
4031: </ul>");
4032: fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
4033: - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
4034: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
4035: fprintf(fichtm,"\
4036: - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
4037: stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
4038: fprintf(fichtm,"\
4039: - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
4040: subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
4041: fprintf(fichtm,"\
4042: - (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): \
4043: <a href=\"%s\">%s</a> <br>\n",
4044: estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
4045: fprintf(fichtm,"\
4046: - Population projections by age and states: \
4047: <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
4048:
4049: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
4050:
4051: m=pow(2,cptcoveff);
4052: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4053:
4054: jj1=0;
4055: for(k1=1; k1<=m;k1++){
4056: for(i1=1; i1<=ncodemax[k1];i1++){
4057: jj1++;
4058: if (cptcovn > 0) {
4059: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4060: for (cpt=1; cpt<=cptcoveff;cpt++)
4061: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4062: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4063: }
4064: /* Pij */
4065: 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> \
4066: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
4067: /* Quasi-incidences */
4068: fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
4069: 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> \
4070: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
4071: /* Period (stable) prevalence in each health state */
4072: for(cpt=1; cpt<=nlstate;cpt++){
4073: 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> \
4074: <img src=\"%s%d_%d.png\">",nlstate, cpt, subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
4075: }
4076: for(cpt=1; cpt<=nlstate;cpt++) {
4077: 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> \
4078: <img src=\"%s%d%d.png\">",cpt,nlstate,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
4079: }
4080: } /* end i1 */
4081: }/* End k1 */
4082: fprintf(fichtm,"</ul>");
4083:
4084:
4085: fprintf(fichtm,"\
4086: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
4087: - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
4088:
4089: fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4090: subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
4091: fprintf(fichtm,"\
4092: - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4093: subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
4094:
4095: fprintf(fichtm,"\
4096: - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4097: subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
4098: fprintf(fichtm,"\
4099: - 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): \
4100: <a href=\"%s\">%s</a> <br>\n</li>",
4101: estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
4102: fprintf(fichtm,"\
4103: - (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): \
4104: <a href=\"%s\">%s</a> <br>\n</li>",
4105: estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
4106: fprintf(fichtm,"\
4107: - 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",
4108: estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
4109: fprintf(fichtm,"\
4110: - 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",
4111: estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
4112: fprintf(fichtm,"\
4113: - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
4114: subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
4115:
4116: /* if(popforecast==1) fprintf(fichtm,"\n */
4117: /* - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
4118: /* - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
4119: /* <br>",fileres,fileres,fileres,fileres); */
4120: /* else */
4121: /* 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); */
4122: fflush(fichtm);
4123: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
4124:
4125: m=pow(2,cptcoveff);
4126: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4127:
4128: jj1=0;
4129: for(k1=1; k1<=m;k1++){
4130: for(i1=1; i1<=ncodemax[k1];i1++){
4131: jj1++;
4132: if (cptcovn > 0) {
4133: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4134: for (cpt=1; cpt<=cptcoveff;cpt++)
4135: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4136: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4137: }
4138: for(cpt=1; cpt<=nlstate;cpt++) {
4139: fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
4140: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
4141: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);
4142: }
4143: fprintf(fichtm,"\n<br>- Total life expectancy by age and \
4144: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
4145: true period expectancies (those weighted with period prevalences are also\
4146: drawn in addition to the population based expectancies computed using\
4147: observed and cahotic prevalences: %s%d.png<br>\
4148: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
4149: } /* end i1 */
4150: }/* End k1 */
4151: fprintf(fichtm,"</ul>");
4152: fflush(fichtm);
4153: }
4154:
4155: /******************* Gnuplot file **************/
4156: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4157:
4158: char dirfileres[132],optfileres[132];
4159: int m0,cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
4160: int ng=0;
4161: /* if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
4162: /* printf("Problem with file %s",optionfilegnuplot); */
4163: /* fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
4164: /* } */
4165:
4166: /*#ifdef windows */
4167: fprintf(ficgp,"cd \"%s\" \n",pathc);
4168: /*#endif */
4169: m=pow(2,cptcoveff);
4170:
4171: strcpy(dirfileres,optionfilefiname);
4172: strcpy(optfileres,"vpl");
4173: /* 1eme*/
4174: fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
4175: for (cpt=1; cpt<= nlstate ; cpt ++) {
4176: for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
4177: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
4178: fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
4179: fprintf(ficgp,"set xlabel \"Age\" \n\
4180: set ylabel \"Probability\" \n\
4181: set ter png small size 320, 240\n\
4182: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
4183:
4184: for (i=1; i<= nlstate ; i ++) {
4185: if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
4186: else fprintf(ficgp," \%%*lf (\%%*lf)");
4187: }
4188: 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);
4189: for (i=1; i<= nlstate ; i ++) {
4190: if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
4191: else fprintf(ficgp," \%%*lf (\%%*lf)");
4192: }
4193: 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);
4194: for (i=1; i<= nlstate ; i ++) {
4195: if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
4196: else fprintf(ficgp," \%%*lf (\%%*lf)");
4197: }
4198: 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));
4199: }
4200: }
4201: /*2 eme*/
4202: fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
4203: for (k1=1; k1<= m ; k1 ++) {
4204: fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
4205: fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
4206:
4207: for (i=1; i<= nlstate+1 ; i ++) {
4208: k=2*i;
4209: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4210: for (j=1; j<= nlstate+1 ; j ++) {
4211: if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
4212: else fprintf(ficgp," \%%*lf (\%%*lf)");
4213: }
4214: if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
4215: else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
4216: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4217: for (j=1; j<= nlstate+1 ; j ++) {
4218: if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
4219: else fprintf(ficgp," \%%*lf (\%%*lf)");
4220: }
4221: fprintf(ficgp,"\" t\"\" w l lt 0,");
4222: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4223: for (j=1; j<= nlstate+1 ; j ++) {
4224: if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
4225: else fprintf(ficgp," \%%*lf (\%%*lf)");
4226: }
4227: if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
4228: else fprintf(ficgp,"\" t\"\" w l lt 0,");
4229: }
4230: }
4231:
4232: /*3eme*/
4233:
4234: for (k1=1; k1<= m ; k1 ++) {
4235: for (cpt=1; cpt<= nlstate ; cpt ++) {
4236: /* k=2+nlstate*(2*cpt-2); */
4237: k=2+(nlstate+1)*(cpt-1);
4238: fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
4239: fprintf(ficgp,"set ter png small size 320, 240\n\
4240: 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);
4241: /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4242: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4243: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4244: fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4245: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4246: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4247:
4248: */
4249: for (i=1; i< nlstate ; i ++) {
4250: 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);
4251: /* 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);*/
4252:
4253: }
4254: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
4255: }
4256: }
4257:
4258: /* CV preval stable (period) */
4259: for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
4260: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
4261: k=3;
4262: fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
4263: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
4264: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
4265: set ter png small size 320, 240\n\
4266: unset log y\n\
4267: plot [%.f:%.f] ", ageminpar, agemaxpar);
4268: for (i=1; i<= nlstate ; i ++){
4269: if(i==1)
4270: fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
4271: else
4272: fprintf(ficgp,", '' ");
4273: l=(nlstate+ndeath)*(i-1)+1;
4274: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
4275: for (j=1; j<= (nlstate-1) ; j ++)
4276: fprintf(ficgp,"+$%d",k+l+j);
4277: fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
4278: } /* nlstate */
4279: fprintf(ficgp,"\n");
4280: } /* end cpt state*/
4281: } /* end covariate */
4282:
4283: /* proba elementaires */
4284: for(i=1,jk=1; i <=nlstate; i++){
4285: for(k=1; k <=(nlstate+ndeath); k++){
4286: if (k != i) {
4287: for(j=1; j <=ncovmodel; j++){
4288: fprintf(ficgp,"p%d=%f ",jk,p[jk]);
4289: jk++;
4290: fprintf(ficgp,"\n");
4291: }
4292: }
4293: }
4294: }
4295: /*goto avoid;*/
4296: for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
4297: for(jk=1; jk <=m; jk++) {
4298: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);
4299: if (ng==2)
4300: fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
4301: else
4302: fprintf(ficgp,"\nset title \"Probability\"\n");
4303: fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot [%.f:%.f] ",ageminpar,agemaxpar);
4304: i=1;
4305: for(k2=1; k2<=nlstate; k2++) {
4306: k3=i;
4307: for(k=1; k<=(nlstate+ndeath); k++) {
4308: if (k != k2){
4309: if(ng==2)
4310: fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
4311: else
4312: fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
4313: ij=1;/* To be checked else nbcode[0][0] wrong */
4314: for(j=3; j <=ncovmodel; j++) {
4315: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /\* Bug valgrind *\/ */
4316: /* /\*fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);*\/ */
4317: /* ij++; */
4318: /* } */
4319: /* else */
4320: fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4321: }
4322: fprintf(ficgp,")/(1");
4323:
4324: for(k1=1; k1 <=nlstate; k1++){
4325: fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
4326: ij=1;
4327: for(j=3; j <=ncovmodel; j++){
4328: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { */
4329: /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]); */
4330: /* ij++; */
4331: /* } */
4332: /* else */
4333: fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4334: }
4335: fprintf(ficgp,")");
4336: }
4337: fprintf(ficgp,") t \"p%d%d\" ", k2,k);
4338: if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
4339: i=i+ncovmodel;
4340: }
4341: } /* end k */
4342: } /* end k2 */
4343: } /* end jk */
4344: } /* end ng */
4345: avoid:
4346: fflush(ficgp);
4347: } /* end gnuplot */
4348:
4349:
4350: /*************** Moving average **************/
4351: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
4352:
4353: int i, cpt, cptcod;
4354: int modcovmax =1;
4355: int mobilavrange, mob;
4356: double age;
4357:
4358: modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
4359: a covariate has 2 modalities */
4360: if (cptcovn<1) modcovmax=1; /* At least 1 pass */
4361:
4362: if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
4363: if(mobilav==1) mobilavrange=5; /* default */
4364: else mobilavrange=mobilav;
4365: for (age=bage; age<=fage; age++)
4366: for (i=1; i<=nlstate;i++)
4367: for (cptcod=1;cptcod<=modcovmax;cptcod++)
4368: mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
4369: /* We keep the original values on the extreme ages bage, fage and for
4370: fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
4371: we use a 5 terms etc. until the borders are no more concerned.
4372: */
4373: for (mob=3;mob <=mobilavrange;mob=mob+2){
4374: for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
4375: for (i=1; i<=nlstate;i++){
4376: for (cptcod=1;cptcod<=modcovmax;cptcod++){
4377: mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
4378: for (cpt=1;cpt<=(mob-1)/2;cpt++){
4379: mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
4380: mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
4381: }
4382: mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
4383: }
4384: }
4385: }/* end age */
4386: }/* end mob */
4387: }else return -1;
4388: return 0;
4389: }/* End movingaverage */
4390:
4391:
4392: /************** Forecasting ******************/
4393: 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){
4394: /* proj1, year, month, day of starting projection
4395: agemin, agemax range of age
4396: dateprev1 dateprev2 range of dates during which prevalence is computed
4397: anproj2 year of en of projection (same day and month as proj1).
4398: */
4399: int yearp, stepsize, hstepm, nhstepm, j, k, c, cptcod, i, h, i1;
4400: int *popage;
4401: double agec; /* generic age */
4402: double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
4403: double *popeffectif,*popcount;
4404: double ***p3mat;
4405: double ***mobaverage;
4406: char fileresf[FILENAMELENGTH];
4407:
4408: agelim=AGESUP;
4409: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4410:
4411: strcpy(fileresf,"f");
4412: strcat(fileresf,fileres);
4413: if((ficresf=fopen(fileresf,"w"))==NULL) {
4414: printf("Problem with forecast resultfile: %s\n", fileresf);
4415: fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
4416: }
4417: printf("Computing forecasting: result on file '%s' \n", fileresf);
4418: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
4419:
4420: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4421:
4422: if (mobilav!=0) {
4423: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4424: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4425: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4426: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4427: }
4428: }
4429:
4430: stepsize=(int) (stepm+YEARM-1)/YEARM;
4431: if (stepm<=12) stepsize=1;
4432: if(estepm < stepm){
4433: printf ("Problem %d lower than %d\n",estepm, stepm);
4434: }
4435: else hstepm=estepm;
4436:
4437: hstepm=hstepm/stepm;
4438: yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp and
4439: fractional in yp1 */
4440: anprojmean=yp;
4441: yp2=modf((yp1*12),&yp);
4442: mprojmean=yp;
4443: yp1=modf((yp2*30.5),&yp);
4444: jprojmean=yp;
4445: if(jprojmean==0) jprojmean=1;
4446: if(mprojmean==0) jprojmean=1;
4447:
4448: i1=cptcoveff;
4449: if (cptcovn < 1){i1=1;}
4450:
4451: fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
4452:
4453: fprintf(ficresf,"#****** Routine prevforecast **\n");
4454:
4455: /* if (h==(int)(YEARM*yearp)){ */
4456: for(cptcov=1, k=0;cptcov<=i1;cptcov++){
4457: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4458: k=k+1;
4459: fprintf(ficresf,"\n#******");
4460: for(j=1;j<=cptcoveff;j++) {
4461: 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]]);
4462: }
4463: fprintf(ficresf,"******\n");
4464: fprintf(ficresf,"# Covariate valuofcovar yearproj age");
4465: for(j=1; j<=nlstate+ndeath;j++){
4466: for(i=1; i<=nlstate;i++)
4467: fprintf(ficresf," p%d%d",i,j);
4468: fprintf(ficresf," p.%d",j);
4469: }
4470: for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
4471: fprintf(ficresf,"\n");
4472: fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);
4473:
4474: for (agec=fage; agec>=(ageminpar-1); agec--){
4475: nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
4476: nhstepm = nhstepm/hstepm;
4477: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4478: oldm=oldms;savm=savms;
4479: hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
4480:
4481: for (h=0; h<=nhstepm; h++){
4482: if (h*hstepm/YEARM*stepm ==yearp) {
4483: fprintf(ficresf,"\n");
4484: for(j=1;j<=cptcoveff;j++)
4485: fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4486: fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
4487: }
4488: for(j=1; j<=nlstate+ndeath;j++) {
4489: ppij=0.;
4490: for(i=1; i<=nlstate;i++) {
4491: if (mobilav==1)
4492: ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
4493: else {
4494: ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
4495: }
4496: if (h*hstepm/YEARM*stepm== yearp) {
4497: fprintf(ficresf," %.3f", p3mat[i][j][h]);
4498: }
4499: } /* end i */
4500: if (h*hstepm/YEARM*stepm==yearp) {
4501: fprintf(ficresf," %.3f", ppij);
4502: }
4503: }/* end j */
4504: } /* end h */
4505: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4506: } /* end agec */
4507: } /* end yearp */
4508: } /* end cptcod */
4509: } /* end cptcov */
4510:
4511: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4512:
4513: fclose(ficresf);
4514: }
4515:
4516: /************** Forecasting *****not tested NB*************/
4517: 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){
4518:
4519: int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
4520: int *popage;
4521: double calagedatem, agelim, kk1, kk2;
4522: double *popeffectif,*popcount;
4523: double ***p3mat,***tabpop,***tabpopprev;
4524: double ***mobaverage;
4525: char filerespop[FILENAMELENGTH];
4526:
4527: tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4528: tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4529: agelim=AGESUP;
4530: calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
4531:
4532: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4533:
4534:
4535: strcpy(filerespop,"pop");
4536: strcat(filerespop,fileres);
4537: if((ficrespop=fopen(filerespop,"w"))==NULL) {
4538: printf("Problem with forecast resultfile: %s\n", filerespop);
4539: fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
4540: }
4541: printf("Computing forecasting: result on file '%s' \n", filerespop);
4542: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
4543:
4544: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4545:
4546: if (mobilav!=0) {
4547: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4548: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4549: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4550: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4551: }
4552: }
4553:
4554: stepsize=(int) (stepm+YEARM-1)/YEARM;
4555: if (stepm<=12) stepsize=1;
4556:
4557: agelim=AGESUP;
4558:
4559: hstepm=1;
4560: hstepm=hstepm/stepm;
4561:
4562: if (popforecast==1) {
4563: if((ficpop=fopen(popfile,"r"))==NULL) {
4564: printf("Problem with population file : %s\n",popfile);exit(0);
4565: fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
4566: }
4567: popage=ivector(0,AGESUP);
4568: popeffectif=vector(0,AGESUP);
4569: popcount=vector(0,AGESUP);
4570:
4571: i=1;
4572: while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
4573:
4574: imx=i;
4575: for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
4576: }
4577:
4578: for(cptcov=1,k=0;cptcov<=i2;cptcov++){
4579: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4580: k=k+1;
4581: fprintf(ficrespop,"\n#******");
4582: for(j=1;j<=cptcoveff;j++) {
4583: fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4584: }
4585: fprintf(ficrespop,"******\n");
4586: fprintf(ficrespop,"# Age");
4587: for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
4588: if (popforecast==1) fprintf(ficrespop," [Population]");
4589:
4590: for (cpt=0; cpt<=0;cpt++) {
4591: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4592:
4593: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4594: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4595: nhstepm = nhstepm/hstepm;
4596:
4597: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4598: oldm=oldms;savm=savms;
4599: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4600:
4601: for (h=0; h<=nhstepm; h++){
4602: if (h==(int) (calagedatem+YEARM*cpt)) {
4603: fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4604: }
4605: for(j=1; j<=nlstate+ndeath;j++) {
4606: kk1=0.;kk2=0;
4607: for(i=1; i<=nlstate;i++) {
4608: if (mobilav==1)
4609: kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
4610: else {
4611: kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
4612: }
4613: }
4614: if (h==(int)(calagedatem+12*cpt)){
4615: tabpop[(int)(agedeb)][j][cptcod]=kk1;
4616: /*fprintf(ficrespop," %.3f", kk1);
4617: if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
4618: }
4619: }
4620: for(i=1; i<=nlstate;i++){
4621: kk1=0.;
4622: for(j=1; j<=nlstate;j++){
4623: kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
4624: }
4625: tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
4626: }
4627:
4628: if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
4629: fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
4630: }
4631: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4632: }
4633: }
4634:
4635: /******/
4636:
4637: for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
4638: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4639: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4640: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4641: nhstepm = nhstepm/hstepm;
4642:
4643: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4644: oldm=oldms;savm=savms;
4645: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4646: for (h=0; h<=nhstepm; h++){
4647: if (h==(int) (calagedatem+YEARM*cpt)) {
4648: fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4649: }
4650: for(j=1; j<=nlstate+ndeath;j++) {
4651: kk1=0.;kk2=0;
4652: for(i=1; i<=nlstate;i++) {
4653: kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];
4654: }
4655: if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);
4656: }
4657: }
4658: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4659: }
4660: }
4661: }
4662: }
4663:
4664: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4665:
4666: if (popforecast==1) {
4667: free_ivector(popage,0,AGESUP);
4668: free_vector(popeffectif,0,AGESUP);
4669: free_vector(popcount,0,AGESUP);
4670: }
4671: free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4672: free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4673: fclose(ficrespop);
4674: } /* End of popforecast */
4675:
4676: int fileappend(FILE *fichier, char *optionfich)
4677: {
4678: if((fichier=fopen(optionfich,"a"))==NULL) {
4679: printf("Problem with file: %s\n", optionfich);
4680: fprintf(ficlog,"Problem with file: %s\n", optionfich);
4681: return (0);
4682: }
4683: fflush(fichier);
4684: return (1);
4685: }
4686:
4687:
4688: /**************** function prwizard **********************/
4689: void prwizard(int ncovmodel, int nlstate, int ndeath, char model[], FILE *ficparo)
4690: {
4691:
4692: /* Wizard to print covariance matrix template */
4693:
4694: char ca[32], cb[32], cc[32];
4695: int i,j, k, l, li, lj, lk, ll, jj, npar, itimes;
4696: int numlinepar;
4697:
4698: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4699: fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4700: for(i=1; i <=nlstate; i++){
4701: jj=0;
4702: for(j=1; j <=nlstate+ndeath; j++){
4703: if(j==i) continue;
4704: jj++;
4705: /*ca[0]= k+'a'-1;ca[1]='\0';*/
4706: printf("%1d%1d",i,j);
4707: fprintf(ficparo,"%1d%1d",i,j);
4708: for(k=1; k<=ncovmodel;k++){
4709: /* printf(" %lf",param[i][j][k]); */
4710: /* fprintf(ficparo," %lf",param[i][j][k]); */
4711: printf(" 0.");
4712: fprintf(ficparo," 0.");
4713: }
4714: printf("\n");
4715: fprintf(ficparo,"\n");
4716: }
4717: }
4718: printf("# Scales (for hessian or gradient estimation)\n");
4719: fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
4720: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
4721: for(i=1; i <=nlstate; i++){
4722: jj=0;
4723: for(j=1; j <=nlstate+ndeath; j++){
4724: if(j==i) continue;
4725: jj++;
4726: fprintf(ficparo,"%1d%1d",i,j);
4727: printf("%1d%1d",i,j);
4728: fflush(stdout);
4729: for(k=1; k<=ncovmodel;k++){
4730: /* printf(" %le",delti3[i][j][k]); */
4731: /* fprintf(ficparo," %le",delti3[i][j][k]); */
4732: printf(" 0.");
4733: fprintf(ficparo," 0.");
4734: }
4735: numlinepar++;
4736: printf("\n");
4737: fprintf(ficparo,"\n");
4738: }
4739: }
4740: printf("# Covariance matrix\n");
4741: /* # 121 Var(a12)\n\ */
4742: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4743: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
4744: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
4745: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
4746: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
4747: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
4748: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4749: fflush(stdout);
4750: fprintf(ficparo,"# Covariance matrix\n");
4751: /* # 121 Var(a12)\n\ */
4752: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4753: /* # ...\n\ */
4754: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4755:
4756: for(itimes=1;itimes<=2;itimes++){
4757: jj=0;
4758: for(i=1; i <=nlstate; i++){
4759: for(j=1; j <=nlstate+ndeath; j++){
4760: if(j==i) continue;
4761: for(k=1; k<=ncovmodel;k++){
4762: jj++;
4763: ca[0]= k+'a'-1;ca[1]='\0';
4764: if(itimes==1){
4765: printf("#%1d%1d%d",i,j,k);
4766: fprintf(ficparo,"#%1d%1d%d",i,j,k);
4767: }else{
4768: printf("%1d%1d%d",i,j,k);
4769: fprintf(ficparo,"%1d%1d%d",i,j,k);
4770: /* printf(" %.5le",matcov[i][j]); */
4771: }
4772: ll=0;
4773: for(li=1;li <=nlstate; li++){
4774: for(lj=1;lj <=nlstate+ndeath; lj++){
4775: if(lj==li) continue;
4776: for(lk=1;lk<=ncovmodel;lk++){
4777: ll++;
4778: if(ll<=jj){
4779: cb[0]= lk +'a'-1;cb[1]='\0';
4780: if(ll<jj){
4781: if(itimes==1){
4782: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4783: fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4784: }else{
4785: printf(" 0.");
4786: fprintf(ficparo," 0.");
4787: }
4788: }else{
4789: if(itimes==1){
4790: printf(" Var(%s%1d%1d)",ca,i,j);
4791: fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
4792: }else{
4793: printf(" 0.");
4794: fprintf(ficparo," 0.");
4795: }
4796: }
4797: }
4798: } /* end lk */
4799: } /* end lj */
4800: } /* end li */
4801: printf("\n");
4802: fprintf(ficparo,"\n");
4803: numlinepar++;
4804: } /* end k*/
4805: } /*end j */
4806: } /* end i */
4807: } /* end itimes */
4808:
4809: } /* end of prwizard */
4810: /******************* Gompertz Likelihood ******************************/
4811: double gompertz(double x[])
4812: {
4813: double A,B,L=0.0,sump=0.,num=0.;
4814: int i,n=0; /* n is the size of the sample */
4815:
4816: for (i=0;i<=imx-1 ; i++) {
4817: sump=sump+weight[i];
4818: /* sump=sump+1;*/
4819: num=num+1;
4820: }
4821:
4822:
4823: /* for (i=0; i<=imx; i++)
4824: 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]);*/
4825:
4826: for (i=1;i<=imx ; i++)
4827: {
4828: if (cens[i] == 1 && wav[i]>1)
4829: A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
4830:
4831: if (cens[i] == 0 && wav[i]>1)
4832: A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
4833: +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);
4834:
4835: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
4836: if (wav[i] > 1 ) { /* ??? */
4837: L=L+A*weight[i];
4838: /* 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]);*/
4839: }
4840: }
4841:
4842: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
4843:
4844: return -2*L*num/sump;
4845: }
4846:
4847: #ifdef GSL
4848: /******************* Gompertz_f Likelihood ******************************/
4849: double gompertz_f(const gsl_vector *v, void *params)
4850: {
4851: double A,B,LL=0.0,sump=0.,num=0.;
4852: double *x= (double *) v->data;
4853: int i,n=0; /* n is the size of the sample */
4854:
4855: for (i=0;i<=imx-1 ; i++) {
4856: sump=sump+weight[i];
4857: /* sump=sump+1;*/
4858: num=num+1;
4859: }
4860:
4861:
4862: /* for (i=0; i<=imx; i++)
4863: 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]);*/
4864: printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
4865: for (i=1;i<=imx ; i++)
4866: {
4867: if (cens[i] == 1 && wav[i]>1)
4868: A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
4869:
4870: if (cens[i] == 0 && wav[i]>1)
4871: A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
4872: +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);
4873:
4874: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
4875: if (wav[i] > 1 ) { /* ??? */
4876: LL=LL+A*weight[i];
4877: /* 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]);*/
4878: }
4879: }
4880:
4881: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
4882: printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
4883:
4884: return -2*LL*num/sump;
4885: }
4886: #endif
4887:
4888: /******************* Printing html file ***********/
4889: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
4890: int lastpass, int stepm, int weightopt, char model[],\
4891: int imx, double p[],double **matcov,double agemortsup){
4892: int i,k;
4893:
4894: fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
4895: fprintf(fichtm," mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
4896: for (i=1;i<=2;i++)
4897: 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]));
4898: fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
4899: fprintf(fichtm,"</ul>");
4900:
4901: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
4902:
4903: 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>");
4904:
4905: for (k=agegomp;k<(agemortsup-2);k++)
4906: 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]);
4907:
4908:
4909: fflush(fichtm);
4910: }
4911:
4912: /******************* Gnuplot file **************/
4913: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4914:
4915: char dirfileres[132],optfileres[132];
4916: int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;
4917: int ng;
4918:
4919:
4920: /*#ifdef windows */
4921: fprintf(ficgp,"cd \"%s\" \n",pathc);
4922: /*#endif */
4923:
4924:
4925: strcpy(dirfileres,optionfilefiname);
4926: strcpy(optfileres,"vpl");
4927: fprintf(ficgp,"set out \"graphmort.png\"\n ");
4928: fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
4929: fprintf(ficgp, "set ter png small size 320, 240\n set log y\n");
4930: /* fprintf(ficgp, "set size 0.65,0.65\n"); */
4931: fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
4932:
4933: }
4934:
4935: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
4936: {
4937:
4938: /*-------- data file ----------*/
4939: FILE *fic;
4940: char dummy[]=" ";
4941: int i, j, n;
4942: int linei, month, year,iout;
4943: char line[MAXLINE], linetmp[MAXLINE];
4944: char stra[80], strb[80];
4945: char *stratrunc;
4946: int lstra;
4947:
4948:
4949: if((fic=fopen(datafile,"r"))==NULL) {
4950: printf("Problem while opening datafile: %s\n", datafile);return 1;
4951: fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
4952: }
4953:
4954: i=1;
4955: linei=0;
4956: while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
4957: linei=linei+1;
4958: for(j=strlen(line); j>=0;j--){ /* Untabifies line */
4959: if(line[j] == '\t')
4960: line[j] = ' ';
4961: }
4962: for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
4963: ;
4964: };
4965: line[j+1]=0; /* Trims blanks at end of line */
4966: if(line[0]=='#'){
4967: fprintf(ficlog,"Comment line\n%s\n",line);
4968: printf("Comment line\n%s\n",line);
4969: continue;
4970: }
4971: trimbb(linetmp,line); /* Trims multiple blanks in line */
4972: for (j=0; line[j]!='\0';j++){
4973: line[j]=linetmp[j];
4974: }
4975:
4976:
4977: for (j=maxwav;j>=1;j--){
4978: cutv(stra, strb, line, ' ');
4979: if(strb[0]=='.') { /* Missing status */
4980: lval=-1;
4981: }else{
4982: errno=0;
4983: lval=strtol(strb,&endptr,10);
4984: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
4985: if( strb[0]=='\0' || (*endptr != '\0')){
4986: 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);
4987: 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);
4988: return 1;
4989: }
4990: }
4991: s[j][i]=lval;
4992:
4993: strcpy(line,stra);
4994: cutv(stra, strb,line,' ');
4995: if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
4996: }
4997: else if(iout=sscanf(strb,"%s.",dummy) != 0){
4998: month=99;
4999: year=9999;
5000: }else{
5001: 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);
5002: 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);
5003: return 1;
5004: }
5005: anint[j][i]= (double) year;
5006: mint[j][i]= (double)month;
5007: strcpy(line,stra);
5008: } /* ENd Waves */
5009:
5010: cutv(stra, strb,line,' ');
5011: if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
5012: }
5013: else if(iout=sscanf(strb,"%s.",dummy) != 0){
5014: month=99;
5015: year=9999;
5016: }else{
5017: 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);
5018: 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);
5019: return 1;
5020: }
5021: andc[i]=(double) year;
5022: moisdc[i]=(double) month;
5023: strcpy(line,stra);
5024:
5025: cutv(stra, strb,line,' ');
5026: if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
5027: }
5028: else if(iout=sscanf(strb,"%s.", dummy) != 0){
5029: month=99;
5030: year=9999;
5031: }else{
5032: 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);
5033: 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);
5034: return 1;
5035: }
5036: if (year==9999) {
5037: 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);
5038: 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);
5039: return 1;
5040:
5041: }
5042: annais[i]=(double)(year);
5043: moisnais[i]=(double)(month);
5044: strcpy(line,stra);
5045:
5046: cutv(stra, strb,line,' ');
5047: errno=0;
5048: dval=strtod(strb,&endptr);
5049: if( strb[0]=='\0' || (*endptr != '\0')){
5050: printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight. Exiting.\n",dval, i,line,linei);
5051: 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);
5052: fflush(ficlog);
5053: return 1;
5054: }
5055: weight[i]=dval;
5056: strcpy(line,stra);
5057:
5058: for (j=ncovcol;j>=1;j--){
5059: cutv(stra, strb,line,' ');
5060: if(strb[0]=='.') { /* Missing status */
5061: lval=-1;
5062: }else{
5063: errno=0;
5064: lval=strtol(strb,&endptr,10);
5065: if( strb[0]=='\0' || (*endptr != '\0')){
5066: 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);
5067: 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);
5068: return 1;
5069: }
5070: }
5071: if(lval <-1 || lval >1){
5072: printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
5073: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5074: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5075: For example, for multinomial values like 1, 2 and 3,\n \
5076: build V1=0 V2=0 for the reference value (1),\n \
5077: V1=1 V2=0 for (2) \n \
5078: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5079: output of IMaCh is often meaningless.\n \
5080: Exiting.\n",lval,linei, i,line,j);
5081: fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
5082: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5083: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5084: For example, for multinomial values like 1, 2 and 3,\n \
5085: build V1=0 V2=0 for the reference value (1),\n \
5086: V1=1 V2=0 for (2) \n \
5087: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5088: output of IMaCh is often meaningless.\n \
5089: Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
5090: return 1;
5091: }
5092: covar[j][i]=(double)(lval);
5093: strcpy(line,stra);
5094: }
5095: lstra=strlen(stra);
5096:
5097: if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
5098: stratrunc = &(stra[lstra-9]);
5099: num[i]=atol(stratrunc);
5100: }
5101: else
5102: num[i]=atol(stra);
5103: /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
5104: 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;}*/
5105:
5106: i=i+1;
5107: } /* End loop reading data */
5108:
5109: *imax=i-1; /* Number of individuals */
5110: fclose(fic);
5111:
5112: return (0);
5113: endread:
5114: printf("Exiting readdata: ");
5115: fclose(fic);
5116: return (1);
5117:
5118:
5119:
5120: }
5121: void removespace(char *str) {
5122: char *p1 = str, *p2 = str;
5123: do
5124: while (*p2 == ' ')
5125: p2++;
5126: while (*p1++ = *p2++);
5127: }
5128:
5129: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
5130: * Model V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age
5131: * - cptcovt total number of covariates of the model nbocc(+)+1 = 8
5132: * - cptcovn or number of covariates k of the models excluding age*products =6
5133: * - cptcovage number of covariates with age*products =2
5134: * - cptcovs number of simple covariates
5135: * - 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
5136: * which is a new column after the 9 (ncovcol) variables.
5137: * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
5138: * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
5139: * Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
5140: * - Tvard[k] p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
5141: */
5142: {
5143: int i, j, k, ks;
5144: int i1, j1, k1, k2;
5145: char modelsav[80];
5146: char stra[80], strb[80], strc[80], strd[80],stre[80];
5147:
5148: /*removespace(model);*/
5149: if (strlen(model) >1){ /* If there is at least 1 covariate */
5150: j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
5151: j=nbocc(model,'+'); /**< j=Number of '+' */
5152: j1=nbocc(model,'*'); /**< j1=Number of '*' */
5153: cptcovs=j+1-j1; /**< Number of simple covariates V1+V2*age+V3 +V3*V4=> V1 + V3 =2 */
5154: cptcovt= j+1; /* Number of total covariates in the model V1 + V2*age+ V3 + V3*V4=> 4*/
5155: /* including age products which are counted in cptcovage.
5156: /* but the covariates which are products must be treated separately: ncovn=4- 2=2 (V1+V3). */
5157: cptcovprod=j1; /**< Number of products V1*V2 +v3*age = 2 */
5158: cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1 */
5159: strcpy(modelsav,model);
5160: if (strstr(model,"AGE") !=0){
5161: printf("Error. AGE must be in lower case 'age' model=%s ",model);
5162: fprintf(ficlog,"Error. AGE must be in lower case model=%s ",model);fflush(ficlog);
5163: return 1;
5164: }
5165: if (strstr(model,"v") !=0){
5166: printf("Error. 'v' must be in upper case 'V' model=%s ",model);
5167: fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
5168: return 1;
5169: }
5170:
5171: /* Design
5172: * V1 V2 V3 V4 V5 V6 V7 V8 V9 Weight
5173: * < ncovcol=8 >
5174: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
5175: * k= 1 2 3 4 5 6 7 8
5176: * cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
5177: * covar[k,i], value of kth covariate if not including age for individual i:
5178: * covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
5179: * Tvar[k] # of the kth covariate: Tvar[1]=2 Tvar[4]=3 Tvar[8]=8
5180: * if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and
5181: * Tage[++cptcovage]=k
5182: * if products, new covar are created after ncovcol with k1
5183: * Tvar[k]=ncovcol+k1; # of the kth covariate product: Tvar[5]=ncovcol+1=10 Tvar[6]=ncovcol+1=11
5184: * Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
5185: * 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
5186: * Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
5187: * Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
5188: * V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
5189: * < ncovcol=8 >
5190: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 d1 d1 d2 d2
5191: * k= 1 2 3 4 5 6 7 8 9 10 11 12
5192: * Tvar[k]= 2 1 3 3 10 11 8 8 5 6 7 8
5193: * p Tvar[1]@12={2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5194: * p Tprod[1]@2={ 6, 5}
5195: *p Tvard[1][1]@4= {7, 8, 5, 6}
5196: * covar[k][i]= V2 V1 ? V3 V5*V6? V7*V8? ? V8
5197: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
5198: *How to reorganize?
5199: * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
5200: * Tvars {2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5201: * {2, 1, 4, 8, 5, 6, 3, 7}
5202: * Struct []
5203: */
5204:
5205: /* This loop fills the array Tvar from the string 'model'.*/
5206: /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
5207: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 */
5208: /* k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
5209: /* k=3 V4 Tvar[k=3]= 4 (from V4) */
5210: /* k=2 V1 Tvar[k=2]= 1 (from V1) */
5211: /* k=1 Tvar[1]=2 (from V2) */
5212: /* k=5 Tvar[5] */
5213: /* for (k=1; k<=cptcovn;k++) { */
5214: /* cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
5215: /* } */
5216: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
5217: /*
5218: * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
5219: for(k=cptcovt; k>=1;k--) /**< Number of covariates */
5220: Tvar[k]=0;
5221: cptcovage=0;
5222: for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
5223: cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+'
5224: modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */
5225: if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
5226: /* printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
5227: /*scanf("%d",i);*/
5228: if (strchr(strb,'*')) { /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
5229: cutl(strc,strd,strb,'*'); /**< strd*strc Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
5230: if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
5231: /* covar is not filled and then is empty */
5232: cptcovprod--;
5233: cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
5234: Tvar[k]=atoi(stre); /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2 */
5235: cptcovage++; /* Sums the number of covariates which include age as a product */
5236: Tage[cptcovage]=k; /* Tage[1] = 4 */
5237: /*printf("stre=%s ", stre);*/
5238: } else if (strcmp(strd,"age")==0) { /* or age*Vn */
5239: cptcovprod--;
5240: cutl(stre,strb,strc,'V');
5241: Tvar[k]=atoi(stre);
5242: cptcovage++;
5243: Tage[cptcovage]=k;
5244: } else { /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2 strb=V3*V2*/
5245: /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
5246: cptcovn++;
5247: cptcovprodnoage++;k1++;
5248: cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
5249: Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
5250: because this model-covariate is a construction we invent a new column
5251: ncovcol + k1
5252: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
5253: Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
5254: cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
5255: Tprod[k1]=k; /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 */
5256: Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
5257: Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
5258: k2=k2+2;
5259: Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
5260: Tvar[cptcovt+k2+1]=Tvard[k1][2]; /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
5261: for (i=1; i<=lastobs;i++){
5262: /* Computes the new covariate which is a product of
5263: covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
5264: covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
5265: }
5266: } /* End age is not in the model */
5267: } /* End if model includes a product */
5268: else { /* no more sum */
5269: /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
5270: /* scanf("%d",i);*/
5271: cutl(strd,strc,strb,'V');
5272: ks++; /**< Number of simple covariates */
5273: cptcovn++;
5274: Tvar[k]=atoi(strd);
5275: }
5276: strcpy(modelsav,stra); /* modelsav=V2+V1+V4 stra=V2+V1+V4 */
5277: /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
5278: scanf("%d",i);*/
5279: } /* end of loop + */
5280: } /* end model */
5281:
5282: /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
5283: If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
5284:
5285: /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
5286: printf("cptcovprod=%d ", cptcovprod);
5287: fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
5288:
5289: scanf("%d ",i);*/
5290:
5291:
5292: return (0); /* with covar[new additional covariate if product] and Tage if age */
5293: endread:
5294: printf("Exiting decodemodel: ");
5295: return (1);
5296: }
5297:
5298: calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
5299: {
5300: int i, m;
5301:
5302: for (i=1; i<=imx; i++) {
5303: for(m=2; (m<= maxwav); m++) {
5304: if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
5305: anint[m][i]=9999;
5306: s[m][i]=-1;
5307: }
5308: if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
5309: *nberr++;
5310: 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);
5311: 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);
5312: s[m][i]=-1;
5313: }
5314: if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
5315: *nberr++;
5316: 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]);
5317: 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]);
5318: s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
5319: }
5320: }
5321: }
5322:
5323: for (i=1; i<=imx; i++) {
5324: agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
5325: for(m=firstpass; (m<= lastpass); m++){
5326: if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
5327: if (s[m][i] >= nlstate+1) {
5328: if(agedc[i]>0)
5329: if((int)moisdc[i]!=99 && (int)andc[i]!=9999)
5330: agev[m][i]=agedc[i];
5331: /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
5332: else {
5333: if ((int)andc[i]!=9999){
5334: nbwarn++;
5335: printf("Warning negative age at death: %ld line:%d\n",num[i],i);
5336: fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
5337: agev[m][i]=-1;
5338: }
5339: }
5340: }
5341: else if(s[m][i] !=9){ /* Standard case, age in fractional
5342: years but with the precision of a month */
5343: agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
5344: if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
5345: agev[m][i]=1;
5346: else if(agev[m][i] < *agemin){
5347: *agemin=agev[m][i];
5348: printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
5349: }
5350: else if(agev[m][i] >*agemax){
5351: *agemax=agev[m][i];
5352: /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
5353: }
5354: /*agev[m][i]=anint[m][i]-annais[i];*/
5355: /* agev[m][i] = age[i]+2*m;*/
5356: }
5357: else { /* =9 */
5358: agev[m][i]=1;
5359: s[m][i]=-1;
5360: }
5361: }
5362: else /*= 0 Unknown */
5363: agev[m][i]=1;
5364: }
5365:
5366: }
5367: for (i=1; i<=imx; i++) {
5368: for(m=firstpass; (m<=lastpass); m++){
5369: if (s[m][i] > (nlstate+ndeath)) {
5370: *nberr++;
5371: 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);
5372: 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);
5373: return 1;
5374: }
5375: }
5376: }
5377:
5378: /*for (i=1; i<=imx; i++){
5379: for (m=firstpass; (m<lastpass); m++){
5380: printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
5381: }
5382:
5383: }*/
5384:
5385:
5386: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
5387: fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
5388:
5389: return (0);
5390: endread:
5391: printf("Exiting calandcheckages: ");
5392: return (1);
5393: }
5394:
5395:
5396: /***********************************************/
5397: /**************** Main Program *****************/
5398: /***********************************************/
5399:
5400: int main(int argc, char *argv[])
5401: {
5402: #ifdef GSL
5403: const gsl_multimin_fminimizer_type *T;
5404: size_t iteri = 0, it;
5405: int rval = GSL_CONTINUE;
5406: int status = GSL_SUCCESS;
5407: double ssval;
5408: #endif
5409: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
5410: int i,j, k, n=MAXN,iter,m,size=100,cptcode, cptcod;
5411: int linei, month, year,iout;
5412: int jj, ll, li, lj, lk, imk;
5413: int numlinepar=0; /* Current linenumber of parameter file */
5414: int itimes;
5415: int NDIM=2;
5416: int vpopbased=0;
5417:
5418: char ca[32], cb[32], cc[32];
5419: /* FILE *fichtm; *//* Html File */
5420: /* FILE *ficgp;*/ /*Gnuplot File */
5421: struct stat info;
5422: double agedeb, agefin,hf;
5423: double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
5424:
5425: double fret;
5426: double **xi,tmp,delta;
5427:
5428: double dum; /* Dummy variable */
5429: double ***p3mat;
5430: double ***mobaverage;
5431: int *indx;
5432: char line[MAXLINE], linepar[MAXLINE];
5433: char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
5434: char pathr[MAXLINE], pathimach[MAXLINE];
5435: char **bp, *tok, *val; /* pathtot */
5436: int firstobs=1, lastobs=10;
5437: int sdeb, sfin; /* Status at beginning and end */
5438: int c, h , cpt,l;
5439: int ju,jl, mi;
5440: int i1,j1, jk,aa,bb, stepsize, ij;
5441: int jnais,jdc,jint4,jint1,jint2,jint3,*tab;
5442: int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
5443: int mobilav=0,popforecast=0;
5444: int hstepm, nhstepm;
5445: int agemortsup;
5446: float sumlpop=0.;
5447: double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
5448: double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
5449:
5450: double bage, fage, age, agelim, agebase;
5451: double ftolpl=FTOL;
5452: double **prlim;
5453: double ***param; /* Matrix of parameters */
5454: double *p;
5455: double **matcov; /* Matrix of covariance */
5456: double ***delti3; /* Scale */
5457: double *delti; /* Scale */
5458: double ***eij, ***vareij;
5459: double **varpl; /* Variances of prevalence limits by age */
5460: double *epj, vepp;
5461: double kk1, kk2;
5462: double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
5463: double **ximort;
5464: char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
5465: int *dcwave;
5466:
5467: char z[1]="c", occ;
5468:
5469: /*char *strt;*/
5470: char strtend[80];
5471:
5472: long total_usecs;
5473:
5474: /* setlocale (LC_ALL, ""); */
5475: /* bindtextdomain (PACKAGE, LOCALEDIR); */
5476: /* textdomain (PACKAGE); */
5477: /* setlocale (LC_CTYPE, ""); */
5478: /* setlocale (LC_MESSAGES, ""); */
5479:
5480: /* gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
5481: rstart_time = time(NULL);
5482: /* (void) gettimeofday(&start_time,&tzp);*/
5483: start_time = *localtime(&rstart_time);
5484: curr_time=start_time;
5485: /*tml = *localtime(&start_time.tm_sec);*/
5486: /* strcpy(strstart,asctime(&tml)); */
5487: strcpy(strstart,asctime(&start_time));
5488:
5489: /* printf("Localtime (at start)=%s",strstart); */
5490: /* tp.tm_sec = tp.tm_sec +86400; */
5491: /* tm = *localtime(&start_time.tm_sec); */
5492: /* tmg.tm_year=tmg.tm_year +dsign*dyear; */
5493: /* tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
5494: /* tmg.tm_hour=tmg.tm_hour + 1; */
5495: /* tp.tm_sec = mktime(&tmg); */
5496: /* strt=asctime(&tmg); */
5497: /* printf("Time(after) =%s",strstart); */
5498: /* (void) time (&time_value);
5499: * printf("time=%d,t-=%d\n",time_value,time_value-86400);
5500: * tm = *localtime(&time_value);
5501: * strstart=asctime(&tm);
5502: * printf("tim_value=%d,asctime=%s\n",time_value,strstart);
5503: */
5504:
5505: nberr=0; /* Number of errors and warnings */
5506: nbwarn=0;
5507: getcwd(pathcd, size);
5508:
5509: printf("\n%s\n%s",version,fullversion);
5510: if(argc <=1){
5511: printf("\nEnter the parameter file name: ");
5512: fgets(pathr,FILENAMELENGTH,stdin);
5513: i=strlen(pathr);
5514: if(pathr[i-1]=='\n')
5515: pathr[i-1]='\0';
5516: i=strlen(pathr);
5517: if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
5518: pathr[i-1]='\0';
5519: for (tok = pathr; tok != NULL; ){
5520: printf("Pathr |%s|\n",pathr);
5521: while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
5522: printf("val= |%s| pathr=%s\n",val,pathr);
5523: strcpy (pathtot, val);
5524: if(pathr[0] == '\0') break; /* Dirty */
5525: }
5526: }
5527: else{
5528: strcpy(pathtot,argv[1]);
5529: }
5530: /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
5531: /*cygwin_split_path(pathtot,path,optionfile);
5532: printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
5533: /* cutv(path,optionfile,pathtot,'\\');*/
5534:
5535: /* Split argv[0], imach program to get pathimach */
5536: printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
5537: split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
5538: printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
5539: /* strcpy(pathimach,argv[0]); */
5540: /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
5541: split(pathtot,path,optionfile,optionfilext,optionfilefiname);
5542: printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
5543: chdir(path); /* Can be a relative path */
5544: if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
5545: printf("Current directory %s!\n",pathcd);
5546: strcpy(command,"mkdir ");
5547: strcat(command,optionfilefiname);
5548: if((outcmd=system(command)) != 0){
5549: printf("Problem creating directory or it already exists %s%s, err=%d\n",path,optionfilefiname,outcmd);
5550: /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
5551: /* fclose(ficlog); */
5552: /* exit(1); */
5553: }
5554: /* if((imk=mkdir(optionfilefiname))<0){ */
5555: /* perror("mkdir"); */
5556: /* } */
5557:
5558: /*-------- arguments in the command line --------*/
5559:
5560: /* Log file */
5561: strcat(filelog, optionfilefiname);
5562: strcat(filelog,".log"); /* */
5563: if((ficlog=fopen(filelog,"w"))==NULL) {
5564: printf("Problem with logfile %s\n",filelog);
5565: goto end;
5566: }
5567: fprintf(ficlog,"Log filename:%s\n",filelog);
5568: fprintf(ficlog,"\n%s\n%s",version,fullversion);
5569: fprintf(ficlog,"\nEnter the parameter file name: \n");
5570: fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
5571: path=%s \n\
5572: optionfile=%s\n\
5573: optionfilext=%s\n\
5574: optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
5575:
5576: printf("Local time (at start):%s",strstart);
5577: fprintf(ficlog,"Local time (at start): %s",strstart);
5578: fflush(ficlog);
5579: /* (void) gettimeofday(&curr_time,&tzp); */
5580: /* printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
5581:
5582: /* */
5583: strcpy(fileres,"r");
5584: strcat(fileres, optionfilefiname);
5585: strcat(fileres,".txt"); /* Other files have txt extension */
5586:
5587: /*---------arguments file --------*/
5588:
5589: if((ficpar=fopen(optionfile,"r"))==NULL) {
5590: printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
5591: fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
5592: fflush(ficlog);
5593: /* goto end; */
5594: exit(70);
5595: }
5596:
5597:
5598:
5599: strcpy(filereso,"o");
5600: strcat(filereso,fileres);
5601: if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
5602: printf("Problem with Output resultfile: %s\n", filereso);
5603: fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
5604: fflush(ficlog);
5605: goto end;
5606: }
5607:
5608: /* Reads comments: lines beginning with '#' */
5609: numlinepar=0;
5610: while((c=getc(ficpar))=='#' && c!= EOF){
5611: ungetc(c,ficpar);
5612: fgets(line, MAXLINE, ficpar);
5613: numlinepar++;
5614: fputs(line,stdout);
5615: fputs(line,ficparo);
5616: fputs(line,ficlog);
5617: }
5618: ungetc(c,ficpar);
5619:
5620: 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);
5621: numlinepar++;
5622: 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);
5623: 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);
5624: 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);
5625: fflush(ficlog);
5626: while((c=getc(ficpar))=='#' && c!= EOF){
5627: ungetc(c,ficpar);
5628: fgets(line, MAXLINE, ficpar);
5629: numlinepar++;
5630: fputs(line, stdout);
5631: //puts(line);
5632: fputs(line,ficparo);
5633: fputs(line,ficlog);
5634: }
5635: ungetc(c,ficpar);
5636:
5637:
5638: covar=matrix(0,NCOVMAX,1,n); /**< used in readdata */
5639: cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
5640: /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
5641: v1+v2*age+v2*v3 makes cptcovn = 3
5642: */
5643: if (strlen(model)>1)
5644: 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*/
5645: else
5646: ncovmodel=2;
5647: nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
5648: nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
5649: npar= nforce*ncovmodel; /* Number of parameters like aij*/
5650: if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
5651: 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);
5652: 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);
5653: fflush(stdout);
5654: fclose (ficlog);
5655: goto end;
5656: }
5657: delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5658: delti=delti3[1][1];
5659: /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
5660: if(mle==-1){ /* Print a wizard for help writing covariance matrix */
5661: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
5662: printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
5663: fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
5664: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
5665: fclose (ficparo);
5666: fclose (ficlog);
5667: goto end;
5668: exit(0);
5669: }
5670: else if(mle==-3) {
5671: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
5672: printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
5673: fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
5674: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5675: matcov=matrix(1,npar,1,npar);
5676: }
5677: else{
5678: /* Read guessed parameters */
5679: /* Reads comments: lines beginning with '#' */
5680: while((c=getc(ficpar))=='#' && c!= EOF){
5681: ungetc(c,ficpar);
5682: fgets(line, MAXLINE, ficpar);
5683: numlinepar++;
5684: fputs(line,stdout);
5685: fputs(line,ficparo);
5686: fputs(line,ficlog);
5687: }
5688: ungetc(c,ficpar);
5689:
5690: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
5691: for(i=1; i <=nlstate; i++){
5692: j=0;
5693: for(jj=1; jj <=nlstate+ndeath; jj++){
5694: if(jj==i) continue;
5695: j++;
5696: fscanf(ficpar,"%1d%1d",&i1,&j1);
5697: if ((i1 != i) && (j1 != j)){
5698: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
5699: It might be a problem of design; if ncovcol and the model are correct\n \
5700: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
5701: exit(1);
5702: }
5703: fprintf(ficparo,"%1d%1d",i1,j1);
5704: if(mle==1)
5705: printf("%1d%1d",i,j);
5706: fprintf(ficlog,"%1d%1d",i,j);
5707: for(k=1; k<=ncovmodel;k++){
5708: fscanf(ficpar," %lf",¶m[i][j][k]);
5709: if(mle==1){
5710: printf(" %lf",param[i][j][k]);
5711: fprintf(ficlog," %lf",param[i][j][k]);
5712: }
5713: else
5714: fprintf(ficlog," %lf",param[i][j][k]);
5715: fprintf(ficparo," %lf",param[i][j][k]);
5716: }
5717: fscanf(ficpar,"\n");
5718: numlinepar++;
5719: if(mle==1)
5720: printf("\n");
5721: fprintf(ficlog,"\n");
5722: fprintf(ficparo,"\n");
5723: }
5724: }
5725: fflush(ficlog);
5726:
5727: /* Reads scales values */
5728: p=param[1][1];
5729:
5730: /* Reads comments: lines beginning with '#' */
5731: while((c=getc(ficpar))=='#' && c!= EOF){
5732: ungetc(c,ficpar);
5733: fgets(line, MAXLINE, ficpar);
5734: numlinepar++;
5735: fputs(line,stdout);
5736: fputs(line,ficparo);
5737: fputs(line,ficlog);
5738: }
5739: ungetc(c,ficpar);
5740:
5741: for(i=1; i <=nlstate; i++){
5742: for(j=1; j <=nlstate+ndeath-1; j++){
5743: fscanf(ficpar,"%1d%1d",&i1,&j1);
5744: if ((i1-i)*(j1-j)!=0){
5745: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
5746: exit(1);
5747: }
5748: printf("%1d%1d",i,j);
5749: fprintf(ficparo,"%1d%1d",i1,j1);
5750: fprintf(ficlog,"%1d%1d",i1,j1);
5751: for(k=1; k<=ncovmodel;k++){
5752: fscanf(ficpar,"%le",&delti3[i][j][k]);
5753: printf(" %le",delti3[i][j][k]);
5754: fprintf(ficparo," %le",delti3[i][j][k]);
5755: fprintf(ficlog," %le",delti3[i][j][k]);
5756: }
5757: fscanf(ficpar,"\n");
5758: numlinepar++;
5759: printf("\n");
5760: fprintf(ficparo,"\n");
5761: fprintf(ficlog,"\n");
5762: }
5763: }
5764: fflush(ficlog);
5765:
5766: /* Reads covariance matrix */
5767: delti=delti3[1][1];
5768:
5769:
5770: /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
5771:
5772: /* Reads comments: lines beginning with '#' */
5773: while((c=getc(ficpar))=='#' && c!= EOF){
5774: ungetc(c,ficpar);
5775: fgets(line, MAXLINE, ficpar);
5776: numlinepar++;
5777: fputs(line,stdout);
5778: fputs(line,ficparo);
5779: fputs(line,ficlog);
5780: }
5781: ungetc(c,ficpar);
5782:
5783: matcov=matrix(1,npar,1,npar);
5784: for(i=1; i <=npar; i++)
5785: for(j=1; j <=npar; j++) matcov[i][j]=0.;
5786:
5787: for(i=1; i <=npar; i++){
5788: fscanf(ficpar,"%s",str);
5789: if(mle==1)
5790: printf("%s",str);
5791: fprintf(ficlog,"%s",str);
5792: fprintf(ficparo,"%s",str);
5793: for(j=1; j <=i; j++){
5794: fscanf(ficpar," %le",&matcov[i][j]);
5795: if(mle==1){
5796: printf(" %.5le",matcov[i][j]);
5797: }
5798: fprintf(ficlog," %.5le",matcov[i][j]);
5799: fprintf(ficparo," %.5le",matcov[i][j]);
5800: }
5801: fscanf(ficpar,"\n");
5802: numlinepar++;
5803: if(mle==1)
5804: printf("\n");
5805: fprintf(ficlog,"\n");
5806: fprintf(ficparo,"\n");
5807: }
5808: for(i=1; i <=npar; i++)
5809: for(j=i+1;j<=npar;j++)
5810: matcov[i][j]=matcov[j][i];
5811:
5812: if(mle==1)
5813: printf("\n");
5814: fprintf(ficlog,"\n");
5815:
5816: fflush(ficlog);
5817:
5818: /*-------- Rewriting parameter file ----------*/
5819: strcpy(rfileres,"r"); /* "Rparameterfile */
5820: strcat(rfileres,optionfilefiname); /* Parameter file first name*/
5821: strcat(rfileres,"."); /* */
5822: strcat(rfileres,optionfilext); /* Other files have txt extension */
5823: if((ficres =fopen(rfileres,"w"))==NULL) {
5824: printf("Problem writing new parameter file: %s\n", fileres);goto end;
5825: fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
5826: }
5827: fprintf(ficres,"#%s\n",version);
5828: } /* End of mle != -3 */
5829:
5830:
5831: n= lastobs;
5832: num=lvector(1,n);
5833: moisnais=vector(1,n);
5834: annais=vector(1,n);
5835: moisdc=vector(1,n);
5836: andc=vector(1,n);
5837: agedc=vector(1,n);
5838: cod=ivector(1,n);
5839: weight=vector(1,n);
5840: for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
5841: mint=matrix(1,maxwav,1,n);
5842: anint=matrix(1,maxwav,1,n);
5843: s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */
5844: tab=ivector(1,NCOVMAX);
5845: ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
5846:
5847: /* Reads data from file datafile */
5848: if (readdata(datafile, firstobs, lastobs, &imx)==1)
5849: goto end;
5850:
5851: /* Calculation of the number of parameters from char model */
5852: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4
5853: k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
5854: k=3 V4 Tvar[k=3]= 4 (from V4)
5855: k=2 V1 Tvar[k=2]= 1 (from V1)
5856: k=1 Tvar[1]=2 (from V2)
5857: */
5858: Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
5859: /* V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs).
5860: For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4,
5861: Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
5862: */
5863: /* For model-covariate k tells which data-covariate to use but
5864: because this model-covariate is a construction we invent a new column
5865: ncovcol + k1
5866: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
5867: Tvar[3=V1*V4]=4+1 etc */
5868: Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
5869: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
5870: if V2+V1+V1*V4+age*V3+V3*V2 TProd[k1=2]=5 (V3*V2)
5871: */
5872: Tvaraff=ivector(1,NCOVMAX); /* Unclear */
5873: 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
5874: * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd.
5875: * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
5876: Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
5877: 4 covariates (3 plus signs)
5878: Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
5879: */
5880:
5881: if(decodemodel(model, lastobs) == 1)
5882: goto end;
5883:
5884: if((double)(lastobs-imx)/(double)imx > 1.10){
5885: nbwarn++;
5886: 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);
5887: 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);
5888: }
5889: /* if(mle==1){*/
5890: if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
5891: for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
5892: }
5893:
5894: /*-calculation of age at interview from date of interview and age at death -*/
5895: agev=matrix(1,maxwav,1,imx);
5896:
5897: if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
5898: goto end;
5899:
5900:
5901: agegomp=(int)agemin;
5902: free_vector(moisnais,1,n);
5903: free_vector(annais,1,n);
5904: /* free_matrix(mint,1,maxwav,1,n);
5905: free_matrix(anint,1,maxwav,1,n);*/
5906: free_vector(moisdc,1,n);
5907: free_vector(andc,1,n);
5908: /* */
5909:
5910: wav=ivector(1,imx);
5911: dh=imatrix(1,lastpass-firstpass+1,1,imx);
5912: bh=imatrix(1,lastpass-firstpass+1,1,imx);
5913: mw=imatrix(1,lastpass-firstpass+1,1,imx);
5914:
5915: /* Concatenates waves */
5916: concatwav(wav, dh, bh, mw, s, agedc, agev, firstpass, lastpass, imx, nlstate, stepm);
5917: /* */
5918:
5919: /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
5920:
5921: nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
5922: ncodemax[1]=1;
5923: Ndum =ivector(-1,NCOVMAX);
5924: if (ncovmodel > 2)
5925: tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
5926:
5927: codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
5928: /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
5929: h=0;
5930:
5931:
5932: /*if (cptcovn > 0) */
5933:
5934:
5935: m=pow(2,cptcoveff);
5936:
5937: for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
5938: 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 */
5939: for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
5940: for(cpt=1; cpt <=pow(2,k-1); cpt++){ /* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 */
5941: h++;
5942: if (h>m)
5943: h=1;
5944: /**< codtab(h,k) k = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
5945: * h 1 2 3 4
5946: *______________________________
5947: * 1 i=1 1 i=1 1 i=1 1 i=1 1
5948: * 2 2 1 1 1
5949: * 3 i=2 1 2 1 1
5950: * 4 2 2 1 1
5951: * 5 i=3 1 i=2 1 2 1
5952: * 6 2 1 2 1
5953: * 7 i=4 1 2 2 1
5954: * 8 2 2 2 1
5955: * 9 i=5 1 i=3 1 i=2 1 1
5956: * 10 2 1 1 1
5957: * 11 i=6 1 2 1 1
5958: * 12 2 2 1 1
5959: * 13 i=7 1 i=4 1 2 1
5960: * 14 2 1 2 1
5961: * 15 i=8 1 2 2 1
5962: * 16 2 2 2 1
5963: */
5964: codtab[h][k]=j;
5965: /*codtab[h][Tvar[k]]=j;*/
5966: 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]]);
5967: }
5968: }
5969: }
5970: }
5971: /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
5972: codtab[1][2]=1;codtab[2][2]=2; */
5973: /* for(i=1; i <=m ;i++){
5974: for(k=1; k <=cptcovn; k++){
5975: printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
5976: }
5977: printf("\n");
5978: }
5979: scanf("%d",i);*/
5980:
5981: free_ivector(Ndum,-1,NCOVMAX);
5982:
5983:
5984:
5985: /*------------ gnuplot -------------*/
5986: strcpy(optionfilegnuplot,optionfilefiname);
5987: if(mle==-3)
5988: strcat(optionfilegnuplot,"-mort");
5989: strcat(optionfilegnuplot,".gp");
5990:
5991: if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
5992: printf("Problem with file %s",optionfilegnuplot);
5993: }
5994: else{
5995: fprintf(ficgp,"\n# %s\n", version);
5996: fprintf(ficgp,"# %s\n", optionfilegnuplot);
5997: //fprintf(ficgp,"set missing 'NaNq'\n");
5998: fprintf(ficgp,"set datafile missing 'NaNq'\n");
5999: }
6000: /* fclose(ficgp);*/
6001: /*--------- index.htm --------*/
6002:
6003: strcpy(optionfilehtm,optionfilefiname); /* Main html file */
6004: if(mle==-3)
6005: strcat(optionfilehtm,"-mort");
6006: strcat(optionfilehtm,".htm");
6007: if((fichtm=fopen(optionfilehtm,"w"))==NULL) {
6008: printf("Problem with %s \n",optionfilehtm);
6009: exit(0);
6010: }
6011:
6012: strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
6013: strcat(optionfilehtmcov,"-cov.htm");
6014: if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL) {
6015: printf("Problem with %s \n",optionfilehtmcov), exit(0);
6016: }
6017: else{
6018: fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6019: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6020: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
6021: optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
6022: }
6023:
6024: fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6025: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6026: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
6027: \n\
6028: <hr size=\"2\" color=\"#EC5E5E\">\
6029: <ul><li><h4>Parameter files</h4>\n\
6030: - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
6031: - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
6032: - Log file of the run: <a href=\"%s\">%s</a><br>\n\
6033: - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
6034: - Date and time at start: %s</ul>\n",\
6035: optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
6036: optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
6037: fileres,fileres,\
6038: filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
6039: fflush(fichtm);
6040:
6041: strcpy(pathr,path);
6042: strcat(pathr,optionfilefiname);
6043: chdir(optionfilefiname); /* Move to directory named optionfile */
6044:
6045: /* Calculates basic frequencies. Computes observed prevalence at single age
6046: and prints on file fileres'p'. */
6047: freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
6048:
6049: fprintf(fichtm,"\n");
6050: fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
6051: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
6052: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
6053: imx,agemin,agemax,jmin,jmax,jmean);
6054: pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6055: oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6056: newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6057: savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6058: oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
6059:
6060:
6061: /* For Powell, parameters are in a vector p[] starting at p[1]
6062: so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
6063: p=param[1][1]; /* *(*(*(param +1)+1)+0) */
6064:
6065: globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
6066:
6067: if (mle==-3){
6068: ximort=matrix(1,NDIM,1,NDIM);
6069: /* ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
6070: cens=ivector(1,n);
6071: ageexmed=vector(1,n);
6072: agecens=vector(1,n);
6073: dcwave=ivector(1,n);
6074:
6075: for (i=1; i<=imx; i++){
6076: dcwave[i]=-1;
6077: for (m=firstpass; m<=lastpass; m++)
6078: if (s[m][i]>nlstate) {
6079: dcwave[i]=m;
6080: /* printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
6081: break;
6082: }
6083: }
6084:
6085: for (i=1; i<=imx; i++) {
6086: if (wav[i]>0){
6087: ageexmed[i]=agev[mw[1][i]][i];
6088: j=wav[i];
6089: agecens[i]=1.;
6090:
6091: if (ageexmed[i]> 1 && wav[i] > 0){
6092: agecens[i]=agev[mw[j][i]][i];
6093: cens[i]= 1;
6094: }else if (ageexmed[i]< 1)
6095: cens[i]= -1;
6096: if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
6097: cens[i]=0 ;
6098: }
6099: else cens[i]=-1;
6100: }
6101:
6102: for (i=1;i<=NDIM;i++) {
6103: for (j=1;j<=NDIM;j++)
6104: ximort[i][j]=(i == j ? 1.0 : 0.0);
6105: }
6106:
6107: /*p[1]=0.0268; p[NDIM]=0.083;*/
6108: /*printf("%lf %lf", p[1], p[2]);*/
6109:
6110:
6111: #ifdef GSL
6112: printf("GSL optimization\n"); fprintf(ficlog,"Powell\n");
6113: #else
6114: printf("Powell\n"); fprintf(ficlog,"Powell\n");
6115: #endif
6116: strcpy(filerespow,"pow-mort");
6117: strcat(filerespow,fileres);
6118: if((ficrespow=fopen(filerespow,"w"))==NULL) {
6119: printf("Problem with resultfile: %s\n", filerespow);
6120: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
6121: }
6122: #ifdef GSL
6123: fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
6124: #else
6125: fprintf(ficrespow,"# Powell\n# iter -2*LL");
6126: #endif
6127: /* for (i=1;i<=nlstate;i++)
6128: for(j=1;j<=nlstate+ndeath;j++)
6129: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
6130: */
6131: fprintf(ficrespow,"\n");
6132: #ifdef GSL
6133: /* gsl starts here */
6134: T = gsl_multimin_fminimizer_nmsimplex;
6135: gsl_multimin_fminimizer *sfm = NULL;
6136: gsl_vector *ss, *x;
6137: gsl_multimin_function minex_func;
6138:
6139: /* Initial vertex size vector */
6140: ss = gsl_vector_alloc (NDIM);
6141:
6142: if (ss == NULL){
6143: GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
6144: }
6145: /* Set all step sizes to 1 */
6146: gsl_vector_set_all (ss, 0.001);
6147:
6148: /* Starting point */
6149:
6150: x = gsl_vector_alloc (NDIM);
6151:
6152: if (x == NULL){
6153: gsl_vector_free(ss);
6154: GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
6155: }
6156:
6157: /* Initialize method and iterate */
6158: /* p[1]=0.0268; p[NDIM]=0.083; */
6159: /* gsl_vector_set(x, 0, 0.0268); */
6160: /* gsl_vector_set(x, 1, 0.083); */
6161: gsl_vector_set(x, 0, p[1]);
6162: gsl_vector_set(x, 1, p[2]);
6163:
6164: minex_func.f = &gompertz_f;
6165: minex_func.n = NDIM;
6166: minex_func.params = (void *)&p; /* ??? */
6167:
6168: sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
6169: gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
6170:
6171: printf("Iterations beginning .....\n\n");
6172: printf("Iter. # Intercept Slope -Log Likelihood Simplex size\n");
6173:
6174: iteri=0;
6175: while (rval == GSL_CONTINUE){
6176: iteri++;
6177: status = gsl_multimin_fminimizer_iterate(sfm);
6178:
6179: if (status) printf("error: %s\n", gsl_strerror (status));
6180: fflush(0);
6181:
6182: if (status)
6183: break;
6184:
6185: rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
6186: ssval = gsl_multimin_fminimizer_size (sfm);
6187:
6188: if (rval == GSL_SUCCESS)
6189: printf ("converged to a local maximum at\n");
6190:
6191: printf("%5d ", iteri);
6192: for (it = 0; it < NDIM; it++){
6193: printf ("%10.5f ", gsl_vector_get (sfm->x, it));
6194: }
6195: printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
6196: }
6197:
6198: printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
6199:
6200: gsl_vector_free(x); /* initial values */
6201: gsl_vector_free(ss); /* inital step size */
6202: for (it=0; it<NDIM; it++){
6203: p[it+1]=gsl_vector_get(sfm->x,it);
6204: fprintf(ficrespow," %.12lf", p[it]);
6205: }
6206: gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1) */
6207: #endif
6208: #ifdef POWELL
6209: powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
6210: #endif
6211: fclose(ficrespow);
6212:
6213: hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);
6214:
6215: for(i=1; i <=NDIM; i++)
6216: for(j=i+1;j<=NDIM;j++)
6217: matcov[i][j]=matcov[j][i];
6218:
6219: printf("\nCovariance matrix\n ");
6220: for(i=1; i <=NDIM; i++) {
6221: for(j=1;j<=NDIM;j++){
6222: printf("%f ",matcov[i][j]);
6223: }
6224: printf("\n ");
6225: }
6226:
6227: printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
6228: for (i=1;i<=NDIM;i++)
6229: printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
6230:
6231: lsurv=vector(1,AGESUP);
6232: lpop=vector(1,AGESUP);
6233: tpop=vector(1,AGESUP);
6234: lsurv[agegomp]=100000;
6235:
6236: for (k=agegomp;k<=AGESUP;k++) {
6237: agemortsup=k;
6238: if (p[1]*exp(p[2]*(k-agegomp))>1) break;
6239: }
6240:
6241: for (k=agegomp;k<agemortsup;k++)
6242: lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
6243:
6244: for (k=agegomp;k<agemortsup;k++){
6245: lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
6246: sumlpop=sumlpop+lpop[k];
6247: }
6248:
6249: tpop[agegomp]=sumlpop;
6250: for (k=agegomp;k<(agemortsup-3);k++){
6251: /* tpop[k+1]=2;*/
6252: tpop[k+1]=tpop[k]-lpop[k];
6253: }
6254:
6255:
6256: printf("\nAge lx qx dx Lx Tx e(x)\n");
6257: for (k=agegomp;k<(agemortsup-2);k++)
6258: 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]);
6259:
6260:
6261: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6262: printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6263:
6264: printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
6265: stepm, weightopt,\
6266: model,imx,p,matcov,agemortsup);
6267:
6268: free_vector(lsurv,1,AGESUP);
6269: free_vector(lpop,1,AGESUP);
6270: free_vector(tpop,1,AGESUP);
6271: #ifdef GSL
6272: free_ivector(cens,1,n);
6273: free_vector(agecens,1,n);
6274: free_ivector(dcwave,1,n);
6275: free_matrix(ximort,1,NDIM,1,NDIM);
6276: #endif
6277: } /* Endof if mle==-3 */
6278:
6279: else{ /* For mle >=1 */
6280: globpr=0;/* debug */
6281: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
6282: printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6283: for (k=1; k<=npar;k++)
6284: printf(" %d %8.5f",k,p[k]);
6285: printf("\n");
6286: globpr=1; /* to print the contributions */
6287: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
6288: printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6289: for (k=1; k<=npar;k++)
6290: printf(" %d %8.5f",k,p[k]);
6291: printf("\n");
6292: if(mle>=1){ /* Could be 1 or 2 */
6293: mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
6294: }
6295:
6296: /*--------- results files --------------*/
6297: 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);
6298:
6299:
6300: fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6301: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6302: fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6303: for(i=1,jk=1; i <=nlstate; i++){
6304: for(k=1; k <=(nlstate+ndeath); k++){
6305: if (k != i) {
6306: printf("%d%d ",i,k);
6307: fprintf(ficlog,"%d%d ",i,k);
6308: fprintf(ficres,"%1d%1d ",i,k);
6309: for(j=1; j <=ncovmodel; j++){
6310: printf("%lf ",p[jk]);
6311: fprintf(ficlog,"%lf ",p[jk]);
6312: fprintf(ficres,"%lf ",p[jk]);
6313: jk++;
6314: }
6315: printf("\n");
6316: fprintf(ficlog,"\n");
6317: fprintf(ficres,"\n");
6318: }
6319: }
6320: }
6321: if(mle!=0){
6322: /* Computing hessian and covariance matrix */
6323: ftolhess=ftol; /* Usually correct */
6324: hesscov(matcov, p, npar, delti, ftolhess, func);
6325: }
6326: fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
6327: printf("# Scales (for hessian or gradient estimation)\n");
6328: fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
6329: for(i=1,jk=1; i <=nlstate; i++){
6330: for(j=1; j <=nlstate+ndeath; j++){
6331: if (j!=i) {
6332: fprintf(ficres,"%1d%1d",i,j);
6333: printf("%1d%1d",i,j);
6334: fprintf(ficlog,"%1d%1d",i,j);
6335: for(k=1; k<=ncovmodel;k++){
6336: printf(" %.5e",delti[jk]);
6337: fprintf(ficlog," %.5e",delti[jk]);
6338: fprintf(ficres," %.5e",delti[jk]);
6339: jk++;
6340: }
6341: printf("\n");
6342: fprintf(ficlog,"\n");
6343: fprintf(ficres,"\n");
6344: }
6345: }
6346: }
6347:
6348: 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");
6349: if(mle>=1)
6350: 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");
6351: 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");
6352: /* # 121 Var(a12)\n\ */
6353: /* # 122 Cov(b12,a12) Var(b12)\n\ */
6354: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
6355: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
6356: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
6357: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
6358: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
6359: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
6360:
6361:
6362: /* Just to have a covariance matrix which will be more understandable
6363: even is we still don't want to manage dictionary of variables
6364: */
6365: for(itimes=1;itimes<=2;itimes++){
6366: jj=0;
6367: for(i=1; i <=nlstate; i++){
6368: for(j=1; j <=nlstate+ndeath; j++){
6369: if(j==i) continue;
6370: for(k=1; k<=ncovmodel;k++){
6371: jj++;
6372: ca[0]= k+'a'-1;ca[1]='\0';
6373: if(itimes==1){
6374: if(mle>=1)
6375: printf("#%1d%1d%d",i,j,k);
6376: fprintf(ficlog,"#%1d%1d%d",i,j,k);
6377: fprintf(ficres,"#%1d%1d%d",i,j,k);
6378: }else{
6379: if(mle>=1)
6380: printf("%1d%1d%d",i,j,k);
6381: fprintf(ficlog,"%1d%1d%d",i,j,k);
6382: fprintf(ficres,"%1d%1d%d",i,j,k);
6383: }
6384: ll=0;
6385: for(li=1;li <=nlstate; li++){
6386: for(lj=1;lj <=nlstate+ndeath; lj++){
6387: if(lj==li) continue;
6388: for(lk=1;lk<=ncovmodel;lk++){
6389: ll++;
6390: if(ll<=jj){
6391: cb[0]= lk +'a'-1;cb[1]='\0';
6392: if(ll<jj){
6393: if(itimes==1){
6394: if(mle>=1)
6395: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6396: fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6397: fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6398: }else{
6399: if(mle>=1)
6400: printf(" %.5e",matcov[jj][ll]);
6401: fprintf(ficlog," %.5e",matcov[jj][ll]);
6402: fprintf(ficres," %.5e",matcov[jj][ll]);
6403: }
6404: }else{
6405: if(itimes==1){
6406: if(mle>=1)
6407: printf(" Var(%s%1d%1d)",ca,i,j);
6408: fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
6409: fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
6410: }else{
6411: if(mle>=1)
6412: printf(" %.5e",matcov[jj][ll]);
6413: fprintf(ficlog," %.5e",matcov[jj][ll]);
6414: fprintf(ficres," %.5e",matcov[jj][ll]);
6415: }
6416: }
6417: }
6418: } /* end lk */
6419: } /* end lj */
6420: } /* end li */
6421: if(mle>=1)
6422: printf("\n");
6423: fprintf(ficlog,"\n");
6424: fprintf(ficres,"\n");
6425: numlinepar++;
6426: } /* end k*/
6427: } /*end j */
6428: } /* end i */
6429: } /* end itimes */
6430:
6431: fflush(ficlog);
6432: fflush(ficres);
6433:
6434: while((c=getc(ficpar))=='#' && c!= EOF){
6435: ungetc(c,ficpar);
6436: fgets(line, MAXLINE, ficpar);
6437: fputs(line,stdout);
6438: fputs(line,ficparo);
6439: }
6440: ungetc(c,ficpar);
6441:
6442: estepm=0;
6443: fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
6444: if (estepm==0 || estepm < stepm) estepm=stepm;
6445: if (fage <= 2) {
6446: bage = ageminpar;
6447: fage = agemaxpar;
6448: }
6449:
6450: fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
6451: fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6452: fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6453:
6454: while((c=getc(ficpar))=='#' && c!= EOF){
6455: ungetc(c,ficpar);
6456: fgets(line, MAXLINE, ficpar);
6457: fputs(line,stdout);
6458: fputs(line,ficparo);
6459: }
6460: ungetc(c,ficpar);
6461:
6462: 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);
6463: 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);
6464: 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);
6465: printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
6466: 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);
6467:
6468: while((c=getc(ficpar))=='#' && c!= EOF){
6469: ungetc(c,ficpar);
6470: fgets(line, MAXLINE, ficpar);
6471: fputs(line,stdout);
6472: fputs(line,ficparo);
6473: }
6474: ungetc(c,ficpar);
6475:
6476:
6477: dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
6478: dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
6479:
6480: fscanf(ficpar,"pop_based=%d\n",&popbased);
6481: fprintf(ficparo,"pop_based=%d\n",popbased);
6482: fprintf(ficres,"pop_based=%d\n",popbased);
6483:
6484: while((c=getc(ficpar))=='#' && c!= EOF){
6485: ungetc(c,ficpar);
6486: fgets(line, MAXLINE, ficpar);
6487: fputs(line,stdout);
6488: fputs(line,ficparo);
6489: }
6490: ungetc(c,ficpar);
6491:
6492: 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);
6493: 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);
6494: 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);
6495: 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);
6496: 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);
6497: /* day and month of proj2 are not used but only year anproj2.*/
6498:
6499:
6500:
6501: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
6502: /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
6503:
6504: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6505: printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6506:
6507: printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
6508: model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
6509: jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
6510:
6511: /*------------ free_vector -------------*/
6512: /* chdir(path); */
6513:
6514: free_ivector(wav,1,imx);
6515: free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
6516: free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
6517: free_imatrix(mw,1,lastpass-firstpass+1,1,imx);
6518: free_lvector(num,1,n);
6519: free_vector(agedc,1,n);
6520: /*free_matrix(covar,0,NCOVMAX,1,n);*/
6521: /*free_matrix(covar,1,NCOVMAX,1,n);*/
6522: fclose(ficparo);
6523: fclose(ficres);
6524:
6525:
6526: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
6527: #include "prevlim.h" /* Use ficrespl, ficlog */
6528: fclose(ficrespl);
6529:
6530: #ifdef FREEEXIT2
6531: #include "freeexit2.h"
6532: #endif
6533:
6534: /*------------- h Pij x at various ages ------------*/
6535: #include "hpijx.h"
6536: fclose(ficrespij);
6537:
6538: /*-------------- Variance of one-step probabilities---*/
6539: k=1;
6540: varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
6541:
6542:
6543: probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
6544: for(i=1;i<=AGESUP;i++)
6545: for(j=1;j<=NCOVMAX;j++)
6546: for(k=1;k<=NCOVMAX;k++)
6547: probs[i][j][k]=0.;
6548:
6549: /*---------- Forecasting ------------------*/
6550: /*if((stepm == 1) && (strcmp(model,".")==0)){*/
6551: if(prevfcast==1){
6552: /* if(stepm ==1){*/
6553: prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
6554: /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
6555: /* } */
6556: /* else{ */
6557: /* erreur=108; */
6558: /* 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); */
6559: /* 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); */
6560: /* } */
6561: }
6562:
6563:
6564: /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
6565:
6566: prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
6567: /* 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",\
6568: ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
6569: */
6570:
6571: if (mobilav!=0) {
6572: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
6573: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
6574: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
6575: printf(" Error in movingaverage mobilav=%d\n",mobilav);
6576: }
6577: }
6578:
6579:
6580: /*---------- Health expectancies, no variances ------------*/
6581:
6582: strcpy(filerese,"e");
6583: strcat(filerese,fileres);
6584: if((ficreseij=fopen(filerese,"w"))==NULL) {
6585: printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
6586: fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
6587: }
6588: printf("Computing Health Expectancies: result on file '%s' \n", filerese);
6589: fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
6590: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6591: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6592:
6593: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6594: fprintf(ficreseij,"\n#****** ");
6595: for(j=1;j<=cptcoveff;j++) {
6596: fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6597: }
6598: fprintf(ficreseij,"******\n");
6599:
6600: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6601: oldm=oldms;savm=savms;
6602: evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);
6603:
6604: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
6605: /*}*/
6606: }
6607: fclose(ficreseij);
6608:
6609:
6610: /*---------- Health expectancies and variances ------------*/
6611:
6612:
6613: strcpy(filerest,"t");
6614: strcat(filerest,fileres);
6615: if((ficrest=fopen(filerest,"w"))==NULL) {
6616: printf("Problem with total LE resultfile: %s\n", filerest);goto end;
6617: fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
6618: }
6619: printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
6620: fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
6621:
6622:
6623: strcpy(fileresstde,"stde");
6624: strcat(fileresstde,fileres);
6625: if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
6626: printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
6627: fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
6628: }
6629: printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
6630: fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
6631:
6632: strcpy(filerescve,"cve");
6633: strcat(filerescve,fileres);
6634: if((ficrescveij=fopen(filerescve,"w"))==NULL) {
6635: printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
6636: fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
6637: }
6638: printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
6639: fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
6640:
6641: strcpy(fileresv,"v");
6642: strcat(fileresv,fileres);
6643: if((ficresvij=fopen(fileresv,"w"))==NULL) {
6644: printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
6645: fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
6646: }
6647: printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
6648: fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
6649:
6650: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6651: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6652:
6653: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6654: fprintf(ficrest,"\n#****** ");
6655: for(j=1;j<=cptcoveff;j++)
6656: fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6657: fprintf(ficrest,"******\n");
6658:
6659: fprintf(ficresstdeij,"\n#****** ");
6660: fprintf(ficrescveij,"\n#****** ");
6661: for(j=1;j<=cptcoveff;j++) {
6662: fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6663: fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6664: }
6665: fprintf(ficresstdeij,"******\n");
6666: fprintf(ficrescveij,"******\n");
6667:
6668: fprintf(ficresvij,"\n#****** ");
6669: for(j=1;j<=cptcoveff;j++)
6670: fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6671: fprintf(ficresvij,"******\n");
6672:
6673: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6674: oldm=oldms;savm=savms;
6675: cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
6676: /*
6677: */
6678: /* goto endfree; */
6679:
6680: vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6681: pstamp(ficrest);
6682:
6683:
6684: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
6685: oldm=oldms;savm=savms; /* Segmentation fault */
6686: cptcod= 0; /* To be deleted */
6687: varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart); /* cptcod not initialized Intel */
6688: 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 ");
6689: if(vpopbased==1)
6690: 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);
6691: else
6692: fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
6693: fprintf(ficrest,"# Age e.. (std) ");
6694: for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
6695: fprintf(ficrest,"\n");
6696:
6697: epj=vector(1,nlstate+1);
6698: for(age=bage; age <=fage ;age++){
6699: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
6700: if (vpopbased==1) {
6701: if(mobilav ==0){
6702: for(i=1; i<=nlstate;i++)
6703: prlim[i][i]=probs[(int)age][i][k];
6704: }else{ /* mobilav */
6705: for(i=1; i<=nlstate;i++)
6706: prlim[i][i]=mobaverage[(int)age][i][k];
6707: }
6708: }
6709:
6710: fprintf(ficrest," %4.0f",age);
6711: for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
6712: for(i=1, epj[j]=0.;i <=nlstate;i++) {
6713: epj[j] += prlim[i][i]*eij[i][j][(int)age];
6714: /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
6715: }
6716: epj[nlstate+1] +=epj[j];
6717: }
6718:
6719: for(i=1, vepp=0.;i <=nlstate;i++)
6720: for(j=1;j <=nlstate;j++)
6721: vepp += vareij[i][j][(int)age];
6722: fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
6723: for(j=1;j <=nlstate;j++){
6724: fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
6725: }
6726: fprintf(ficrest,"\n");
6727: }
6728: }
6729: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
6730: free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
6731: free_vector(epj,1,nlstate+1);
6732: /*}*/
6733: }
6734: free_vector(weight,1,n);
6735: free_imatrix(Tvard,1,NCOVMAX,1,2);
6736: free_imatrix(s,1,maxwav+1,1,n);
6737: free_matrix(anint,1,maxwav,1,n);
6738: free_matrix(mint,1,maxwav,1,n);
6739: free_ivector(cod,1,n);
6740: free_ivector(tab,1,NCOVMAX);
6741: fclose(ficresstdeij);
6742: fclose(ficrescveij);
6743: fclose(ficresvij);
6744: fclose(ficrest);
6745: fclose(ficpar);
6746:
6747: /*------- Variance of period (stable) prevalence------*/
6748:
6749: strcpy(fileresvpl,"vpl");
6750: strcat(fileresvpl,fileres);
6751: if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
6752: printf("Problem with variance of period (stable) prevalence resultfile: %s\n", fileresvpl);
6753: exit(0);
6754: }
6755: printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
6756:
6757: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6758: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6759:
6760: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6761: fprintf(ficresvpl,"\n#****** ");
6762: for(j=1;j<=cptcoveff;j++)
6763: fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6764: fprintf(ficresvpl,"******\n");
6765:
6766: varpl=matrix(1,nlstate,(int) bage, (int) fage);
6767: oldm=oldms;savm=savms;
6768: varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
6769: free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
6770: /*}*/
6771: }
6772:
6773: fclose(ficresvpl);
6774:
6775: /*---------- End : free ----------------*/
6776: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
6777: free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
6778: } /* mle==-3 arrives here for freeing */
6779: endfree:
6780: free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
6781: free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
6782: free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
6783: free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
6784: free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
6785: free_matrix(covar,0,NCOVMAX,1,n);
6786: free_matrix(matcov,1,npar,1,npar);
6787: /*free_vector(delti,1,npar);*/
6788: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
6789: free_matrix(agev,1,maxwav,1,imx);
6790: free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
6791:
6792: free_ivector(ncodemax,1,NCOVMAX);
6793: free_ivector(Tvar,1,NCOVMAX);
6794: free_ivector(Tprod,1,NCOVMAX);
6795: free_ivector(Tvaraff,1,NCOVMAX);
6796: free_ivector(Tage,1,NCOVMAX);
6797:
6798: free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
6799: free_imatrix(codtab,1,100,1,10);
6800: fflush(fichtm);
6801: fflush(ficgp);
6802:
6803:
6804: if((nberr >0) || (nbwarn>0)){
6805: printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
6806: fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
6807: }else{
6808: printf("End of Imach\n");
6809: fprintf(ficlog,"End of Imach\n");
6810: }
6811: printf("See log file on %s\n",filelog);
6812: /* gettimeofday(&end_time, (struct timezone*)0);*/ /* after time */
6813: /*(void) gettimeofday(&end_time,&tzp);*/
6814: rend_time = time(NULL);
6815: end_time = *localtime(&rend_time);
6816: /* tml = *localtime(&end_time.tm_sec); */
6817: strcpy(strtend,asctime(&end_time));
6818: printf("Local time at start %s\nLocal time at end %s",strstart, strtend);
6819: fprintf(ficlog,"Local time at start %s\nLocal time at end %s\n",strstart, strtend);
6820: printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
6821:
6822: printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
6823: fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
6824: fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
6825: /* printf("Total time was %d uSec.\n", total_usecs);*/
6826: /* if(fileappend(fichtm,optionfilehtm)){ */
6827: fprintf(fichtm,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
6828: fclose(fichtm);
6829: fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
6830: fclose(fichtmcov);
6831: fclose(ficgp);
6832: fclose(ficlog);
6833: /*------ End -----------*/
6834:
6835:
6836: printf("Before Current directory %s!\n",pathcd);
6837: if(chdir(pathcd) != 0)
6838: printf("Can't move to directory %s!\n",path);
6839: if(getcwd(pathcd,MAXLINE) > 0)
6840: printf("Current directory %s!\n",pathcd);
6841: /*strcat(plotcmd,CHARSEPARATOR);*/
6842: sprintf(plotcmd,"gnuplot");
6843: #ifdef _WIN32
6844: sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
6845: #endif
6846: if(!stat(plotcmd,&info)){
6847: printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
6848: if(!stat(getenv("GNUPLOTBIN"),&info)){
6849: printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
6850: }else
6851: strcpy(pplotcmd,plotcmd);
6852: #ifdef __unix
6853: strcpy(plotcmd,GNUPLOTPROGRAM);
6854: if(!stat(plotcmd,&info)){
6855: printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
6856: }else
6857: strcpy(pplotcmd,plotcmd);
6858: #endif
6859: }else
6860: strcpy(pplotcmd,plotcmd);
6861:
6862: sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
6863: printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
6864:
6865: if((outcmd=system(plotcmd)) != 0){
6866: printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
6867: printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
6868: sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
6869: if((outcmd=system(plotcmd)) != 0)
6870: printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
6871: }
6872: printf(" Successful, please wait...");
6873: while (z[0] != 'q') {
6874: /* chdir(path); */
6875: printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
6876: scanf("%s",z);
6877: /* if (z[0] == 'c') system("./imach"); */
6878: if (z[0] == 'e') {
6879: #ifdef __APPLE__
6880: sprintf(pplotcmd, "open %s", optionfilehtm);
6881: #elif __linux
6882: sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
6883: #else
6884: sprintf(pplotcmd, "%s", optionfilehtm);
6885: #endif
6886: printf("Starting browser with: %s",pplotcmd);fflush(stdout);
6887: system(pplotcmd);
6888: }
6889: else if (z[0] == 'g') system(plotcmd);
6890: else if (z[0] == 'q') exit(0);
6891: }
6892: end:
6893: while (z[0] != 'q') {
6894: printf("\nType q for exiting: ");
6895: scanf("%s",z);
6896: }
6897: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>