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