1: /* $Id: imach.c,v 1.181 2015/02/11 23:22:24 brouard Exp $
2: $State: Exp $
3: $Log: imach.c,v $
4: Revision 1.181 2015/02/11 23:22:24 brouard
5: Summary: Comments on Powell added
6:
7: Author:
8:
9: Revision 1.180 2015/02/11 17:33:45 brouard
10: Summary: Finishing move from main to function (hpijx and prevalence_limit)
11:
12: Revision 1.179 2015/01/04 09:57:06 brouard
13: Summary: back to OS/X
14:
15: Revision 1.178 2015/01/04 09:35:48 brouard
16: *** empty log message ***
17:
18: Revision 1.177 2015/01/03 18:40:56 brouard
19: Summary: Still testing ilc32 on OSX
20:
21: Revision 1.176 2015/01/03 16:45:04 brouard
22: *** empty log message ***
23:
24: Revision 1.175 2015/01/03 16:33:42 brouard
25: *** empty log message ***
26:
27: Revision 1.174 2015/01/03 16:15:49 brouard
28: Summary: Still in cross-compilation
29:
30: Revision 1.173 2015/01/03 12:06:26 brouard
31: Summary: trying to detect cross-compilation
32:
33: Revision 1.172 2014/12/27 12:07:47 brouard
34: Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
35:
36: Revision 1.171 2014/12/23 13:26:59 brouard
37: Summary: Back from Visual C
38:
39: Still problem with utsname.h on Windows
40:
41: Revision 1.170 2014/12/23 11:17:12 brouard
42: Summary: Cleaning some \%% back to %%
43:
44: The escape was mandatory for a specific compiler (which one?), but too many warnings.
45:
46: Revision 1.169 2014/12/22 23:08:31 brouard
47: Summary: 0.98p
48:
49: Outputs some informations on compiler used, OS etc. Testing on different platforms.
50:
51: Revision 1.168 2014/12/22 15:17:42 brouard
52: Summary: update
53:
54: Revision 1.167 2014/12/22 13:50:56 brouard
55: Summary: Testing uname and compiler version and if compiled 32 or 64
56:
57: Testing on Linux 64
58:
59: Revision 1.166 2014/12/22 11:40:47 brouard
60: *** empty log message ***
61:
62: Revision 1.165 2014/12/16 11:20:36 brouard
63: Summary: After compiling on Visual C
64:
65: * imach.c (Module): Merging 1.61 to 1.162
66:
67: Revision 1.164 2014/12/16 10:52:11 brouard
68: Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
69:
70: * imach.c (Module): Merging 1.61 to 1.162
71:
72: Revision 1.163 2014/12/16 10:30:11 brouard
73: * imach.c (Module): Merging 1.61 to 1.162
74:
75: Revision 1.162 2014/09/25 11:43:39 brouard
76: Summary: temporary backup 0.99!
77:
78: Revision 1.1 2014/09/16 11:06:58 brouard
79: Summary: With some code (wrong) for nlopt
80:
81: Author:
82:
83: Revision 1.161 2014/09/15 20:41:41 brouard
84: Summary: Problem with macro SQR on Intel compiler
85:
86: Revision 1.160 2014/09/02 09:24:05 brouard
87: *** empty log message ***
88:
89: Revision 1.159 2014/09/01 10:34:10 brouard
90: Summary: WIN32
91: Author: Brouard
92:
93: Revision 1.158 2014/08/27 17:11:51 brouard
94: *** empty log message ***
95:
96: Revision 1.157 2014/08/27 16:26:55 brouard
97: Summary: Preparing windows Visual studio version
98: Author: Brouard
99:
100: In order to compile on Visual studio, time.h is now correct and time_t
101: and tm struct should be used. difftime should be used but sometimes I
102: just make the differences in raw time format (time(&now).
103: Trying to suppress #ifdef LINUX
104: Add xdg-open for __linux in order to open default browser.
105:
106: Revision 1.156 2014/08/25 20:10:10 brouard
107: *** empty log message ***
108:
109: Revision 1.155 2014/08/25 18:32:34 brouard
110: Summary: New compile, minor changes
111: Author: Brouard
112:
113: Revision 1.154 2014/06/20 17:32:08 brouard
114: Summary: Outputs now all graphs of convergence to period prevalence
115:
116: Revision 1.153 2014/06/20 16:45:46 brouard
117: Summary: If 3 live state, convergence to period prevalence on same graph
118: Author: Brouard
119:
120: Revision 1.152 2014/06/18 17:54:09 brouard
121: Summary: open browser, use gnuplot on same dir than imach if not found in the path
122:
123: Revision 1.151 2014/06/18 16:43:30 brouard
124: *** empty log message ***
125:
126: Revision 1.150 2014/06/18 16:42:35 brouard
127: Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
128: Author: brouard
129:
130: Revision 1.149 2014/06/18 15:51:14 brouard
131: Summary: Some fixes in parameter files errors
132: Author: Nicolas Brouard
133:
134: Revision 1.148 2014/06/17 17:38:48 brouard
135: Summary: Nothing new
136: Author: Brouard
137:
138: Just a new packaging for OS/X version 0.98nS
139:
140: Revision 1.147 2014/06/16 10:33:11 brouard
141: *** empty log message ***
142:
143: Revision 1.146 2014/06/16 10:20:28 brouard
144: Summary: Merge
145: Author: Brouard
146:
147: Merge, before building revised version.
148:
149: Revision 1.145 2014/06/10 21:23:15 brouard
150: Summary: Debugging with valgrind
151: Author: Nicolas Brouard
152:
153: Lot of changes in order to output the results with some covariates
154: After the Edimburgh REVES conference 2014, it seems mandatory to
155: improve the code.
156: No more memory valgrind error but a lot has to be done in order to
157: continue the work of splitting the code into subroutines.
158: Also, decodemodel has been improved. Tricode is still not
159: optimal. nbcode should be improved. Documentation has been added in
160: the source code.
161:
162: Revision 1.143 2014/01/26 09:45:38 brouard
163: Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
164:
165: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
166: (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
167:
168: Revision 1.142 2014/01/26 03:57:36 brouard
169: Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
170:
171: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
172:
173: Revision 1.141 2014/01/26 02:42:01 brouard
174: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
175:
176: Revision 1.140 2011/09/02 10:37:54 brouard
177: Summary: times.h is ok with mingw32 now.
178:
179: Revision 1.139 2010/06/14 07:50:17 brouard
180: After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
181: I remember having already fixed agemin agemax which are pointers now but not cvs saved.
182:
183: Revision 1.138 2010/04/30 18:19:40 brouard
184: *** empty log message ***
185:
186: Revision 1.137 2010/04/29 18:11:38 brouard
187: (Module): Checking covariates for more complex models
188: than V1+V2. A lot of change to be done. Unstable.
189:
190: Revision 1.136 2010/04/26 20:30:53 brouard
191: (Module): merging some libgsl code. Fixing computation
192: of likelione (using inter/intrapolation if mle = 0) in order to
193: get same likelihood as if mle=1.
194: Some cleaning of code and comments added.
195:
196: Revision 1.135 2009/10/29 15:33:14 brouard
197: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
198:
199: Revision 1.134 2009/10/29 13:18:53 brouard
200: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
201:
202: Revision 1.133 2009/07/06 10:21:25 brouard
203: just nforces
204:
205: Revision 1.132 2009/07/06 08:22:05 brouard
206: Many tings
207:
208: Revision 1.131 2009/06/20 16:22:47 brouard
209: Some dimensions resccaled
210:
211: Revision 1.130 2009/05/26 06:44:34 brouard
212: (Module): Max Covariate is now set to 20 instead of 8. A
213: lot of cleaning with variables initialized to 0. Trying to make
214: V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
215:
216: Revision 1.129 2007/08/31 13:49:27 lievre
217: Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
218:
219: Revision 1.128 2006/06/30 13:02:05 brouard
220: (Module): Clarifications on computing e.j
221:
222: Revision 1.127 2006/04/28 18:11:50 brouard
223: (Module): Yes the sum of survivors was wrong since
224: imach-114 because nhstepm was no more computed in the age
225: loop. Now we define nhstepma in the age loop.
226: (Module): In order to speed up (in case of numerous covariates) we
227: compute health expectancies (without variances) in a first step
228: and then all the health expectancies with variances or standard
229: deviation (needs data from the Hessian matrices) which slows the
230: computation.
231: In the future we should be able to stop the program is only health
232: expectancies and graph are needed without standard deviations.
233:
234: Revision 1.126 2006/04/28 17:23:28 brouard
235: (Module): Yes the sum of survivors was wrong since
236: imach-114 because nhstepm was no more computed in the age
237: loop. Now we define nhstepma in the age loop.
238: Version 0.98h
239:
240: Revision 1.125 2006/04/04 15:20:31 lievre
241: Errors in calculation of health expectancies. Age was not initialized.
242: Forecasting file added.
243:
244: Revision 1.124 2006/03/22 17:13:53 lievre
245: Parameters are printed with %lf instead of %f (more numbers after the comma).
246: The log-likelihood is printed in the log file
247:
248: Revision 1.123 2006/03/20 10:52:43 brouard
249: * imach.c (Module): <title> changed, corresponds to .htm file
250: name. <head> headers where missing.
251:
252: * imach.c (Module): Weights can have a decimal point as for
253: English (a comma might work with a correct LC_NUMERIC environment,
254: otherwise the weight is truncated).
255: Modification of warning when the covariates values are not 0 or
256: 1.
257: Version 0.98g
258:
259: Revision 1.122 2006/03/20 09:45:41 brouard
260: (Module): Weights can have a decimal point as for
261: English (a comma might work with a correct LC_NUMERIC environment,
262: otherwise the weight is truncated).
263: Modification of warning when the covariates values are not 0 or
264: 1.
265: Version 0.98g
266:
267: Revision 1.121 2006/03/16 17:45:01 lievre
268: * imach.c (Module): Comments concerning covariates added
269:
270: * imach.c (Module): refinements in the computation of lli if
271: status=-2 in order to have more reliable computation if stepm is
272: not 1 month. Version 0.98f
273:
274: Revision 1.120 2006/03/16 15:10:38 lievre
275: (Module): refinements in the computation of lli if
276: status=-2 in order to have more reliable computation if stepm is
277: not 1 month. Version 0.98f
278:
279: Revision 1.119 2006/03/15 17:42:26 brouard
280: (Module): Bug if status = -2, the loglikelihood was
281: computed as likelihood omitting the logarithm. Version O.98e
282:
283: Revision 1.118 2006/03/14 18:20:07 brouard
284: (Module): varevsij Comments added explaining the second
285: table of variances if popbased=1 .
286: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
287: (Module): Function pstamp added
288: (Module): Version 0.98d
289:
290: Revision 1.117 2006/03/14 17:16:22 brouard
291: (Module): varevsij Comments added explaining the second
292: table of variances if popbased=1 .
293: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
294: (Module): Function pstamp added
295: (Module): Version 0.98d
296:
297: Revision 1.116 2006/03/06 10:29:27 brouard
298: (Module): Variance-covariance wrong links and
299: varian-covariance of ej. is needed (Saito).
300:
301: Revision 1.115 2006/02/27 12:17:45 brouard
302: (Module): One freematrix added in mlikeli! 0.98c
303:
304: Revision 1.114 2006/02/26 12:57:58 brouard
305: (Module): Some improvements in processing parameter
306: filename with strsep.
307:
308: Revision 1.113 2006/02/24 14:20:24 brouard
309: (Module): Memory leaks checks with valgrind and:
310: datafile was not closed, some imatrix were not freed and on matrix
311: allocation too.
312:
313: Revision 1.112 2006/01/30 09:55:26 brouard
314: (Module): Back to gnuplot.exe instead of wgnuplot.exe
315:
316: Revision 1.111 2006/01/25 20:38:18 brouard
317: (Module): Lots of cleaning and bugs added (Gompertz)
318: (Module): Comments can be added in data file. Missing date values
319: can be a simple dot '.'.
320:
321: Revision 1.110 2006/01/25 00:51:50 brouard
322: (Module): Lots of cleaning and bugs added (Gompertz)
323:
324: Revision 1.109 2006/01/24 19:37:15 brouard
325: (Module): Comments (lines starting with a #) are allowed in data.
326:
327: Revision 1.108 2006/01/19 18:05:42 lievre
328: Gnuplot problem appeared...
329: To be fixed
330:
331: Revision 1.107 2006/01/19 16:20:37 brouard
332: Test existence of gnuplot in imach path
333:
334: Revision 1.106 2006/01/19 13:24:36 brouard
335: Some cleaning and links added in html output
336:
337: Revision 1.105 2006/01/05 20:23:19 lievre
338: *** empty log message ***
339:
340: Revision 1.104 2005/09/30 16:11:43 lievre
341: (Module): sump fixed, loop imx fixed, and simplifications.
342: (Module): If the status is missing at the last wave but we know
343: that the person is alive, then we can code his/her status as -2
344: (instead of missing=-1 in earlier versions) and his/her
345: contributions to the likelihood is 1 - Prob of dying from last
346: health status (= 1-p13= p11+p12 in the easiest case of somebody in
347: the healthy state at last known wave). Version is 0.98
348:
349: Revision 1.103 2005/09/30 15:54:49 lievre
350: (Module): sump fixed, loop imx fixed, and simplifications.
351:
352: Revision 1.102 2004/09/15 17:31:30 brouard
353: Add the possibility to read data file including tab characters.
354:
355: Revision 1.101 2004/09/15 10:38:38 brouard
356: Fix on curr_time
357:
358: Revision 1.100 2004/07/12 18:29:06 brouard
359: Add version for Mac OS X. Just define UNIX in Makefile
360:
361: Revision 1.99 2004/06/05 08:57:40 brouard
362: *** empty log message ***
363:
364: Revision 1.98 2004/05/16 15:05:56 brouard
365: New version 0.97 . First attempt to estimate force of mortality
366: directly from the data i.e. without the need of knowing the health
367: state at each age, but using a Gompertz model: log u =a + b*age .
368: This is the basic analysis of mortality and should be done before any
369: other analysis, in order to test if the mortality estimated from the
370: cross-longitudinal survey is different from the mortality estimated
371: from other sources like vital statistic data.
372:
373: The same imach parameter file can be used but the option for mle should be -3.
374:
375: Agnès, who wrote this part of the code, tried to keep most of the
376: former routines in order to include the new code within the former code.
377:
378: The output is very simple: only an estimate of the intercept and of
379: the slope with 95% confident intervals.
380:
381: Current limitations:
382: A) Even if you enter covariates, i.e. with the
383: model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
384: B) There is no computation of Life Expectancy nor Life Table.
385:
386: Revision 1.97 2004/02/20 13:25:42 lievre
387: Version 0.96d. Population forecasting command line is (temporarily)
388: suppressed.
389:
390: Revision 1.96 2003/07/15 15:38:55 brouard
391: * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
392: rewritten within the same printf. Workaround: many printfs.
393:
394: Revision 1.95 2003/07/08 07:54:34 brouard
395: * imach.c (Repository):
396: (Repository): Using imachwizard code to output a more meaningful covariance
397: matrix (cov(a12,c31) instead of numbers.
398:
399: Revision 1.94 2003/06/27 13:00:02 brouard
400: Just cleaning
401:
402: Revision 1.93 2003/06/25 16:33:55 brouard
403: (Module): On windows (cygwin) function asctime_r doesn't
404: exist so I changed back to asctime which exists.
405: (Module): Version 0.96b
406:
407: Revision 1.92 2003/06/25 16:30:45 brouard
408: (Module): On windows (cygwin) function asctime_r doesn't
409: exist so I changed back to asctime which exists.
410:
411: Revision 1.91 2003/06/25 15:30:29 brouard
412: * imach.c (Repository): Duplicated warning errors corrected.
413: (Repository): Elapsed time after each iteration is now output. It
414: helps to forecast when convergence will be reached. Elapsed time
415: is stamped in powell. We created a new html file for the graphs
416: concerning matrix of covariance. It has extension -cov.htm.
417:
418: Revision 1.90 2003/06/24 12:34:15 brouard
419: (Module): Some bugs corrected for windows. Also, when
420: mle=-1 a template is output in file "or"mypar.txt with the design
421: of the covariance matrix to be input.
422:
423: Revision 1.89 2003/06/24 12:30:52 brouard
424: (Module): Some bugs corrected for windows. Also, when
425: mle=-1 a template is output in file "or"mypar.txt with the design
426: of the covariance matrix to be input.
427:
428: Revision 1.88 2003/06/23 17:54:56 brouard
429: * 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.
430:
431: Revision 1.87 2003/06/18 12:26:01 brouard
432: Version 0.96
433:
434: Revision 1.86 2003/06/17 20:04:08 brouard
435: (Module): Change position of html and gnuplot routines and added
436: routine fileappend.
437:
438: Revision 1.85 2003/06/17 13:12:43 brouard
439: * imach.c (Repository): Check when date of death was earlier that
440: current date of interview. It may happen when the death was just
441: prior to the death. In this case, dh was negative and likelihood
442: was wrong (infinity). We still send an "Error" but patch by
443: assuming that the date of death was just one stepm after the
444: interview.
445: (Repository): Because some people have very long ID (first column)
446: we changed int to long in num[] and we added a new lvector for
447: memory allocation. But we also truncated to 8 characters (left
448: truncation)
449: (Repository): No more line truncation errors.
450:
451: Revision 1.84 2003/06/13 21:44:43 brouard
452: * imach.c (Repository): Replace "freqsummary" at a correct
453: place. It differs from routine "prevalence" which may be called
454: many times. Probs is memory consuming and must be used with
455: parcimony.
456: Version 0.95a3 (should output exactly the same maximization than 0.8a2)
457:
458: Revision 1.83 2003/06/10 13:39:11 lievre
459: *** empty log message ***
460:
461: Revision 1.82 2003/06/05 15:57:20 brouard
462: Add log in imach.c and fullversion number is now printed.
463:
464: */
465: /*
466: Interpolated Markov Chain
467:
468: Short summary of the programme:
469:
470: This program computes Healthy Life Expectancies from
471: cross-longitudinal data. Cross-longitudinal data consist in: -1- a
472: first survey ("cross") where individuals from different ages are
473: interviewed on their health status or degree of disability (in the
474: case of a health survey which is our main interest) -2- at least a
475: second wave of interviews ("longitudinal") which measure each change
476: (if any) in individual health status. Health expectancies are
477: computed from the time spent in each health state according to a
478: model. More health states you consider, more time is necessary to reach the
479: Maximum Likelihood of the parameters involved in the model. The
480: simplest model is the multinomial logistic model where pij is the
481: probability to be observed in state j at the second wave
482: conditional to be observed in state i at the first wave. Therefore
483: the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
484: 'age' is age and 'sex' is a covariate. If you want to have a more
485: complex model than "constant and age", you should modify the program
486: where the markup *Covariates have to be included here again* invites
487: you to do it. More covariates you add, slower the
488: convergence.
489:
490: The advantage of this computer programme, compared to a simple
491: multinomial logistic model, is clear when the delay between waves is not
492: identical for each individual. Also, if a individual missed an
493: intermediate interview, the information is lost, but taken into
494: account using an interpolation or extrapolation.
495:
496: hPijx is the probability to be observed in state i at age x+h
497: conditional to the observed state i at age x. The delay 'h' can be
498: split into an exact number (nh*stepm) of unobserved intermediate
499: states. This elementary transition (by month, quarter,
500: semester or year) is modelled as a multinomial logistic. The hPx
501: matrix is simply the matrix product of nh*stepm elementary matrices
502: and the contribution of each individual to the likelihood is simply
503: hPijx.
504:
505: Also this programme outputs the covariance matrix of the parameters but also
506: of the life expectancies. It also computes the period (stable) prevalence.
507:
508: Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
509: Institut national d'études démographiques, Paris.
510: This software have been partly granted by Euro-REVES, a concerted action
511: from the European Union.
512: It is copyrighted identically to a GNU software product, ie programme and
513: software can be distributed freely for non commercial use. Latest version
514: can be accessed at http://euroreves.ined.fr/imach .
515:
516: Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
517: or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
518:
519: **********************************************************************/
520: /*
521: main
522: read parameterfile
523: read datafile
524: concatwav
525: freqsummary
526: if (mle >= 1)
527: mlikeli
528: print results files
529: if mle==1
530: computes hessian
531: read end of parameter file: agemin, agemax, bage, fage, estepm
532: begin-prev-date,...
533: open gnuplot file
534: open html file
535: period (stable) prevalence | pl_nom 1-1 2-2 etc by covariate
536: for age prevalim() | #****** V1=0 V2=1 V3=1 V4=0 ******
537: | 65 1 0 2 1 3 1 4 0 0.96326 0.03674
538: freexexit2 possible for memory heap.
539:
540: h Pij x | pij_nom ficrestpij
541: # Cov Agex agex+h hpijx with i,j= 1-1 1-2 1-3 2-1 2-2 2-3
542: 1 85 85 1.00000 0.00000 0.00000 0.00000 1.00000 0.00000
543: 1 85 86 0.68299 0.22291 0.09410 0.71093 0.00000 0.28907
544:
545: 1 65 99 0.00364 0.00322 0.99314 0.00350 0.00310 0.99340
546: 1 65 100 0.00214 0.00204 0.99581 0.00206 0.00196 0.99597
547: variance of p one-step probabilities varprob | prob_nom ficresprob #One-step probabilities and stand. devi in ()
548: Standard deviation of one-step probabilities | probcor_nom ficresprobcor #One-step probabilities and correlation matrix
549: Matrix of variance covariance of one-step probabilities | probcov_nom ficresprobcov #One-step probabilities and covariance matrix
550:
551: forecasting if prevfcast==1 prevforecast call prevalence()
552: health expectancies
553: Variance-covariance of DFLE
554: prevalence()
555: movingaverage()
556: varevsij()
557: if popbased==1 varevsij(,popbased)
558: total life expectancies
559: Variance of period (stable) prevalence
560: end
561: */
562:
563: #define POWELL /* Instead of NLOPT */
564: #define POWELLDIRECT /* Directest to decide new direction instead of Powell test */
565:
566: #include <math.h>
567: #include <stdio.h>
568: #include <stdlib.h>
569: #include <string.h>
570:
571: #ifdef _WIN32
572: #include <io.h>
573: #include <windows.h>
574: #include <tchar.h>
575: #else
576: #include <unistd.h>
577: #endif
578:
579: #include <limits.h>
580: #include <sys/types.h>
581:
582: #if defined(__GNUC__)
583: #include <sys/utsname.h> /* Doesn't work on Windows */
584: #endif
585:
586: #include <sys/stat.h>
587: #include <errno.h>
588: /* extern int errno; */
589:
590: /* #ifdef LINUX */
591: /* #include <time.h> */
592: /* #include "timeval.h" */
593: /* #else */
594: /* #include <sys/time.h> */
595: /* #endif */
596:
597: #include <time.h>
598:
599: #ifdef GSL
600: #include <gsl/gsl_errno.h>
601: #include <gsl/gsl_multimin.h>
602: #endif
603:
604:
605: #ifdef NLOPT
606: #include <nlopt.h>
607: typedef struct {
608: double (* function)(double [] );
609: } myfunc_data ;
610: #endif
611:
612: /* #include <libintl.h> */
613: /* #define _(String) gettext (String) */
614:
615: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
616:
617: #define GNUPLOTPROGRAM "gnuplot"
618: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
619: #define FILENAMELENGTH 132
620:
621: #define GLOCK_ERROR_NOPATH -1 /* empty path */
622: #define GLOCK_ERROR_GETCWD -2 /* cannot get cwd */
623:
624: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
625: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
626:
627: #define NINTERVMAX 8
628: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
629: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
630: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
631: #define codtabm(h,k) 1 & (h-1) >> (k-1) ;
632: #define MAXN 20000
633: #define YEARM 12. /**< Number of months per year */
634: #define AGESUP 130
635: #define AGEBASE 40
636: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
637: #ifdef _WIN32
638: #define DIRSEPARATOR '\\'
639: #define CHARSEPARATOR "\\"
640: #define ODIRSEPARATOR '/'
641: #else
642: #define DIRSEPARATOR '/'
643: #define CHARSEPARATOR "/"
644: #define ODIRSEPARATOR '\\'
645: #endif
646:
647: /* $Id: imach.c,v 1.181 2015/02/11 23:22:24 brouard Exp $ */
648: /* $State: Exp $ */
649:
650: char version[]="Imach version 0.98p, Février 2015,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015";
651: char fullversion[]="$Revision: 1.181 $ $Date: 2015/02/11 23:22:24 $";
652: char strstart[80];
653: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
654: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings */
655: int nvar=0, nforce=0; /* Number of variables, number of forces */
656: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
657: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
658: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
659: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
660: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
661: int cptcovprodnoage=0; /**< Number of covariate products without age */
662: int cptcoveff=0; /* Total number of covariates to vary for printing results */
663: int cptcov=0; /* Working variable */
664: int npar=NPARMAX;
665: int nlstate=2; /* Number of live states */
666: int ndeath=1; /* Number of dead states */
667: int ncovmodel=0, ncovcol=0; /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
668: int popbased=0;
669:
670: int *wav; /* Number of waves for this individuual 0 is possible */
671: int maxwav=0; /* Maxim number of waves */
672: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
673: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */
674: int gipmx=0, gsw=0; /* Global variables on the number of contributions
675: to the likelihood and the sum of weights (done by funcone)*/
676: int mle=1, weightopt=0;
677: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
678: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
679: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
680: * wave mi and wave mi+1 is not an exact multiple of stepm. */
681: int countcallfunc=0; /* Count the number of calls to func */
682: double jmean=1; /* Mean space between 2 waves */
683: double **matprod2(); /* test */
684: double **oldm, **newm, **savm; /* Working pointers to matrices */
685: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
686: /*FILE *fic ; */ /* Used in readdata only */
687: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
688: FILE *ficlog, *ficrespow;
689: int globpr=0; /* Global variable for printing or not */
690: double fretone; /* Only one call to likelihood */
691: long ipmx=0; /* Number of contributions */
692: double sw; /* Sum of weights */
693: char filerespow[FILENAMELENGTH];
694: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
695: FILE *ficresilk;
696: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
697: FILE *ficresprobmorprev;
698: FILE *fichtm, *fichtmcov; /* Html File */
699: FILE *ficreseij;
700: char filerese[FILENAMELENGTH];
701: FILE *ficresstdeij;
702: char fileresstde[FILENAMELENGTH];
703: FILE *ficrescveij;
704: char filerescve[FILENAMELENGTH];
705: FILE *ficresvij;
706: char fileresv[FILENAMELENGTH];
707: FILE *ficresvpl;
708: char fileresvpl[FILENAMELENGTH];
709: char title[MAXLINE];
710: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH], filerespl[FILENAMELENGTH];
711: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
712: char tmpout[FILENAMELENGTH], tmpout2[FILENAMELENGTH];
713: char command[FILENAMELENGTH];
714: int outcmd=0;
715:
716: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
717:
718: char filelog[FILENAMELENGTH]; /* Log file */
719: char filerest[FILENAMELENGTH];
720: char fileregp[FILENAMELENGTH];
721: char popfile[FILENAMELENGTH];
722:
723: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
724:
725: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
726: /* struct timezone tzp; */
727: /* extern int gettimeofday(); */
728: struct tm tml, *gmtime(), *localtime();
729:
730: extern time_t time();
731:
732: struct tm start_time, end_time, curr_time, last_time, forecast_time;
733: time_t rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
734: struct tm tm;
735:
736: char strcurr[80], strfor[80];
737:
738: char *endptr;
739: long lval;
740: double dval;
741:
742: #define NR_END 1
743: #define FREE_ARG char*
744: #define FTOL 1.0e-10
745:
746: #define NRANSI
747: #define ITMAX 200
748:
749: #define TOL 2.0e-4
750:
751: #define CGOLD 0.3819660
752: #define ZEPS 1.0e-10
753: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
754:
755: #define GOLD 1.618034
756: #define GLIMIT 100.0
757: #define TINY 1.0e-20
758:
759: static double maxarg1,maxarg2;
760: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
761: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
762:
763: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
764: #define rint(a) floor(a+0.5)
765: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
766: /* #define mytinydouble 1.0e-16 */
767: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
768: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
769: /* static double dsqrarg; */
770: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
771: static double sqrarg;
772: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
773: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
774: int agegomp= AGEGOMP;
775:
776: int imx;
777: int stepm=1;
778: /* Stepm, step in month: minimum step interpolation*/
779:
780: int estepm;
781: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
782:
783: int m,nb;
784: long *num;
785: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
786: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
787: double **pmmij, ***probs;
788: double *ageexmed,*agecens;
789: double dateintmean=0;
790:
791: double *weight;
792: int **s; /* Status */
793: double *agedc;
794: double **covar; /**< covar[j,i], value of jth covariate for individual i,
795: * covar=matrix(0,NCOVMAX,1,n);
796: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; */
797: double idx;
798: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
799: int *Ndum; /** Freq of modality (tricode */
800: int **codtab; /**< codtab=imatrix(1,100,1,10); */
801: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
802: double *lsurv, *lpop, *tpop;
803:
804: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
805: double ftolhess; /**< Tolerance for computing hessian */
806:
807: /**************** split *************************/
808: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
809: {
810: /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
811: the name of the file (name), its extension only (ext) and its first part of the name (finame)
812: */
813: char *ss; /* pointer */
814: int l1, l2; /* length counters */
815:
816: l1 = strlen(path ); /* length of path */
817: if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
818: ss= strrchr( path, DIRSEPARATOR ); /* find last / */
819: if ( ss == NULL ) { /* no directory, so determine current directory */
820: strcpy( name, path ); /* we got the fullname name because no directory */
821: /*if(strrchr(path, ODIRSEPARATOR )==NULL)
822: printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
823: /* get current working directory */
824: /* extern char* getcwd ( char *buf , int len);*/
825: if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
826: return( GLOCK_ERROR_GETCWD );
827: }
828: /* got dirc from getcwd*/
829: printf(" DIRC = %s \n",dirc);
830: } else { /* strip direcotry from path */
831: ss++; /* after this, the filename */
832: l2 = strlen( ss ); /* length of filename */
833: if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
834: strcpy( name, ss ); /* save file name */
835: strncpy( dirc, path, l1 - l2 ); /* now the directory */
836: dirc[l1-l2] = 0; /* add zero */
837: printf(" DIRC2 = %s \n",dirc);
838: }
839: /* We add a separator at the end of dirc if not exists */
840: l1 = strlen( dirc ); /* length of directory */
841: if( dirc[l1-1] != DIRSEPARATOR ){
842: dirc[l1] = DIRSEPARATOR;
843: dirc[l1+1] = 0;
844: printf(" DIRC3 = %s \n",dirc);
845: }
846: ss = strrchr( name, '.' ); /* find last / */
847: if (ss >0){
848: ss++;
849: strcpy(ext,ss); /* save extension */
850: l1= strlen( name);
851: l2= strlen(ss)+1;
852: strncpy( finame, name, l1-l2);
853: finame[l1-l2]= 0;
854: }
855:
856: return( 0 ); /* we're done */
857: }
858:
859:
860: /******************************************/
861:
862: void replace_back_to_slash(char *s, char*t)
863: {
864: int i;
865: int lg=0;
866: i=0;
867: lg=strlen(t);
868: for(i=0; i<= lg; i++) {
869: (s[i] = t[i]);
870: if (t[i]== '\\') s[i]='/';
871: }
872: }
873:
874: char *trimbb(char *out, char *in)
875: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
876: char *s;
877: s=out;
878: while (*in != '\0'){
879: while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
880: in++;
881: }
882: *out++ = *in++;
883: }
884: *out='\0';
885: return s;
886: }
887:
888: char *cutl(char *blocc, char *alocc, char *in, char occ)
889: {
890: /* cuts string in into blocc and alocc where blocc ends before first occurence of char 'occ'
891: and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
892: gives blocc="abcdef2ghi" and alocc="j".
893: If occ is not found blocc is null and alocc is equal to in. Returns blocc
894: */
895: char *s, *t;
896: t=in;s=in;
897: while ((*in != occ) && (*in != '\0')){
898: *alocc++ = *in++;
899: }
900: if( *in == occ){
901: *(alocc)='\0';
902: s=++in;
903: }
904:
905: if (s == t) {/* occ not found */
906: *(alocc-(in-s))='\0';
907: in=s;
908: }
909: while ( *in != '\0'){
910: *blocc++ = *in++;
911: }
912:
913: *blocc='\0';
914: return t;
915: }
916: char *cutv(char *blocc, char *alocc, char *in, char occ)
917: {
918: /* cuts string in into blocc and alocc where blocc ends before last occurence of char 'occ'
919: and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
920: gives blocc="abcdef2ghi" and alocc="j".
921: If occ is not found blocc is null and alocc is equal to in. Returns alocc
922: */
923: char *s, *t;
924: t=in;s=in;
925: while (*in != '\0'){
926: while( *in == occ){
927: *blocc++ = *in++;
928: s=in;
929: }
930: *blocc++ = *in++;
931: }
932: if (s == t) /* occ not found */
933: *(blocc-(in-s))='\0';
934: else
935: *(blocc-(in-s)-1)='\0';
936: in=s;
937: while ( *in != '\0'){
938: *alocc++ = *in++;
939: }
940:
941: *alocc='\0';
942: return s;
943: }
944:
945: int nbocc(char *s, char occ)
946: {
947: int i,j=0;
948: int lg=20;
949: i=0;
950: lg=strlen(s);
951: for(i=0; i<= lg; i++) {
952: if (s[i] == occ ) j++;
953: }
954: return j;
955: }
956:
957: /* void cutv(char *u,char *v, char*t, char occ) */
958: /* { */
959: /* /\* cuts string t into u and v where u ends before last occurence of char 'occ' */
960: /* and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
961: /* gives u="abcdef2ghi" and v="j" *\/ */
962: /* int i,lg,j,p=0; */
963: /* i=0; */
964: /* lg=strlen(t); */
965: /* for(j=0; j<=lg-1; j++) { */
966: /* if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
967: /* } */
968:
969: /* for(j=0; j<p; j++) { */
970: /* (u[j] = t[j]); */
971: /* } */
972: /* u[p]='\0'; */
973:
974: /* for(j=0; j<= lg; j++) { */
975: /* if (j>=(p+1))(v[j-p-1] = t[j]); */
976: /* } */
977: /* } */
978:
979: #ifdef _WIN32
980: char * strsep(char **pp, const char *delim)
981: {
982: char *p, *q;
983:
984: if ((p = *pp) == NULL)
985: return 0;
986: if ((q = strpbrk (p, delim)) != NULL)
987: {
988: *pp = q + 1;
989: *q = '\0';
990: }
991: else
992: *pp = 0;
993: return p;
994: }
995: #endif
996:
997: /********************** nrerror ********************/
998:
999: void nrerror(char error_text[])
1000: {
1001: fprintf(stderr,"ERREUR ...\n");
1002: fprintf(stderr,"%s\n",error_text);
1003: exit(EXIT_FAILURE);
1004: }
1005: /*********************** vector *******************/
1006: double *vector(int nl, int nh)
1007: {
1008: double *v;
1009: v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
1010: if (!v) nrerror("allocation failure in vector");
1011: return v-nl+NR_END;
1012: }
1013:
1014: /************************ free vector ******************/
1015: void free_vector(double*v, int nl, int nh)
1016: {
1017: free((FREE_ARG)(v+nl-NR_END));
1018: }
1019:
1020: /************************ivector *******************************/
1021: int *ivector(long nl,long nh)
1022: {
1023: int *v;
1024: v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
1025: if (!v) nrerror("allocation failure in ivector");
1026: return v-nl+NR_END;
1027: }
1028:
1029: /******************free ivector **************************/
1030: void free_ivector(int *v, long nl, long nh)
1031: {
1032: free((FREE_ARG)(v+nl-NR_END));
1033: }
1034:
1035: /************************lvector *******************************/
1036: long *lvector(long nl,long nh)
1037: {
1038: long *v;
1039: v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
1040: if (!v) nrerror("allocation failure in ivector");
1041: return v-nl+NR_END;
1042: }
1043:
1044: /******************free lvector **************************/
1045: void free_lvector(long *v, long nl, long nh)
1046: {
1047: free((FREE_ARG)(v+nl-NR_END));
1048: }
1049:
1050: /******************* imatrix *******************************/
1051: int **imatrix(long nrl, long nrh, long ncl, long nch)
1052: /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
1053: {
1054: long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
1055: int **m;
1056:
1057: /* allocate pointers to rows */
1058: m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
1059: if (!m) nrerror("allocation failure 1 in matrix()");
1060: m += NR_END;
1061: m -= nrl;
1062:
1063:
1064: /* allocate rows and set pointers to them */
1065: m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
1066: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1067: m[nrl] += NR_END;
1068: m[nrl] -= ncl;
1069:
1070: for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
1071:
1072: /* return pointer to array of pointers to rows */
1073: return m;
1074: }
1075:
1076: /****************** free_imatrix *************************/
1077: void free_imatrix(m,nrl,nrh,ncl,nch)
1078: int **m;
1079: long nch,ncl,nrh,nrl;
1080: /* free an int matrix allocated by imatrix() */
1081: {
1082: free((FREE_ARG) (m[nrl]+ncl-NR_END));
1083: free((FREE_ARG) (m+nrl-NR_END));
1084: }
1085:
1086: /******************* matrix *******************************/
1087: double **matrix(long nrl, long nrh, long ncl, long nch)
1088: {
1089: long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
1090: double **m;
1091:
1092: m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1093: if (!m) nrerror("allocation failure 1 in matrix()");
1094: m += NR_END;
1095: m -= nrl;
1096:
1097: m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1098: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1099: m[nrl] += NR_END;
1100: m[nrl] -= ncl;
1101:
1102: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1103: return m;
1104: /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
1105: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
1106: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1107: */
1108: }
1109:
1110: /*************************free matrix ************************/
1111: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
1112: {
1113: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1114: free((FREE_ARG)(m+nrl-NR_END));
1115: }
1116:
1117: /******************* ma3x *******************************/
1118: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
1119: {
1120: long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
1121: double ***m;
1122:
1123: m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1124: if (!m) nrerror("allocation failure 1 in matrix()");
1125: m += NR_END;
1126: m -= nrl;
1127:
1128: m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1129: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1130: m[nrl] += NR_END;
1131: m[nrl] -= ncl;
1132:
1133: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1134:
1135: m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
1136: if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
1137: m[nrl][ncl] += NR_END;
1138: m[nrl][ncl] -= nll;
1139: for (j=ncl+1; j<=nch; j++)
1140: m[nrl][j]=m[nrl][j-1]+nlay;
1141:
1142: for (i=nrl+1; i<=nrh; i++) {
1143: m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
1144: for (j=ncl+1; j<=nch; j++)
1145: m[i][j]=m[i][j-1]+nlay;
1146: }
1147: return m;
1148: /* gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
1149: &(m[i][j][k]) <=> *((*(m+i) + j)+k)
1150: */
1151: }
1152:
1153: /*************************free ma3x ************************/
1154: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
1155: {
1156: free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
1157: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1158: free((FREE_ARG)(m+nrl-NR_END));
1159: }
1160:
1161: /*************** function subdirf ***********/
1162: char *subdirf(char fileres[])
1163: {
1164: /* Caution optionfilefiname is hidden */
1165: strcpy(tmpout,optionfilefiname);
1166: strcat(tmpout,"/"); /* Add to the right */
1167: strcat(tmpout,fileres);
1168: return tmpout;
1169: }
1170:
1171: /*************** function subdirf2 ***********/
1172: char *subdirf2(char fileres[], char *preop)
1173: {
1174:
1175: /* Caution optionfilefiname is hidden */
1176: strcpy(tmpout,optionfilefiname);
1177: strcat(tmpout,"/");
1178: strcat(tmpout,preop);
1179: strcat(tmpout,fileres);
1180: return tmpout;
1181: }
1182:
1183: /*************** function subdirf3 ***********/
1184: char *subdirf3(char fileres[], char *preop, char *preop2)
1185: {
1186:
1187: /* Caution optionfilefiname is hidden */
1188: strcpy(tmpout,optionfilefiname);
1189: strcat(tmpout,"/");
1190: strcat(tmpout,preop);
1191: strcat(tmpout,preop2);
1192: strcat(tmpout,fileres);
1193: return tmpout;
1194: }
1195:
1196: char *asc_diff_time(long time_sec, char ascdiff[])
1197: {
1198: long sec_left, days, hours, minutes;
1199: days = (time_sec) / (60*60*24);
1200: sec_left = (time_sec) % (60*60*24);
1201: hours = (sec_left) / (60*60) ;
1202: sec_left = (sec_left) %(60*60);
1203: minutes = (sec_left) /60;
1204: sec_left = (sec_left) % (60);
1205: sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);
1206: return ascdiff;
1207: }
1208:
1209: /***************** f1dim *************************/
1210: extern int ncom;
1211: extern double *pcom,*xicom;
1212: extern double (*nrfunc)(double []);
1213:
1214: double f1dim(double x)
1215: {
1216: int j;
1217: double f;
1218: double *xt;
1219:
1220: xt=vector(1,ncom);
1221: for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
1222: f=(*nrfunc)(xt);
1223: free_vector(xt,1,ncom);
1224: return f;
1225: }
1226:
1227: /*****************brent *************************/
1228: double brent(double ax, double bx, double cx, double (*f)(double), double tol, double *xmin)
1229: {
1230: int iter;
1231: double a,b,d,etemp;
1232: double fu=0,fv,fw,fx;
1233: double ftemp=0.;
1234: double p,q,r,tol1,tol2,u,v,w,x,xm;
1235: double e=0.0;
1236:
1237: a=(ax < cx ? ax : cx);
1238: b=(ax > cx ? ax : cx);
1239: x=w=v=bx;
1240: fw=fv=fx=(*f)(x);
1241: for (iter=1;iter<=ITMAX;iter++) {
1242: xm=0.5*(a+b);
1243: tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
1244: /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
1245: printf(".");fflush(stdout);
1246: fprintf(ficlog,".");fflush(ficlog);
1247: #ifdef DEBUGBRENT
1248: 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);
1249: 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);
1250: /* if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
1251: #endif
1252: if (fabs(x-xm) <= (tol2-0.5*(b-a))){
1253: *xmin=x;
1254: return fx;
1255: }
1256: ftemp=fu;
1257: if (fabs(e) > tol1) {
1258: r=(x-w)*(fx-fv);
1259: q=(x-v)*(fx-fw);
1260: p=(x-v)*q-(x-w)*r;
1261: q=2.0*(q-r);
1262: if (q > 0.0) p = -p;
1263: q=fabs(q);
1264: etemp=e;
1265: e=d;
1266: if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
1267: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1268: else {
1269: d=p/q;
1270: u=x+d;
1271: if (u-a < tol2 || b-u < tol2)
1272: d=SIGN(tol1,xm-x);
1273: }
1274: } else {
1275: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1276: }
1277: u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
1278: fu=(*f)(u);
1279: if (fu <= fx) {
1280: if (u >= x) a=x; else b=x;
1281: SHFT(v,w,x,u)
1282: SHFT(fv,fw,fx,fu)
1283: } else {
1284: if (u < x) a=u; else b=u;
1285: if (fu <= fw || w == x) {
1286: v=w;
1287: w=u;
1288: fv=fw;
1289: fw=fu;
1290: } else if (fu <= fv || v == x || v == w) {
1291: v=u;
1292: fv=fu;
1293: }
1294: }
1295: }
1296: nrerror("Too many iterations in brent");
1297: *xmin=x;
1298: return fx;
1299: }
1300:
1301: /****************** mnbrak ***********************/
1302:
1303: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
1304: double (*func)(double))
1305: {
1306: double ulim,u,r,q, dum;
1307: double fu;
1308:
1309: *fa=(*func)(*ax);
1310: *fb=(*func)(*bx);
1311: if (*fb > *fa) {
1312: SHFT(dum,*ax,*bx,dum)
1313: SHFT(dum,*fb,*fa,dum)
1314: }
1315: *cx=(*bx)+GOLD*(*bx-*ax);
1316: *fc=(*func)(*cx);
1317: while (*fb > *fc) { /* Declining fa, fb, fc */
1318: r=(*bx-*ax)*(*fb-*fc);
1319: q=(*bx-*cx)*(*fb-*fa);
1320: u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
1321: (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscisse of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
1322: ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscisse where function can be evaluated */
1323: if ((*bx-u)*(u-*cx) > 0.0) { /* if u between b and c */
1324: fu=(*func)(u);
1325: #ifdef DEBUG
1326: /* f(x)=A(x-u)**2+f(u) */
1327: double A, fparabu;
1328: A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
1329: fparabu= *fa - A*(*ax-u)*(*ax-u);
1330: printf("mnbrak (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf), (*u=%.12f, fu=%.12lf, fparabu=%.12f)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu, fparabu);
1331: fprintf(ficlog, "mnbrak (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf), (*u=%.12f, fu=%.12lf, fparabu=%.12f)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu, fparabu);
1332: #endif
1333: } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1334: fu=(*func)(u);
1335: if (fu < *fc) {
1336: SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
1337: SHFT(*fb,*fc,fu,(*func)(u))
1338: }
1339: } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1340: u=ulim;
1341: fu=(*func)(u);
1342: } else {
1343: u=(*cx)+GOLD*(*cx-*bx);
1344: fu=(*func)(u);
1345: }
1346: SHFT(*ax,*bx,*cx,u)
1347: SHFT(*fa,*fb,*fc,fu)
1348: }
1349: }
1350:
1351: /*************** linmin ************************/
1352: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
1353: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
1354: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
1355: the value of func at the returned location p . This is actually all accomplished by calling the
1356: routines mnbrak and brent .*/
1357: int ncom;
1358: double *pcom,*xicom;
1359: double (*nrfunc)(double []);
1360:
1361: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
1362: {
1363: double brent(double ax, double bx, double cx,
1364: double (*f)(double), double tol, double *xmin);
1365: double f1dim(double x);
1366: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
1367: double *fc, double (*func)(double));
1368: int j;
1369: double xx,xmin,bx,ax;
1370: double fx,fb,fa;
1371:
1372: ncom=n;
1373: pcom=vector(1,n);
1374: xicom=vector(1,n);
1375: nrfunc=func;
1376: for (j=1;j<=n;j++) {
1377: pcom[j]=p[j];
1378: xicom[j]=xi[j];
1379: }
1380: ax=0.0;
1381: xx=1.0;
1382: mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Find a bracket a,x,b in direction n=xi ie xicom */
1383: *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Find a minimum P+lambda n in that direction (lambdamin), with TOL between abscisses */
1384: #ifdef DEBUG
1385: printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1386: fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1387: #endif
1388: for (j=1;j<=n;j++) {
1389: xi[j] *= xmin;
1390: p[j] += xi[j];
1391: }
1392: free_vector(xicom,1,n);
1393: free_vector(pcom,1,n);
1394: }
1395:
1396:
1397: /*************** powell ************************/
1398: /*
1399: Minimization of a function func of n variables. Input consists of an initial starting point
1400: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
1401: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
1402: such that failure to decrease by more than this amount on one iteration signals doneness. On
1403: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
1404: function value at p , and iter is the number of iterations taken. The routine linmin is used.
1405: */
1406: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
1407: double (*func)(double []))
1408: {
1409: void linmin(double p[], double xi[], int n, double *fret,
1410: double (*func)(double []));
1411: int i,ibig,j;
1412: double del,t,*pt,*ptt,*xit;
1413: double directest;
1414: double fp,fptt;
1415: double *xits;
1416: int niterf, itmp;
1417:
1418: pt=vector(1,n);
1419: ptt=vector(1,n);
1420: xit=vector(1,n);
1421: xits=vector(1,n);
1422: *fret=(*func)(p);
1423: for (j=1;j<=n;j++) pt[j]=p[j];
1424: rcurr_time = time(NULL);
1425: for (*iter=1;;++(*iter)) {
1426: fp=(*fret);
1427: ibig=0;
1428: del=0.0;
1429: rlast_time=rcurr_time;
1430: /* (void) gettimeofday(&curr_time,&tzp); */
1431: rcurr_time = time(NULL);
1432: curr_time = *localtime(&rcurr_time);
1433: printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
1434: fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1435: /* fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1436: for (i=1;i<=n;i++) {
1437: printf(" %d %.12f",i, p[i]);
1438: fprintf(ficlog," %d %.12lf",i, p[i]);
1439: fprintf(ficrespow," %.12lf", p[i]);
1440: }
1441: printf("\n");
1442: fprintf(ficlog,"\n");
1443: fprintf(ficrespow,"\n");fflush(ficrespow);
1444: if(*iter <=3){
1445: tml = *localtime(&rcurr_time);
1446: strcpy(strcurr,asctime(&tml));
1447: rforecast_time=rcurr_time;
1448: itmp = strlen(strcurr);
1449: if(strcurr[itmp-1]=='\n') /* Windows outputs with a new line */
1450: strcurr[itmp-1]='\0';
1451: printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1452: fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1453: for(niterf=10;niterf<=30;niterf+=10){
1454: rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
1455: forecast_time = *localtime(&rforecast_time);
1456: strcpy(strfor,asctime(&forecast_time));
1457: itmp = strlen(strfor);
1458: if(strfor[itmp-1]=='\n')
1459: strfor[itmp-1]='\0';
1460: 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);
1461: 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);
1462: }
1463: }
1464: for (i=1;i<=n;i++) {
1465: for (j=1;j<=n;j++) xit[j]=xi[j][i];
1466: fptt=(*fret);
1467: #ifdef DEBUG
1468: printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1469: fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1470: #endif
1471: printf("%d",i);fflush(stdout);
1472: fprintf(ficlog,"%d",i);fflush(ficlog);
1473: linmin(p,xit,n,fret,func);
1474: if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions
1475: because that direction will be replaced unless the gain del is small
1476: in comparison with the 'probable' gain, mu^2, with the last average direction.
1477: Unless the n directions are conjugate some gain in the determinant may be obtained
1478: with the new direction.
1479: */
1480: del=fabs(fptt-(*fret));
1481: ibig=i;
1482: }
1483: #ifdef DEBUG
1484: printf("%d %.12e",i,(*fret));
1485: fprintf(ficlog,"%d %.12e",i,(*fret));
1486: for (j=1;j<=n;j++) {
1487: xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
1488: printf(" x(%d)=%.12e",j,xit[j]);
1489: fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1490: }
1491: for(j=1;j<=n;j++) {
1492: printf(" p(%d)=%.12e",j,p[j]);
1493: fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1494: }
1495: printf("\n");
1496: fprintf(ficlog,"\n");
1497: #endif
1498: } /* end i */
1499: if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
1500: #ifdef DEBUG
1501: int k[2],l;
1502: k[0]=1;
1503: k[1]=-1;
1504: printf("Max: %.12e",(*func)(p));
1505: fprintf(ficlog,"Max: %.12e",(*func)(p));
1506: for (j=1;j<=n;j++) {
1507: printf(" %.12e",p[j]);
1508: fprintf(ficlog," %.12e",p[j]);
1509: }
1510: printf("\n");
1511: fprintf(ficlog,"\n");
1512: for(l=0;l<=1;l++) {
1513: for (j=1;j<=n;j++) {
1514: ptt[j]=p[j]+(p[j]-pt[j])*k[l];
1515: printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1516: fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1517: }
1518: printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1519: fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1520: }
1521: #endif
1522:
1523:
1524: free_vector(xit,1,n);
1525: free_vector(xits,1,n);
1526: free_vector(ptt,1,n);
1527: free_vector(pt,1,n);
1528: return;
1529: }
1530: if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
1531: for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1532: ptt[j]=2.0*p[j]-pt[j];
1533: xit[j]=p[j]-pt[j];
1534: pt[j]=p[j];
1535: }
1536: fptt=(*func)(ptt); /* f_3 */
1537: if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1538: /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1539: /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1540: /* Let f"(x2) be the 2nd derivative equal everywhere. */
1541: /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
1542: /* will reach at f3 = fm + h^2/2 f"m ; f" = (f1 -2f2 +f3 ) / h**2 */
1543: /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1544: /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1545:
1546: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del);
1547: t= t- del*SQR(fp-fptt);
1548: directest = SQR(fp-2.0*(*fret)+fptt) - 2.0 * del; /* If del was big enough we change it for a new direction */
1549: #ifdef DEBUG
1550: printf("t1= %.12lf, t2= %.12lf, t=%.12lf directest=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t,directest);
1551: fprintf(ficlog,"t1= %.12lf, t2= %.12lf, t=%.12lf directest=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t,directest);
1552: printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1553: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1554: fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1555: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1556: 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);
1557: 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);
1558: #endif
1559: #ifdef POWELLDIRECT
1560: if (directest < 0.0) { /* Then we use it for new direction */
1561: #else
1562: if (t < 0.0) { /* Then we use it for new direction */
1563: #endif
1564: linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction.*/
1565: for (j=1;j<=n;j++) {
1566: xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
1567: xi[j][n]=xit[j]; /* and this nth direction by the by the average p_0 p_n */
1568: }
1569: printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1570: fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1571:
1572: #ifdef DEBUG
1573: printf("Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1574: fprintf(ficlog,"Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1575: for(j=1;j<=n;j++){
1576: printf(" %.12e",xit[j]);
1577: fprintf(ficlog," %.12e",xit[j]);
1578: }
1579: printf("\n");
1580: fprintf(ficlog,"\n");
1581: #endif
1582: } /* end of t negative */
1583: } /* end if (fptt < fp) */
1584: }
1585: }
1586:
1587: /**** Prevalence limit (stable or period prevalence) ****************/
1588:
1589: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
1590: {
1591: /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1592: matrix by transitions matrix until convergence is reached */
1593:
1594: int i, ii,j,k;
1595: double min, max, maxmin, maxmax,sumnew=0.;
1596: /* double **matprod2(); */ /* test */
1597: double **out, cov[NCOVMAX+1], **pmij();
1598: double **newm;
1599: double agefin, delaymax=50 ; /* Max number of years to converge */
1600:
1601: for (ii=1;ii<=nlstate+ndeath;ii++)
1602: for (j=1;j<=nlstate+ndeath;j++){
1603: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1604: }
1605:
1606: cov[1]=1.;
1607:
1608: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1609: for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1610: newm=savm;
1611: /* Covariates have to be included here again */
1612: cov[2]=agefin;
1613:
1614: for (k=1; k<=cptcovn;k++) {
1615: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1616: /*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]]);*/
1617: }
1618: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1619: /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
1620: /* cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]] * nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]]; */
1621:
1622: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
1623: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
1624: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1625: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1626: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1627: out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1628:
1629: savm=oldm;
1630: oldm=newm;
1631: maxmax=0.;
1632: for(j=1;j<=nlstate;j++){
1633: min=1.;
1634: max=0.;
1635: for(i=1; i<=nlstate; i++) {
1636: sumnew=0;
1637: for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
1638: prlim[i][j]= newm[i][j]/(1-sumnew);
1639: /*printf(" prevalim i=%d, j=%d, prmlim[%d][%d]=%f, agefin=%d \n", i, j, i, j, prlim[i][j],(int)agefin);*/
1640: max=FMAX(max,prlim[i][j]);
1641: min=FMIN(min,prlim[i][j]);
1642: }
1643: maxmin=max-min;
1644: maxmax=FMAX(maxmax,maxmin);
1645: } /* j loop */
1646: if(maxmax < ftolpl){
1647: return prlim;
1648: }
1649: } /* age loop */
1650: return prlim; /* should not reach here */
1651: }
1652:
1653: /*************** transition probabilities ***************/
1654:
1655: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1656: {
1657: /* According to parameters values stored in x and the covariate's values stored in cov,
1658: computes the probability to be observed in state j being in state i by appying the
1659: model to the ncovmodel covariates (including constant and age).
1660: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
1661: and, according on how parameters are entered, the position of the coefficient xij(nc) of the
1662: ncth covariate in the global vector x is given by the formula:
1663: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
1664: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
1665: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
1666: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1667: Outputs ps[i][j] the probability to be observed in j being in j according to
1668: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1669: */
1670: double s1, lnpijopii;
1671: /*double t34;*/
1672: int i,j, nc, ii, jj;
1673:
1674: for(i=1; i<= nlstate; i++){
1675: for(j=1; j<i;j++){
1676: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1677: /*lnpijopii += param[i][j][nc]*cov[nc];*/
1678: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
1679: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1680: }
1681: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1682: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1683: }
1684: for(j=i+1; j<=nlstate+ndeath;j++){
1685: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1686: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
1687: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
1688: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1689: }
1690: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1691: }
1692: }
1693:
1694: for(i=1; i<= nlstate; i++){
1695: s1=0;
1696: for(j=1; j<i; j++){
1697: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1698: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1699: }
1700: for(j=i+1; j<=nlstate+ndeath; j++){
1701: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1702: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1703: }
1704: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1705: ps[i][i]=1./(s1+1.);
1706: /* Computing other pijs */
1707: for(j=1; j<i; j++)
1708: ps[i][j]= exp(ps[i][j])*ps[i][i];
1709: for(j=i+1; j<=nlstate+ndeath; j++)
1710: ps[i][j]= exp(ps[i][j])*ps[i][i];
1711: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
1712: } /* end i */
1713:
1714: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
1715: for(jj=1; jj<= nlstate+ndeath; jj++){
1716: ps[ii][jj]=0;
1717: ps[ii][ii]=1;
1718: }
1719: }
1720:
1721:
1722: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
1723: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */
1724: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
1725: /* } */
1726: /* printf("\n "); */
1727: /* } */
1728: /* printf("\n ");printf("%lf ",cov[2]);*/
1729: /*
1730: for(i=1; i<= npar; i++) printf("%f ",x[i]);
1731: goto end;*/
1732: return ps;
1733: }
1734:
1735: /**************** Product of 2 matrices ******************/
1736:
1737: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1738: {
1739: /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
1740: b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
1741: /* in, b, out are matrice of pointers which should have been initialized
1742: before: only the contents of out is modified. The function returns
1743: a pointer to pointers identical to out */
1744: int i, j, k;
1745: for(i=nrl; i<= nrh; i++)
1746: for(k=ncolol; k<=ncoloh; k++){
1747: out[i][k]=0.;
1748: for(j=ncl; j<=nch; j++)
1749: out[i][k] +=in[i][j]*b[j][k];
1750: }
1751: return out;
1752: }
1753:
1754:
1755: /************* Higher Matrix Product ***************/
1756:
1757: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
1758: {
1759: /* Computes the transition matrix starting at age 'age' over
1760: 'nhstepm*hstepm*stepm' months (i.e. until
1761: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
1762: nhstepm*hstepm matrices.
1763: Output is stored in matrix po[i][j][h] for h every 'hstepm' step
1764: (typically every 2 years instead of every month which is too big
1765: for the memory).
1766: Model is determined by parameters x and covariates have to be
1767: included manually here.
1768:
1769: */
1770:
1771: int i, j, d, h, k;
1772: double **out, cov[NCOVMAX+1];
1773: double **newm;
1774:
1775: /* Hstepm could be zero and should return the unit matrix */
1776: for (i=1;i<=nlstate+ndeath;i++)
1777: for (j=1;j<=nlstate+ndeath;j++){
1778: oldm[i][j]=(i==j ? 1.0 : 0.0);
1779: po[i][j][0]=(i==j ? 1.0 : 0.0);
1780: }
1781: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1782: for(h=1; h <=nhstepm; h++){
1783: for(d=1; d <=hstepm; d++){
1784: newm=savm;
1785: /* Covariates have to be included here again */
1786: cov[1]=1.;
1787: cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
1788: for (k=1; k<=cptcovn;k++)
1789: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1790: for (k=1; k<=cptcovage;k++)
1791: cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
1792: for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1793: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
1794:
1795:
1796: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
1797: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1798: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
1799: pmij(pmmij,cov,ncovmodel,x,nlstate));
1800: savm=oldm;
1801: oldm=newm;
1802: }
1803: for(i=1; i<=nlstate+ndeath; i++)
1804: for(j=1;j<=nlstate+ndeath;j++) {
1805: po[i][j][h]=newm[i][j];
1806: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1807: }
1808: /*printf("h=%d ",h);*/
1809: } /* end h */
1810: /* printf("\n H=%d \n",h); */
1811: return po;
1812: }
1813:
1814: #ifdef NLOPT
1815: double myfunc(unsigned n, const double *p1, double *grad, void *pd){
1816: double fret;
1817: double *xt;
1818: int j;
1819: myfunc_data *d2 = (myfunc_data *) pd;
1820: /* xt = (p1-1); */
1821: xt=vector(1,n);
1822: for (j=1;j<=n;j++) xt[j]=p1[j-1]; /* xt[1]=p1[0] */
1823:
1824: fret=(d2->function)(xt); /* p xt[1]@8 is fine */
1825: /* fret=(*func)(xt); /\* p xt[1]@8 is fine *\/ */
1826: printf("Function = %.12lf ",fret);
1827: for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]);
1828: printf("\n");
1829: free_vector(xt,1,n);
1830: return fret;
1831: }
1832: #endif
1833:
1834: /*************** log-likelihood *************/
1835: double func( double *x)
1836: {
1837: int i, ii, j, k, mi, d, kk;
1838: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1839: double **out;
1840: double sw; /* Sum of weights */
1841: double lli; /* Individual log likelihood */
1842: int s1, s2;
1843: double bbh, survp;
1844: long ipmx;
1845: /*extern weight */
1846: /* We are differentiating ll according to initial status */
1847: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
1848: /*for(i=1;i<imx;i++)
1849: printf(" %d\n",s[4][i]);
1850: */
1851:
1852: ++countcallfunc;
1853:
1854: cov[1]=1.;
1855:
1856: for(k=1; k<=nlstate; k++) ll[k]=0.;
1857:
1858: if(mle==1){
1859: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1860: /* Computes the values of the ncovmodel covariates of the model
1861: depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
1862: Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
1863: to be observed in j being in i according to the model.
1864: */
1865: for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1866: cov[2+k]=covar[Tvar[k]][i];
1867: }
1868: /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4]
1869: is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]
1870: has been calculated etc */
1871: for(mi=1; mi<= wav[i]-1; mi++){
1872: for (ii=1;ii<=nlstate+ndeath;ii++)
1873: for (j=1;j<=nlstate+ndeath;j++){
1874: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1875: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1876: }
1877: for(d=0; d<dh[mi][i]; d++){
1878: newm=savm;
1879: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1880: for (kk=1; kk<=cptcovage;kk++) {
1881: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; /* Tage[kk] gives the data-covariate associated with age */
1882: }
1883: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1884: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1885: savm=oldm;
1886: oldm=newm;
1887: } /* end mult */
1888:
1889: /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
1890: /* But now since version 0.9 we anticipate for bias at large stepm.
1891: * If stepm is larger than one month (smallest stepm) and if the exact delay
1892: * (in months) between two waves is not a multiple of stepm, we rounded to
1893: * the nearest (and in case of equal distance, to the lowest) interval but now
1894: * we keep into memory the bias bh[mi][i] and also the previous matrix product
1895: * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
1896: * probability in order to take into account the bias as a fraction of the way
1897: * from savm to out if bh is negative or even beyond if bh is positive. bh varies
1898: * -stepm/2 to stepm/2 .
1899: * For stepm=1 the results are the same as for previous versions of Imach.
1900: * For stepm > 1 the results are less biased than in previous versions.
1901: */
1902: s1=s[mw[mi][i]][i];
1903: s2=s[mw[mi+1][i]][i];
1904: bbh=(double)bh[mi][i]/(double)stepm;
1905: /* bias bh is positive if real duration
1906: * is higher than the multiple of stepm and negative otherwise.
1907: */
1908: /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
1909: if( s2 > nlstate){
1910: /* i.e. if s2 is a death state and if the date of death is known
1911: then the contribution to the likelihood is the probability to
1912: die between last step unit time and current step unit time,
1913: which is also equal to probability to die before dh
1914: minus probability to die before dh-stepm .
1915: In version up to 0.92 likelihood was computed
1916: as if date of death was unknown. Death was treated as any other
1917: health state: the date of the interview describes the actual state
1918: and not the date of a change in health state. The former idea was
1919: to consider that at each interview the state was recorded
1920: (healthy, disable or death) and IMaCh was corrected; but when we
1921: introduced the exact date of death then we should have modified
1922: the contribution of an exact death to the likelihood. This new
1923: contribution is smaller and very dependent of the step unit
1924: stepm. It is no more the probability to die between last interview
1925: and month of death but the probability to survive from last
1926: interview up to one month before death multiplied by the
1927: probability to die within a month. Thanks to Chris
1928: Jackson for correcting this bug. Former versions increased
1929: mortality artificially. The bad side is that we add another loop
1930: which slows down the processing. The difference can be up to 10%
1931: lower mortality.
1932: */
1933: lli=log(out[s1][s2] - savm[s1][s2]);
1934:
1935:
1936: } else if (s2==-2) {
1937: for (j=1,survp=0. ; j<=nlstate; j++)
1938: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1939: /*survp += out[s1][j]; */
1940: lli= log(survp);
1941: }
1942:
1943: else if (s2==-4) {
1944: for (j=3,survp=0. ; j<=nlstate; j++)
1945: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1946: lli= log(survp);
1947: }
1948:
1949: else if (s2==-5) {
1950: for (j=1,survp=0. ; j<=2; j++)
1951: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1952: lli= log(survp);
1953: }
1954:
1955: else{
1956: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1957: /* 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 */
1958: }
1959: /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
1960: /*if(lli ==000.0)*/
1961: /*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); */
1962: ipmx +=1;
1963: sw += weight[i];
1964: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1965: } /* end of wave */
1966: } /* end of individual */
1967: } else if(mle==2){
1968: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1969: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1970: for(mi=1; mi<= wav[i]-1; mi++){
1971: for (ii=1;ii<=nlstate+ndeath;ii++)
1972: for (j=1;j<=nlstate+ndeath;j++){
1973: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1974: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1975: }
1976: for(d=0; d<=dh[mi][i]; d++){
1977: newm=savm;
1978: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1979: for (kk=1; kk<=cptcovage;kk++) {
1980: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1981: }
1982: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1983: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1984: savm=oldm;
1985: oldm=newm;
1986: } /* end mult */
1987:
1988: s1=s[mw[mi][i]][i];
1989: s2=s[mw[mi+1][i]][i];
1990: bbh=(double)bh[mi][i]/(double)stepm;
1991: 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 */
1992: ipmx +=1;
1993: sw += weight[i];
1994: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1995: } /* end of wave */
1996: } /* end of individual */
1997: } else if(mle==3){ /* exponential inter-extrapolation */
1998: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1999: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2000: for(mi=1; mi<= wav[i]-1; mi++){
2001: for (ii=1;ii<=nlstate+ndeath;ii++)
2002: for (j=1;j<=nlstate+ndeath;j++){
2003: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2004: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2005: }
2006: for(d=0; d<dh[mi][i]; d++){
2007: newm=savm;
2008: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2009: for (kk=1; kk<=cptcovage;kk++) {
2010: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2011: }
2012: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2013: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2014: savm=oldm;
2015: oldm=newm;
2016: } /* end mult */
2017:
2018: s1=s[mw[mi][i]][i];
2019: s2=s[mw[mi+1][i]][i];
2020: bbh=(double)bh[mi][i]/(double)stepm;
2021: 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 */
2022: ipmx +=1;
2023: sw += weight[i];
2024: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2025: } /* end of wave */
2026: } /* end of individual */
2027: }else if (mle==4){ /* ml=4 no inter-extrapolation */
2028: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2029: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2030: for(mi=1; mi<= wav[i]-1; mi++){
2031: for (ii=1;ii<=nlstate+ndeath;ii++)
2032: for (j=1;j<=nlstate+ndeath;j++){
2033: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2034: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2035: }
2036: for(d=0; d<dh[mi][i]; d++){
2037: newm=savm;
2038: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2039: for (kk=1; kk<=cptcovage;kk++) {
2040: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2041: }
2042:
2043: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2044: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2045: savm=oldm;
2046: oldm=newm;
2047: } /* end mult */
2048:
2049: s1=s[mw[mi][i]][i];
2050: s2=s[mw[mi+1][i]][i];
2051: if( s2 > nlstate){
2052: lli=log(out[s1][s2] - savm[s1][s2]);
2053: }else{
2054: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2055: }
2056: ipmx +=1;
2057: sw += weight[i];
2058: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2059: /* 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]); */
2060: } /* end of wave */
2061: } /* end of individual */
2062: }else{ /* ml=5 no inter-extrapolation no jackson =0.8a */
2063: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2064: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2065: for(mi=1; mi<= wav[i]-1; mi++){
2066: for (ii=1;ii<=nlstate+ndeath;ii++)
2067: for (j=1;j<=nlstate+ndeath;j++){
2068: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2069: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2070: }
2071: for(d=0; d<dh[mi][i]; d++){
2072: newm=savm;
2073: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2074: for (kk=1; kk<=cptcovage;kk++) {
2075: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2076: }
2077:
2078: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2079: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2080: savm=oldm;
2081: oldm=newm;
2082: } /* end mult */
2083:
2084: s1=s[mw[mi][i]][i];
2085: s2=s[mw[mi+1][i]][i];
2086: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2087: ipmx +=1;
2088: sw += weight[i];
2089: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2090: /*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]);*/
2091: } /* end of wave */
2092: } /* end of individual */
2093: } /* End of if */
2094: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2095: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2096: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2097: return -l;
2098: }
2099:
2100: /*************** log-likelihood *************/
2101: double funcone( double *x)
2102: {
2103: /* Same as likeli but slower because of a lot of printf and if */
2104: int i, ii, j, k, mi, d, kk;
2105: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
2106: double **out;
2107: double lli; /* Individual log likelihood */
2108: double llt;
2109: int s1, s2;
2110: double bbh, survp;
2111: /*extern weight */
2112: /* We are differentiating ll according to initial status */
2113: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2114: /*for(i=1;i<imx;i++)
2115: printf(" %d\n",s[4][i]);
2116: */
2117: cov[1]=1.;
2118:
2119: for(k=1; k<=nlstate; k++) ll[k]=0.;
2120:
2121: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2122: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2123: for(mi=1; mi<= wav[i]-1; mi++){
2124: for (ii=1;ii<=nlstate+ndeath;ii++)
2125: for (j=1;j<=nlstate+ndeath;j++){
2126: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2127: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2128: }
2129: for(d=0; d<dh[mi][i]; d++){
2130: newm=savm;
2131: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2132: for (kk=1; kk<=cptcovage;kk++) {
2133: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2134: }
2135: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
2136: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2137: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2138: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
2139: /* 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
2140: savm=oldm;
2141: oldm=newm;
2142: } /* end mult */
2143:
2144: s1=s[mw[mi][i]][i];
2145: s2=s[mw[mi+1][i]][i];
2146: bbh=(double)bh[mi][i]/(double)stepm;
2147: /* bias is positive if real duration
2148: * is higher than the multiple of stepm and negative otherwise.
2149: */
2150: if( s2 > nlstate && (mle <5) ){ /* Jackson */
2151: lli=log(out[s1][s2] - savm[s1][s2]);
2152: } else if (s2==-2) {
2153: for (j=1,survp=0. ; j<=nlstate; j++)
2154: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2155: lli= log(survp);
2156: }else if (mle==1){
2157: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2158: } else if(mle==2){
2159: 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 */
2160: } else if(mle==3){ /* exponential inter-extrapolation */
2161: 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 */
2162: } else if (mle==4){ /* mle=4 no inter-extrapolation */
2163: lli=log(out[s1][s2]); /* Original formula */
2164: } else{ /* mle=0 back to 1 */
2165: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2166: /*lli=log(out[s1][s2]); */ /* Original formula */
2167: } /* End of if */
2168: ipmx +=1;
2169: sw += weight[i];
2170: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2171: /*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]); */
2172: if(globpr){
2173: fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
2174: %11.6f %11.6f %11.6f ", \
2175: num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
2176: 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
2177: for(k=1,llt=0.,l=0.; k<=nlstate; k++){
2178: llt +=ll[k]*gipmx/gsw;
2179: fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
2180: }
2181: fprintf(ficresilk," %10.6f\n", -llt);
2182: }
2183: } /* end of wave */
2184: } /* end of individual */
2185: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2186: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2187: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2188: if(globpr==0){ /* First time we count the contributions and weights */
2189: gipmx=ipmx;
2190: gsw=sw;
2191: }
2192: return -l;
2193: }
2194:
2195:
2196: /*************** function likelione ***********/
2197: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
2198: {
2199: /* This routine should help understanding what is done with
2200: the selection of individuals/waves and
2201: to check the exact contribution to the likelihood.
2202: Plotting could be done.
2203: */
2204: int k;
2205:
2206: if(*globpri !=0){ /* Just counts and sums, no printings */
2207: strcpy(fileresilk,"ilk");
2208: strcat(fileresilk,fileres);
2209: if((ficresilk=fopen(fileresilk,"w"))==NULL) {
2210: printf("Problem with resultfile: %s\n", fileresilk);
2211: fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
2212: }
2213: 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");
2214: fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
2215: /* i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
2216: for(k=1; k<=nlstate; k++)
2217: fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
2218: fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
2219: }
2220:
2221: *fretone=(*funcone)(p);
2222: if(*globpri !=0){
2223: fclose(ficresilk);
2224: fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
2225: fflush(fichtm);
2226: }
2227: return;
2228: }
2229:
2230:
2231: /*********** Maximum Likelihood Estimation ***************/
2232:
2233: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
2234: {
2235: int i,j, iter=0;
2236: double **xi;
2237: double fret;
2238: double fretone; /* Only one call to likelihood */
2239: /* char filerespow[FILENAMELENGTH];*/
2240:
2241: #ifdef NLOPT
2242: int creturn;
2243: nlopt_opt opt;
2244: /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
2245: double *lb;
2246: double minf; /* the minimum objective value, upon return */
2247: double * p1; /* Shifted parameters from 0 instead of 1 */
2248: myfunc_data dinst, *d = &dinst;
2249: #endif
2250:
2251:
2252: xi=matrix(1,npar,1,npar);
2253: for (i=1;i<=npar;i++)
2254: for (j=1;j<=npar;j++)
2255: xi[i][j]=(i==j ? 1.0 : 0.0);
2256: printf("Powell\n"); fprintf(ficlog,"Powell\n");
2257: strcpy(filerespow,"pow");
2258: strcat(filerespow,fileres);
2259: if((ficrespow=fopen(filerespow,"w"))==NULL) {
2260: printf("Problem with resultfile: %s\n", filerespow);
2261: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
2262: }
2263: fprintf(ficrespow,"# Powell\n# iter -2*LL");
2264: for (i=1;i<=nlstate;i++)
2265: for(j=1;j<=nlstate+ndeath;j++)
2266: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
2267: fprintf(ficrespow,"\n");
2268: #ifdef POWELL
2269: powell(p,xi,npar,ftol,&iter,&fret,func);
2270: #endif
2271:
2272: #ifdef NLOPT
2273: #ifdef NEWUOA
2274: opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
2275: #else
2276: opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
2277: #endif
2278: lb=vector(0,npar-1);
2279: for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
2280: nlopt_set_lower_bounds(opt, lb);
2281: nlopt_set_initial_step1(opt, 0.1);
2282:
2283: p1= (p+1); /* p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
2284: d->function = func;
2285: printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
2286: nlopt_set_min_objective(opt, myfunc, d);
2287: nlopt_set_xtol_rel(opt, ftol);
2288: if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
2289: printf("nlopt failed! %d\n",creturn);
2290: }
2291: else {
2292: printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
2293: printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
2294: iter=1; /* not equal */
2295: }
2296: nlopt_destroy(opt);
2297: #endif
2298: free_matrix(xi,1,npar,1,npar);
2299: fclose(ficrespow);
2300: printf("#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2301: fprintf(ficlog,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2302: fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2303:
2304: }
2305:
2306: /**** Computes Hessian and covariance matrix ***/
2307: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
2308: {
2309: double **a,**y,*x,pd;
2310: double **hess;
2311: int i, j;
2312: int *indx;
2313:
2314: double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
2315: double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
2316: void lubksb(double **a, int npar, int *indx, double b[]) ;
2317: void ludcmp(double **a, int npar, int *indx, double *d) ;
2318: double gompertz(double p[]);
2319: hess=matrix(1,npar,1,npar);
2320:
2321: printf("\nCalculation of the hessian matrix. Wait...\n");
2322: fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
2323: for (i=1;i<=npar;i++){
2324: printf("%d",i);fflush(stdout);
2325: fprintf(ficlog,"%d",i);fflush(ficlog);
2326:
2327: hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
2328:
2329: /* printf(" %f ",p[i]);
2330: printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
2331: }
2332:
2333: for (i=1;i<=npar;i++) {
2334: for (j=1;j<=npar;j++) {
2335: if (j>i) {
2336: printf(".%d%d",i,j);fflush(stdout);
2337: fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
2338: hess[i][j]=hessij(p,delti,i,j,func,npar);
2339:
2340: hess[j][i]=hess[i][j];
2341: /*printf(" %lf ",hess[i][j]);*/
2342: }
2343: }
2344: }
2345: printf("\n");
2346: fprintf(ficlog,"\n");
2347:
2348: printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
2349: fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
2350:
2351: a=matrix(1,npar,1,npar);
2352: y=matrix(1,npar,1,npar);
2353: x=vector(1,npar);
2354: indx=ivector(1,npar);
2355: for (i=1;i<=npar;i++)
2356: for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
2357: ludcmp(a,npar,indx,&pd);
2358:
2359: for (j=1;j<=npar;j++) {
2360: for (i=1;i<=npar;i++) x[i]=0;
2361: x[j]=1;
2362: lubksb(a,npar,indx,x);
2363: for (i=1;i<=npar;i++){
2364: matcov[i][j]=x[i];
2365: }
2366: }
2367:
2368: printf("\n#Hessian matrix#\n");
2369: fprintf(ficlog,"\n#Hessian matrix#\n");
2370: for (i=1;i<=npar;i++) {
2371: for (j=1;j<=npar;j++) {
2372: printf("%.3e ",hess[i][j]);
2373: fprintf(ficlog,"%.3e ",hess[i][j]);
2374: }
2375: printf("\n");
2376: fprintf(ficlog,"\n");
2377: }
2378:
2379: /* Recompute Inverse */
2380: for (i=1;i<=npar;i++)
2381: for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
2382: ludcmp(a,npar,indx,&pd);
2383:
2384: /* printf("\n#Hessian matrix recomputed#\n");
2385:
2386: for (j=1;j<=npar;j++) {
2387: for (i=1;i<=npar;i++) x[i]=0;
2388: x[j]=1;
2389: lubksb(a,npar,indx,x);
2390: for (i=1;i<=npar;i++){
2391: y[i][j]=x[i];
2392: printf("%.3e ",y[i][j]);
2393: fprintf(ficlog,"%.3e ",y[i][j]);
2394: }
2395: printf("\n");
2396: fprintf(ficlog,"\n");
2397: }
2398: */
2399:
2400: free_matrix(a,1,npar,1,npar);
2401: free_matrix(y,1,npar,1,npar);
2402: free_vector(x,1,npar);
2403: free_ivector(indx,1,npar);
2404: free_matrix(hess,1,npar,1,npar);
2405:
2406:
2407: }
2408:
2409: /*************** hessian matrix ****************/
2410: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
2411: {
2412: int i;
2413: int l=1, lmax=20;
2414: double k1,k2;
2415: double p2[MAXPARM+1]; /* identical to x */
2416: double res;
2417: double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
2418: double fx;
2419: int k=0,kmax=10;
2420: double l1;
2421:
2422: fx=func(x);
2423: for (i=1;i<=npar;i++) p2[i]=x[i];
2424: for(l=0 ; l <=lmax; l++){ /* Enlarging the zone around the Maximum */
2425: l1=pow(10,l);
2426: delts=delt;
2427: for(k=1 ; k <kmax; k=k+1){
2428: delt = delta*(l1*k);
2429: p2[theta]=x[theta] +delt;
2430: k1=func(p2)-fx; /* Might be negative if too close to the theoretical maximum */
2431: p2[theta]=x[theta]-delt;
2432: k2=func(p2)-fx;
2433: /*res= (k1-2.0*fx+k2)/delt/delt; */
2434: res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
2435:
2436: #ifdef DEBUGHESS
2437: 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);
2438: 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);
2439: #endif
2440: /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
2441: if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
2442: k=kmax;
2443: }
2444: else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
2445: k=kmax; l=lmax*10;
2446: }
2447: else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
2448: delts=delt;
2449: }
2450: }
2451: }
2452: delti[theta]=delts;
2453: return res;
2454:
2455: }
2456:
2457: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
2458: {
2459: int i;
2460: int l=1, lmax=20;
2461: double k1,k2,k3,k4,res,fx;
2462: double p2[MAXPARM+1];
2463: int k;
2464:
2465: fx=func(x);
2466: for (k=1; k<=2; k++) {
2467: for (i=1;i<=npar;i++) p2[i]=x[i];
2468: p2[thetai]=x[thetai]+delti[thetai]/k;
2469: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2470: k1=func(p2)-fx;
2471:
2472: p2[thetai]=x[thetai]+delti[thetai]/k;
2473: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2474: k2=func(p2)-fx;
2475:
2476: p2[thetai]=x[thetai]-delti[thetai]/k;
2477: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2478: k3=func(p2)-fx;
2479:
2480: p2[thetai]=x[thetai]-delti[thetai]/k;
2481: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2482: k4=func(p2)-fx;
2483: res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
2484: #ifdef DEBUG
2485: 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);
2486: 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);
2487: #endif
2488: }
2489: return res;
2490: }
2491:
2492: /************** Inverse of matrix **************/
2493: void ludcmp(double **a, int n, int *indx, double *d)
2494: {
2495: int i,imax,j,k;
2496: double big,dum,sum,temp;
2497: double *vv;
2498:
2499: vv=vector(1,n);
2500: *d=1.0;
2501: for (i=1;i<=n;i++) {
2502: big=0.0;
2503: for (j=1;j<=n;j++)
2504: if ((temp=fabs(a[i][j])) > big) big=temp;
2505: if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
2506: vv[i]=1.0/big;
2507: }
2508: for (j=1;j<=n;j++) {
2509: for (i=1;i<j;i++) {
2510: sum=a[i][j];
2511: for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
2512: a[i][j]=sum;
2513: }
2514: big=0.0;
2515: for (i=j;i<=n;i++) {
2516: sum=a[i][j];
2517: for (k=1;k<j;k++)
2518: sum -= a[i][k]*a[k][j];
2519: a[i][j]=sum;
2520: if ( (dum=vv[i]*fabs(sum)) >= big) {
2521: big=dum;
2522: imax=i;
2523: }
2524: }
2525: if (j != imax) {
2526: for (k=1;k<=n;k++) {
2527: dum=a[imax][k];
2528: a[imax][k]=a[j][k];
2529: a[j][k]=dum;
2530: }
2531: *d = -(*d);
2532: vv[imax]=vv[j];
2533: }
2534: indx[j]=imax;
2535: if (a[j][j] == 0.0) a[j][j]=TINY;
2536: if (j != n) {
2537: dum=1.0/(a[j][j]);
2538: for (i=j+1;i<=n;i++) a[i][j] *= dum;
2539: }
2540: }
2541: free_vector(vv,1,n); /* Doesn't work */
2542: ;
2543: }
2544:
2545: void lubksb(double **a, int n, int *indx, double b[])
2546: {
2547: int i,ii=0,ip,j;
2548: double sum;
2549:
2550: for (i=1;i<=n;i++) {
2551: ip=indx[i];
2552: sum=b[ip];
2553: b[ip]=b[i];
2554: if (ii)
2555: for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
2556: else if (sum) ii=i;
2557: b[i]=sum;
2558: }
2559: for (i=n;i>=1;i--) {
2560: sum=b[i];
2561: for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
2562: b[i]=sum/a[i][i];
2563: }
2564: }
2565:
2566: void pstamp(FILE *fichier)
2567: {
2568: fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
2569: }
2570:
2571: /************ Frequencies ********************/
2572: 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[])
2573: { /* Some frequencies */
2574:
2575: int i, m, jk, j1, bool, z1,j;
2576: int first;
2577: double ***freq; /* Frequencies */
2578: double *pp, **prop;
2579: double pos,posprop, k2, dateintsum=0,k2cpt=0;
2580: char fileresp[FILENAMELENGTH];
2581:
2582: pp=vector(1,nlstate);
2583: prop=matrix(1,nlstate,iagemin,iagemax+3);
2584: strcpy(fileresp,"p");
2585: strcat(fileresp,fileres);
2586: if((ficresp=fopen(fileresp,"w"))==NULL) {
2587: printf("Problem with prevalence resultfile: %s\n", fileresp);
2588: fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
2589: exit(0);
2590: }
2591: freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
2592: j1=0;
2593:
2594: j=cptcoveff;
2595: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2596:
2597: first=1;
2598:
2599: /* for(k1=1; k1<=j ; k1++){ */ /* Loop on covariates */
2600: /* for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
2601: /* j1++; */
2602: for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
2603: /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
2604: scanf("%d", i);*/
2605: for (i=-5; i<=nlstate+ndeath; i++)
2606: for (jk=-5; jk<=nlstate+ndeath; jk++)
2607: for(m=iagemin; m <= iagemax+3; m++)
2608: freq[i][jk][m]=0;
2609:
2610: for (i=1; i<=nlstate; i++)
2611: for(m=iagemin; m <= iagemax+3; m++)
2612: prop[i][m]=0;
2613:
2614: dateintsum=0;
2615: k2cpt=0;
2616: for (i=1; i<=imx; i++) {
2617: bool=1;
2618: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
2619: for (z1=1; z1<=cptcoveff; z1++)
2620: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
2621: /* Tests if the value of each of the covariates of i is equal to filter j1 */
2622: bool=0;
2623: /* 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",
2624: bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
2625: j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
2626: /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
2627: }
2628: }
2629:
2630: if (bool==1){
2631: for(m=firstpass; m<=lastpass; m++){
2632: k2=anint[m][i]+(mint[m][i]/12.);
2633: /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
2634: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2635: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2636: if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
2637: if (m<lastpass) {
2638: freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
2639: freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
2640: }
2641:
2642: if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
2643: dateintsum=dateintsum+k2;
2644: k2cpt++;
2645: }
2646: /*}*/
2647: }
2648: }
2649: } /* end i */
2650:
2651: /* fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
2652: pstamp(ficresp);
2653: if (cptcovn>0) {
2654: fprintf(ficresp, "\n#********** Variable ");
2655: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2656: fprintf(ficresp, "**********\n#");
2657: fprintf(ficlog, "\n#********** Variable ");
2658: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2659: fprintf(ficlog, "**********\n#");
2660: }
2661: for(i=1; i<=nlstate;i++)
2662: fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
2663: fprintf(ficresp, "\n");
2664:
2665: for(i=iagemin; i <= iagemax+3; i++){
2666: if(i==iagemax+3){
2667: fprintf(ficlog,"Total");
2668: }else{
2669: if(first==1){
2670: first=0;
2671: printf("See log file for details...\n");
2672: }
2673: fprintf(ficlog,"Age %d", i);
2674: }
2675: for(jk=1; jk <=nlstate ; jk++){
2676: for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
2677: pp[jk] += freq[jk][m][i];
2678: }
2679: for(jk=1; jk <=nlstate ; jk++){
2680: for(m=-1, pos=0; m <=0 ; m++)
2681: pos += freq[jk][m][i];
2682: if(pp[jk]>=1.e-10){
2683: if(first==1){
2684: printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
2685: }
2686: fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
2687: }else{
2688: if(first==1)
2689: printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2690: fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2691: }
2692: }
2693:
2694: for(jk=1; jk <=nlstate ; jk++){
2695: for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
2696: pp[jk] += freq[jk][m][i];
2697: }
2698: for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
2699: pos += pp[jk];
2700: posprop += prop[jk][i];
2701: }
2702: for(jk=1; jk <=nlstate ; jk++){
2703: if(pos>=1.e-5){
2704: if(first==1)
2705: printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2706: fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2707: }else{
2708: if(first==1)
2709: printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2710: fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2711: }
2712: if( i <= iagemax){
2713: if(pos>=1.e-5){
2714: fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
2715: /*probs[i][jk][j1]= pp[jk]/pos;*/
2716: /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
2717: }
2718: else
2719: fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
2720: }
2721: }
2722:
2723: for(jk=-1; jk <=nlstate+ndeath; jk++)
2724: for(m=-1; m <=nlstate+ndeath; m++)
2725: if(freq[jk][m][i] !=0 ) {
2726: if(first==1)
2727: printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
2728: fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
2729: }
2730: if(i <= iagemax)
2731: fprintf(ficresp,"\n");
2732: if(first==1)
2733: printf("Others in log...\n");
2734: fprintf(ficlog,"\n");
2735: }
2736: /*}*/
2737: }
2738: dateintmean=dateintsum/k2cpt;
2739:
2740: fclose(ficresp);
2741: free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
2742: free_vector(pp,1,nlstate);
2743: free_matrix(prop,1,nlstate,iagemin, iagemax+3);
2744: /* End of Freq */
2745: }
2746:
2747: /************ Prevalence ********************/
2748: 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)
2749: {
2750: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
2751: in each health status at the date of interview (if between dateprev1 and dateprev2).
2752: We still use firstpass and lastpass as another selection.
2753: */
2754:
2755: int i, m, jk, j1, bool, z1,j;
2756:
2757: double **prop;
2758: double posprop;
2759: double y2; /* in fractional years */
2760: int iagemin, iagemax;
2761: int first; /** to stop verbosity which is redirected to log file */
2762:
2763: iagemin= (int) agemin;
2764: iagemax= (int) agemax;
2765: /*pp=vector(1,nlstate);*/
2766: prop=matrix(1,nlstate,iagemin,iagemax+3);
2767: /* freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
2768: j1=0;
2769:
2770: /*j=cptcoveff;*/
2771: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2772:
2773: first=1;
2774: for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
2775: /*for(i1=1; i1<=ncodemax[k1];i1++){
2776: j1++;*/
2777:
2778: for (i=1; i<=nlstate; i++)
2779: for(m=iagemin; m <= iagemax+3; m++)
2780: prop[i][m]=0.0;
2781:
2782: for (i=1; i<=imx; i++) { /* Each individual */
2783: bool=1;
2784: if (cptcovn>0) {
2785: for (z1=1; z1<=cptcoveff; z1++)
2786: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
2787: bool=0;
2788: }
2789: if (bool==1) {
2790: for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
2791: y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
2792: if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
2793: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2794: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2795: 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);
2796: if (s[m][i]>0 && s[m][i]<=nlstate) {
2797: /*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]]);*/
2798: prop[s[m][i]][(int)agev[m][i]] += weight[i];
2799: prop[s[m][i]][iagemax+3] += weight[i];
2800: }
2801: }
2802: } /* end selection of waves */
2803: }
2804: }
2805: for(i=iagemin; i <= iagemax+3; i++){
2806: for(jk=1,posprop=0; jk <=nlstate ; jk++) {
2807: posprop += prop[jk][i];
2808: }
2809:
2810: for(jk=1; jk <=nlstate ; jk++){
2811: if( i <= iagemax){
2812: if(posprop>=1.e-5){
2813: probs[i][jk][j1]= prop[jk][i]/posprop;
2814: } else{
2815: if(first==1){
2816: first=0;
2817: 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]);
2818: }
2819: }
2820: }
2821: }/* end jk */
2822: }/* end i */
2823: /*} *//* end i1 */
2824: } /* end j1 */
2825:
2826: /* free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
2827: /*free_vector(pp,1,nlstate);*/
2828: free_matrix(prop,1,nlstate, iagemin,iagemax+3);
2829: } /* End of prevalence */
2830:
2831: /************* Waves Concatenation ***************/
2832:
2833: 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)
2834: {
2835: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
2836: Death is a valid wave (if date is known).
2837: mw[mi][i] is the mi (mi=1 to wav[i]) effective wave of individual i
2838: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
2839: and mw[mi+1][i]. dh depends on stepm.
2840: */
2841:
2842: int i, mi, m;
2843: /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
2844: double sum=0., jmean=0.;*/
2845: int first;
2846: int j, k=0,jk, ju, jl;
2847: double sum=0.;
2848: first=0;
2849: jmin=100000;
2850: jmax=-1;
2851: jmean=0.;
2852: for(i=1; i<=imx; i++){
2853: mi=0;
2854: m=firstpass;
2855: while(s[m][i] <= nlstate){
2856: if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
2857: mw[++mi][i]=m;
2858: if(m >=lastpass)
2859: break;
2860: else
2861: m++;
2862: }/* end while */
2863: if (s[m][i] > nlstate){
2864: mi++; /* Death is another wave */
2865: /* if(mi==0) never been interviewed correctly before death */
2866: /* Only death is a correct wave */
2867: mw[mi][i]=m;
2868: }
2869:
2870: wav[i]=mi;
2871: if(mi==0){
2872: nbwarn++;
2873: if(first==0){
2874: printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
2875: first=1;
2876: }
2877: if(first==1){
2878: fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
2879: }
2880: } /* end mi==0 */
2881: } /* End individuals */
2882:
2883: for(i=1; i<=imx; i++){
2884: for(mi=1; mi<wav[i];mi++){
2885: if (stepm <=0)
2886: dh[mi][i]=1;
2887: else{
2888: if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
2889: if (agedc[i] < 2*AGESUP) {
2890: j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
2891: if(j==0) j=1; /* Survives at least one month after exam */
2892: else if(j<0){
2893: nberr++;
2894: 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]);
2895: j=1; /* Temporary Dangerous patch */
2896: 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);
2897: 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]);
2898: 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);
2899: }
2900: k=k+1;
2901: if (j >= jmax){
2902: jmax=j;
2903: ijmax=i;
2904: }
2905: if (j <= jmin){
2906: jmin=j;
2907: ijmin=i;
2908: }
2909: sum=sum+j;
2910: /*if (j<0) printf("j=%d num=%d \n",j,i);*/
2911: /* printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
2912: }
2913: }
2914: else{
2915: j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
2916: /* 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]); */
2917:
2918: k=k+1;
2919: if (j >= jmax) {
2920: jmax=j;
2921: ijmax=i;
2922: }
2923: else if (j <= jmin){
2924: jmin=j;
2925: ijmin=i;
2926: }
2927: /* if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
2928: /*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]);*/
2929: if(j<0){
2930: nberr++;
2931: 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]);
2932: 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]);
2933: }
2934: sum=sum+j;
2935: }
2936: jk= j/stepm;
2937: jl= j -jk*stepm;
2938: ju= j -(jk+1)*stepm;
2939: if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
2940: if(jl==0){
2941: dh[mi][i]=jk;
2942: bh[mi][i]=0;
2943: }else{ /* We want a negative bias in order to only have interpolation ie
2944: * to avoid the price of an extra matrix product in likelihood */
2945: dh[mi][i]=jk+1;
2946: bh[mi][i]=ju;
2947: }
2948: }else{
2949: if(jl <= -ju){
2950: dh[mi][i]=jk;
2951: bh[mi][i]=jl; /* bias is positive if real duration
2952: * is higher than the multiple of stepm and negative otherwise.
2953: */
2954: }
2955: else{
2956: dh[mi][i]=jk+1;
2957: bh[mi][i]=ju;
2958: }
2959: if(dh[mi][i]==0){
2960: dh[mi][i]=1; /* At least one step */
2961: bh[mi][i]=ju; /* At least one step */
2962: /* 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);*/
2963: }
2964: } /* end if mle */
2965: }
2966: } /* end wave */
2967: }
2968: jmean=sum/k;
2969: 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);
2970: 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);
2971: }
2972:
2973: /*********** Tricode ****************************/
2974: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
2975: {
2976: /**< Uses cptcovn+2*cptcovprod as the number of covariates */
2977: /* Tvar[i]=atoi(stre); find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1
2978: * Boring subroutine which should only output nbcode[Tvar[j]][k]
2979: * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
2980: * nbcode[Tvar[j]][1]=
2981: */
2982:
2983: int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
2984: int modmaxcovj=0; /* Modality max of covariates j */
2985: int cptcode=0; /* Modality max of covariates j */
2986: int modmincovj=0; /* Modality min of covariates j */
2987:
2988:
2989: cptcoveff=0;
2990:
2991: for (k=-1; k < maxncov; k++) Ndum[k]=0;
2992: for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
2993:
2994: /* Loop on covariates without age and products */
2995: for (j=1; j<=(cptcovs); j++) { /* model V1 + V2*age+ V3 + V3*V4 : V1 + V3 = 2 only */
2996: for (i=1; i<=imx; i++) { /* Lopp on individuals: reads the data file to get the maximum value of the
2997: modality of this covariate Vj*/
2998: ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
2999: * If product of Vn*Vm, still boolean *:
3000: * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
3001: * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0 */
3002: /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
3003: modality of the nth covariate of individual i. */
3004: if (ij > modmaxcovj)
3005: modmaxcovj=ij;
3006: else if (ij < modmincovj)
3007: modmincovj=ij;
3008: if ((ij < -1) && (ij > NCOVMAX)){
3009: printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
3010: exit(1);
3011: }else
3012: Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
3013: /* If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
3014: /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
3015: /* getting the maximum value of the modality of the covariate
3016: (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
3017: female is 1, then modmaxcovj=1.*/
3018: }
3019: printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
3020: cptcode=modmaxcovj;
3021: /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
3022: /*for (i=0; i<=cptcode; i++) {*/
3023: for (i=modmincovj; i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
3024: printf("Frequencies of covariates %d V%d %d\n", j, Tvar[j], Ndum[i]);
3025: if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
3026: ncodemax[j]++; /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
3027: }
3028: /* In fact ncodemax[j]=2 (dichotom. variables only) but it could be more for
3029: historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
3030: } /* Ndum[-1] number of undefined modalities */
3031:
3032: /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
3033: /* For covariate j, modalities could be 1, 2, 3, 4. If Ndum[2]=0 ncodemax[j] is not 4 but 3 */
3034: /* If Ndum[3}= 635; Ndum[4]=0; Ndum[5]=0; Ndum[6]=27; Ndum[7]=125;
3035: modmincovj=3; modmaxcovj = 7;
3036: There are only 3 modalities non empty (or 2 if 27 is too few) : ncodemax[j]=3;
3037: which will be coded 0, 1, 2 which in binary on 3-1 digits are 0=00 1=01, 2=10; defining two dummy
3038: variables V1_1 and V1_2.
3039: nbcode[Tvar[j]][ij]=k;
3040: nbcode[Tvar[j]][1]=0;
3041: nbcode[Tvar[j]][2]=1;
3042: nbcode[Tvar[j]][3]=2;
3043: */
3044: ij=1; /* ij is similar to i but can jumps over null modalities */
3045: for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
3046: for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
3047: /*recode from 0 */
3048: if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
3049: nbcode[Tvar[j]][ij]=k; /* stores the modality in an array nbcode.
3050: k is a modality. If we have model=V1+V1*sex
3051: then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
3052: ij++;
3053: }
3054: if (ij > ncodemax[j]) break;
3055: } /* end of loop on */
3056: } /* end of loop on modality */
3057: } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/
3058:
3059: for (k=-1; k< maxncov; k++) Ndum[k]=0;
3060:
3061: for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */
3062: /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
3063: ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
3064: Ndum[ij]++;
3065: }
3066:
3067: ij=1;
3068: for (i=0; i<= maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
3069: /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
3070: if((Ndum[i]!=0) && (i<=ncovcol)){
3071: /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
3072: Tvaraff[ij]=i; /*For printing (unclear) */
3073: ij++;
3074: }else
3075: Tvaraff[ij]=0;
3076: }
3077: ij--;
3078: cptcoveff=ij; /*Number of total covariates*/
3079:
3080: }
3081:
3082:
3083: /*********** Health Expectancies ****************/
3084:
3085: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
3086:
3087: {
3088: /* Health expectancies, no variances */
3089: int i, j, nhstepm, hstepm, h, nstepm;
3090: int nhstepma, nstepma; /* Decreasing with age */
3091: double age, agelim, hf;
3092: double ***p3mat;
3093: double eip;
3094:
3095: pstamp(ficreseij);
3096: fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
3097: fprintf(ficreseij,"# Age");
3098: for(i=1; i<=nlstate;i++){
3099: for(j=1; j<=nlstate;j++){
3100: fprintf(ficreseij," e%1d%1d ",i,j);
3101: }
3102: fprintf(ficreseij," e%1d. ",i);
3103: }
3104: fprintf(ficreseij,"\n");
3105:
3106:
3107: if(estepm < stepm){
3108: printf ("Problem %d lower than %d\n",estepm, stepm);
3109: }
3110: else hstepm=estepm;
3111: /* We compute the life expectancy from trapezoids spaced every estepm months
3112: * This is mainly to measure the difference between two models: for example
3113: * if stepm=24 months pijx are given only every 2 years and by summing them
3114: * we are calculating an estimate of the Life Expectancy assuming a linear
3115: * progression in between and thus overestimating or underestimating according
3116: * to the curvature of the survival function. If, for the same date, we
3117: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3118: * to compare the new estimate of Life expectancy with the same linear
3119: * hypothesis. A more precise result, taking into account a more precise
3120: * curvature will be obtained if estepm is as small as stepm. */
3121:
3122: /* For example we decided to compute the life expectancy with the smallest unit */
3123: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3124: nhstepm is the number of hstepm from age to agelim
3125: nstepm is the number of stepm from age to agelin.
3126: Look at hpijx to understand the reason of that which relies in memory size
3127: and note for a fixed period like estepm months */
3128: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3129: survival function given by stepm (the optimization length). Unfortunately it
3130: means that if the survival funtion is printed only each two years of age and if
3131: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3132: results. So we changed our mind and took the option of the best precision.
3133: */
3134: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3135:
3136: agelim=AGESUP;
3137: /* If stepm=6 months */
3138: /* Computed by stepm unit matrices, product of hstepm matrices, stored
3139: in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
3140:
3141: /* nhstepm age range expressed in number of stepm */
3142: nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3143: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3144: /* if (stepm >= YEARM) hstepm=1;*/
3145: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3146: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3147:
3148: for (age=bage; age<=fage; age ++){
3149: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3150: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3151: /* if (stepm >= YEARM) hstepm=1;*/
3152: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3153:
3154: /* If stepm=6 months */
3155: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3156: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3157:
3158: hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3159:
3160: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3161:
3162: printf("%d|",(int)age);fflush(stdout);
3163: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3164:
3165: /* Computing expectancies */
3166: for(i=1; i<=nlstate;i++)
3167: for(j=1; j<=nlstate;j++)
3168: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3169: eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
3170:
3171: /* 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]);*/
3172:
3173: }
3174:
3175: fprintf(ficreseij,"%3.0f",age );
3176: for(i=1; i<=nlstate;i++){
3177: eip=0;
3178: for(j=1; j<=nlstate;j++){
3179: eip +=eij[i][j][(int)age];
3180: fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
3181: }
3182: fprintf(ficreseij,"%9.4f", eip );
3183: }
3184: fprintf(ficreseij,"\n");
3185:
3186: }
3187: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3188: printf("\n");
3189: fprintf(ficlog,"\n");
3190:
3191: }
3192:
3193: 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[] )
3194:
3195: {
3196: /* Covariances of health expectancies eij and of total life expectancies according
3197: to initial status i, ei. .
3198: */
3199: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
3200: int nhstepma, nstepma; /* Decreasing with age */
3201: double age, agelim, hf;
3202: double ***p3matp, ***p3matm, ***varhe;
3203: double **dnewm,**doldm;
3204: double *xp, *xm;
3205: double **gp, **gm;
3206: double ***gradg, ***trgradg;
3207: int theta;
3208:
3209: double eip, vip;
3210:
3211: varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
3212: xp=vector(1,npar);
3213: xm=vector(1,npar);
3214: dnewm=matrix(1,nlstate*nlstate,1,npar);
3215: doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
3216:
3217: pstamp(ficresstdeij);
3218: fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
3219: fprintf(ficresstdeij,"# Age");
3220: for(i=1; i<=nlstate;i++){
3221: for(j=1; j<=nlstate;j++)
3222: fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
3223: fprintf(ficresstdeij," e%1d. ",i);
3224: }
3225: fprintf(ficresstdeij,"\n");
3226:
3227: pstamp(ficrescveij);
3228: fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
3229: fprintf(ficrescveij,"# Age");
3230: for(i=1; i<=nlstate;i++)
3231: for(j=1; j<=nlstate;j++){
3232: cptj= (j-1)*nlstate+i;
3233: for(i2=1; i2<=nlstate;i2++)
3234: for(j2=1; j2<=nlstate;j2++){
3235: cptj2= (j2-1)*nlstate+i2;
3236: if(cptj2 <= cptj)
3237: fprintf(ficrescveij," %1d%1d,%1d%1d",i,j,i2,j2);
3238: }
3239: }
3240: fprintf(ficrescveij,"\n");
3241:
3242: if(estepm < stepm){
3243: printf ("Problem %d lower than %d\n",estepm, stepm);
3244: }
3245: else hstepm=estepm;
3246: /* We compute the life expectancy from trapezoids spaced every estepm months
3247: * This is mainly to measure the difference between two models: for example
3248: * if stepm=24 months pijx are given only every 2 years and by summing them
3249: * we are calculating an estimate of the Life Expectancy assuming a linear
3250: * progression in between and thus overestimating or underestimating according
3251: * to the curvature of the survival function. If, for the same date, we
3252: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3253: * to compare the new estimate of Life expectancy with the same linear
3254: * hypothesis. A more precise result, taking into account a more precise
3255: * curvature will be obtained if estepm is as small as stepm. */
3256:
3257: /* For example we decided to compute the life expectancy with the smallest unit */
3258: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3259: nhstepm is the number of hstepm from age to agelim
3260: nstepm is the number of stepm from age to agelin.
3261: Look at hpijx to understand the reason of that which relies in memory size
3262: and note for a fixed period like estepm months */
3263: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3264: survival function given by stepm (the optimization length). Unfortunately it
3265: means that if the survival funtion is printed only each two years of age and if
3266: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3267: results. So we changed our mind and took the option of the best precision.
3268: */
3269: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3270:
3271: /* If stepm=6 months */
3272: /* nhstepm age range expressed in number of stepm */
3273: agelim=AGESUP;
3274: nstepm=(int) rint((agelim-bage)*YEARM/stepm);
3275: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3276: /* if (stepm >= YEARM) hstepm=1;*/
3277: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3278:
3279: p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3280: p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3281: gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
3282: trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
3283: gp=matrix(0,nhstepm,1,nlstate*nlstate);
3284: gm=matrix(0,nhstepm,1,nlstate*nlstate);
3285:
3286: for (age=bage; age<=fage; age ++){
3287: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3288: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3289: /* if (stepm >= YEARM) hstepm=1;*/
3290: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3291:
3292: /* If stepm=6 months */
3293: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3294: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3295:
3296: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3297:
3298: /* Computing Variances of health expectancies */
3299: /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
3300: decrease memory allocation */
3301: for(theta=1; theta <=npar; theta++){
3302: for(i=1; i<=npar; i++){
3303: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3304: xm[i] = x[i] - (i==theta ?delti[theta]:0);
3305: }
3306: hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);
3307: hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);
3308:
3309: for(j=1; j<= nlstate; j++){
3310: for(i=1; i<=nlstate; i++){
3311: for(h=0; h<=nhstepm-1; h++){
3312: gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
3313: gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
3314: }
3315: }
3316: }
3317:
3318: for(ij=1; ij<= nlstate*nlstate; ij++)
3319: for(h=0; h<=nhstepm-1; h++){
3320: gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
3321: }
3322: }/* End theta */
3323:
3324:
3325: for(h=0; h<=nhstepm-1; h++)
3326: for(j=1; j<=nlstate*nlstate;j++)
3327: for(theta=1; theta <=npar; theta++)
3328: trgradg[h][j][theta]=gradg[h][theta][j];
3329:
3330:
3331: for(ij=1;ij<=nlstate*nlstate;ij++)
3332: for(ji=1;ji<=nlstate*nlstate;ji++)
3333: varhe[ij][ji][(int)age] =0.;
3334:
3335: printf("%d|",(int)age);fflush(stdout);
3336: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3337: for(h=0;h<=nhstepm-1;h++){
3338: for(k=0;k<=nhstepm-1;k++){
3339: matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
3340: matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
3341: for(ij=1;ij<=nlstate*nlstate;ij++)
3342: for(ji=1;ji<=nlstate*nlstate;ji++)
3343: varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
3344: }
3345: }
3346:
3347: /* Computing expectancies */
3348: hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3349: for(i=1; i<=nlstate;i++)
3350: for(j=1; j<=nlstate;j++)
3351: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3352: eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
3353:
3354: /* 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]);*/
3355:
3356: }
3357:
3358: fprintf(ficresstdeij,"%3.0f",age );
3359: for(i=1; i<=nlstate;i++){
3360: eip=0.;
3361: vip=0.;
3362: for(j=1; j<=nlstate;j++){
3363: eip += eij[i][j][(int)age];
3364: for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
3365: vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
3366: fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
3367: }
3368: fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
3369: }
3370: fprintf(ficresstdeij,"\n");
3371:
3372: fprintf(ficrescveij,"%3.0f",age );
3373: for(i=1; i<=nlstate;i++)
3374: for(j=1; j<=nlstate;j++){
3375: cptj= (j-1)*nlstate+i;
3376: for(i2=1; i2<=nlstate;i2++)
3377: for(j2=1; j2<=nlstate;j2++){
3378: cptj2= (j2-1)*nlstate+i2;
3379: if(cptj2 <= cptj)
3380: fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
3381: }
3382: }
3383: fprintf(ficrescveij,"\n");
3384:
3385: }
3386: free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
3387: free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
3388: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
3389: free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
3390: free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3391: free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3392: printf("\n");
3393: fprintf(ficlog,"\n");
3394:
3395: free_vector(xm,1,npar);
3396: free_vector(xp,1,npar);
3397: free_matrix(dnewm,1,nlstate*nlstate,1,npar);
3398: free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
3399: free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
3400: }
3401:
3402: /************ Variance ******************/
3403: 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[])
3404: {
3405: /* Variance of health expectancies */
3406: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
3407: /* double **newm;*/
3408: /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
3409:
3410: int movingaverage();
3411: double **dnewm,**doldm;
3412: double **dnewmp,**doldmp;
3413: int i, j, nhstepm, hstepm, h, nstepm ;
3414: int k;
3415: double *xp;
3416: double **gp, **gm; /* for var eij */
3417: double ***gradg, ***trgradg; /*for var eij */
3418: double **gradgp, **trgradgp; /* for var p point j */
3419: double *gpp, *gmp; /* for var p point j */
3420: double **varppt; /* for var p point j nlstate to nlstate+ndeath */
3421: double ***p3mat;
3422: double age,agelim, hf;
3423: double ***mobaverage;
3424: int theta;
3425: char digit[4];
3426: char digitp[25];
3427:
3428: char fileresprobmorprev[FILENAMELENGTH];
3429:
3430: if(popbased==1){
3431: if(mobilav!=0)
3432: strcpy(digitp,"-populbased-mobilav-");
3433: else strcpy(digitp,"-populbased-nomobil-");
3434: }
3435: else
3436: strcpy(digitp,"-stablbased-");
3437:
3438: if (mobilav!=0) {
3439: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3440: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
3441: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
3442: printf(" Error in movingaverage mobilav=%d\n",mobilav);
3443: }
3444: }
3445:
3446: strcpy(fileresprobmorprev,"prmorprev");
3447: sprintf(digit,"%-d",ij);
3448: /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
3449: strcat(fileresprobmorprev,digit); /* Tvar to be done */
3450: strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
3451: strcat(fileresprobmorprev,fileres);
3452: if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
3453: printf("Problem with resultfile: %s\n", fileresprobmorprev);
3454: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
3455: }
3456: printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3457:
3458: fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3459: pstamp(ficresprobmorprev);
3460: 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);
3461: fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
3462: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3463: fprintf(ficresprobmorprev," p.%-d SE",j);
3464: for(i=1; i<=nlstate;i++)
3465: fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
3466: }
3467: fprintf(ficresprobmorprev,"\n");
3468: fprintf(ficgp,"\n# Routine varevsij");
3469: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
3470: 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");
3471: fprintf(fichtm,"\n<br>%s <br>\n",digitp);
3472: /* } */
3473: varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3474: pstamp(ficresvij);
3475: fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n# (weighted average of eij where weights are ");
3476: if(popbased==1)
3477: 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);
3478: else
3479: fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
3480: fprintf(ficresvij,"# Age");
3481: for(i=1; i<=nlstate;i++)
3482: for(j=1; j<=nlstate;j++)
3483: fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
3484: fprintf(ficresvij,"\n");
3485:
3486: xp=vector(1,npar);
3487: dnewm=matrix(1,nlstate,1,npar);
3488: doldm=matrix(1,nlstate,1,nlstate);
3489: dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
3490: doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3491:
3492: gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
3493: gpp=vector(nlstate+1,nlstate+ndeath);
3494: gmp=vector(nlstate+1,nlstate+ndeath);
3495: trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
3496:
3497: if(estepm < stepm){
3498: printf ("Problem %d lower than %d\n",estepm, stepm);
3499: }
3500: else hstepm=estepm;
3501: /* For example we decided to compute the life expectancy with the smallest unit */
3502: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3503: nhstepm is the number of hstepm from age to agelim
3504: nstepm is the number of stepm from age to agelin.
3505: Look at function hpijx to understand why (it is linked to memory size questions) */
3506: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3507: survival function given by stepm (the optimization length). Unfortunately it
3508: means that if the survival funtion is printed every two years of age and if
3509: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3510: results. So we changed our mind and took the option of the best precision.
3511: */
3512: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3513: agelim = AGESUP;
3514: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3515: nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3516: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3517: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3518: gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
3519: gp=matrix(0,nhstepm,1,nlstate);
3520: gm=matrix(0,nhstepm,1,nlstate);
3521:
3522:
3523: for(theta=1; theta <=npar; theta++){
3524: for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
3525: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3526: }
3527: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3528: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3529:
3530: if (popbased==1) {
3531: if(mobilav ==0){
3532: for(i=1; i<=nlstate;i++)
3533: prlim[i][i]=probs[(int)age][i][ij];
3534: }else{ /* mobilav */
3535: for(i=1; i<=nlstate;i++)
3536: prlim[i][i]=mobaverage[(int)age][i][ij];
3537: }
3538: }
3539:
3540: for(j=1; j<= nlstate; j++){
3541: for(h=0; h<=nhstepm; h++){
3542: for(i=1, gp[h][j]=0.;i<=nlstate;i++)
3543: gp[h][j] += prlim[i][i]*p3mat[i][j][h];
3544: }
3545: }
3546: /* This for computing probability of death (h=1 means
3547: computed over hstepm matrices product = hstepm*stepm months)
3548: as a weighted average of prlim.
3549: */
3550: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3551: for(i=1,gpp[j]=0.; i<= nlstate; i++)
3552: gpp[j] += prlim[i][i]*p3mat[i][j][1];
3553: }
3554: /* end probability of death */
3555:
3556: for(i=1; i<=npar; i++) /* Computes gradient x - delta */
3557: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3558: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3559: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3560:
3561: if (popbased==1) {
3562: if(mobilav ==0){
3563: for(i=1; i<=nlstate;i++)
3564: prlim[i][i]=probs[(int)age][i][ij];
3565: }else{ /* mobilav */
3566: for(i=1; i<=nlstate;i++)
3567: prlim[i][i]=mobaverage[(int)age][i][ij];
3568: }
3569: }
3570:
3571: for(j=1; j<= nlstate; j++){ /* Sum of wi * eij = e.j */
3572: for(h=0; h<=nhstepm; h++){
3573: for(i=1, gm[h][j]=0.;i<=nlstate;i++)
3574: gm[h][j] += prlim[i][i]*p3mat[i][j][h];
3575: }
3576: }
3577: /* This for computing probability of death (h=1 means
3578: computed over hstepm matrices product = hstepm*stepm months)
3579: as a weighted average of prlim.
3580: */
3581: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3582: for(i=1,gmp[j]=0.; i<= nlstate; i++)
3583: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3584: }
3585: /* end probability of death */
3586:
3587: for(j=1; j<= nlstate; j++) /* vareij */
3588: for(h=0; h<=nhstepm; h++){
3589: gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
3590: }
3591:
3592: for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
3593: gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
3594: }
3595:
3596: } /* End theta */
3597:
3598: trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
3599:
3600: for(h=0; h<=nhstepm; h++) /* veij */
3601: for(j=1; j<=nlstate;j++)
3602: for(theta=1; theta <=npar; theta++)
3603: trgradg[h][j][theta]=gradg[h][theta][j];
3604:
3605: for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
3606: for(theta=1; theta <=npar; theta++)
3607: trgradgp[j][theta]=gradgp[theta][j];
3608:
3609:
3610: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3611: for(i=1;i<=nlstate;i++)
3612: for(j=1;j<=nlstate;j++)
3613: vareij[i][j][(int)age] =0.;
3614:
3615: for(h=0;h<=nhstepm;h++){
3616: for(k=0;k<=nhstepm;k++){
3617: matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
3618: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
3619: for(i=1;i<=nlstate;i++)
3620: for(j=1;j<=nlstate;j++)
3621: vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
3622: }
3623: }
3624:
3625: /* pptj */
3626: matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
3627: matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
3628: for(j=nlstate+1;j<=nlstate+ndeath;j++)
3629: for(i=nlstate+1;i<=nlstate+ndeath;i++)
3630: varppt[j][i]=doldmp[j][i];
3631: /* end ppptj */
3632: /* x centered again */
3633: hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);
3634: prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
3635:
3636: if (popbased==1) {
3637: if(mobilav ==0){
3638: for(i=1; i<=nlstate;i++)
3639: prlim[i][i]=probs[(int)age][i][ij];
3640: }else{ /* mobilav */
3641: for(i=1; i<=nlstate;i++)
3642: prlim[i][i]=mobaverage[(int)age][i][ij];
3643: }
3644: }
3645:
3646: /* This for computing probability of death (h=1 means
3647: computed over hstepm (estepm) matrices product = hstepm*stepm months)
3648: as a weighted average of prlim.
3649: */
3650: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3651: for(i=1,gmp[j]=0.;i<= nlstate; i++)
3652: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3653: }
3654: /* end probability of death */
3655:
3656: fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
3657: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3658: fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
3659: for(i=1; i<=nlstate;i++){
3660: fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
3661: }
3662: }
3663: fprintf(ficresprobmorprev,"\n");
3664:
3665: fprintf(ficresvij,"%.0f ",age );
3666: for(i=1; i<=nlstate;i++)
3667: for(j=1; j<=nlstate;j++){
3668: fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
3669: }
3670: fprintf(ficresvij,"\n");
3671: free_matrix(gp,0,nhstepm,1,nlstate);
3672: free_matrix(gm,0,nhstepm,1,nlstate);
3673: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
3674: free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
3675: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3676: } /* End age */
3677: free_vector(gpp,nlstate+1,nlstate+ndeath);
3678: free_vector(gmp,nlstate+1,nlstate+ndeath);
3679: free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
3680: free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
3681: fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
3682: /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
3683: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
3684: /* fprintf(ficgp,"\n plot \"%s\" u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
3685: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
3686: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
3687: fprintf(ficgp,"\n plot \"%s\" u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
3688: fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
3689: fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
3690: fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
3691: 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);
3692: /* 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);
3693: */
3694: /* fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
3695: fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
3696:
3697: free_vector(xp,1,npar);
3698: free_matrix(doldm,1,nlstate,1,nlstate);
3699: free_matrix(dnewm,1,nlstate,1,npar);
3700: free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3701: free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
3702: free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3703: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3704: fclose(ficresprobmorprev);
3705: fflush(ficgp);
3706: fflush(fichtm);
3707: } /* end varevsij */
3708:
3709: /************ Variance of prevlim ******************/
3710: 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[])
3711: {
3712: /* Variance of prevalence limit */
3713: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
3714:
3715: double **dnewm,**doldm;
3716: int i, j, nhstepm, hstepm;
3717: double *xp;
3718: double *gp, *gm;
3719: double **gradg, **trgradg;
3720: double age,agelim;
3721: int theta;
3722:
3723: pstamp(ficresvpl);
3724: fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
3725: fprintf(ficresvpl,"# Age");
3726: for(i=1; i<=nlstate;i++)
3727: fprintf(ficresvpl," %1d-%1d",i,i);
3728: fprintf(ficresvpl,"\n");
3729:
3730: xp=vector(1,npar);
3731: dnewm=matrix(1,nlstate,1,npar);
3732: doldm=matrix(1,nlstate,1,nlstate);
3733:
3734: hstepm=1*YEARM; /* Every year of age */
3735: hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
3736: agelim = AGESUP;
3737: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3738: nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3739: if (stepm >= YEARM) hstepm=1;
3740: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
3741: gradg=matrix(1,npar,1,nlstate);
3742: gp=vector(1,nlstate);
3743: gm=vector(1,nlstate);
3744:
3745: for(theta=1; theta <=npar; theta++){
3746: for(i=1; i<=npar; i++){ /* Computes gradient */
3747: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3748: }
3749: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3750: for(i=1;i<=nlstate;i++)
3751: gp[i] = prlim[i][i];
3752:
3753: for(i=1; i<=npar; i++) /* Computes gradient */
3754: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3755: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3756: for(i=1;i<=nlstate;i++)
3757: gm[i] = prlim[i][i];
3758:
3759: for(i=1;i<=nlstate;i++)
3760: gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
3761: } /* End theta */
3762:
3763: trgradg =matrix(1,nlstate,1,npar);
3764:
3765: for(j=1; j<=nlstate;j++)
3766: for(theta=1; theta <=npar; theta++)
3767: trgradg[j][theta]=gradg[theta][j];
3768:
3769: for(i=1;i<=nlstate;i++)
3770: varpl[i][(int)age] =0.;
3771: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
3772: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
3773: for(i=1;i<=nlstate;i++)
3774: varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
3775:
3776: fprintf(ficresvpl,"%.0f ",age );
3777: for(i=1; i<=nlstate;i++)
3778: fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
3779: fprintf(ficresvpl,"\n");
3780: free_vector(gp,1,nlstate);
3781: free_vector(gm,1,nlstate);
3782: free_matrix(gradg,1,npar,1,nlstate);
3783: free_matrix(trgradg,1,nlstate,1,npar);
3784: } /* End age */
3785:
3786: free_vector(xp,1,npar);
3787: free_matrix(doldm,1,nlstate,1,npar);
3788: free_matrix(dnewm,1,nlstate,1,nlstate);
3789:
3790: }
3791:
3792: /************ Variance of one-step probabilities ******************/
3793: 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[])
3794: {
3795: int i, j=0, k1, l1, tj;
3796: int k2, l2, j1, z1;
3797: int k=0, l;
3798: int first=1, first1, first2;
3799: double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
3800: double **dnewm,**doldm;
3801: double *xp;
3802: double *gp, *gm;
3803: double **gradg, **trgradg;
3804: double **mu;
3805: double age, cov[NCOVMAX+1];
3806: double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
3807: int theta;
3808: char fileresprob[FILENAMELENGTH];
3809: char fileresprobcov[FILENAMELENGTH];
3810: char fileresprobcor[FILENAMELENGTH];
3811: double ***varpij;
3812:
3813: strcpy(fileresprob,"prob");
3814: strcat(fileresprob,fileres);
3815: if((ficresprob=fopen(fileresprob,"w"))==NULL) {
3816: printf("Problem with resultfile: %s\n", fileresprob);
3817: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
3818: }
3819: strcpy(fileresprobcov,"probcov");
3820: strcat(fileresprobcov,fileres);
3821: if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
3822: printf("Problem with resultfile: %s\n", fileresprobcov);
3823: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
3824: }
3825: strcpy(fileresprobcor,"probcor");
3826: strcat(fileresprobcor,fileres);
3827: if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
3828: printf("Problem with resultfile: %s\n", fileresprobcor);
3829: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
3830: }
3831: printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3832: fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3833: printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3834: fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3835: printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3836: fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3837: pstamp(ficresprob);
3838: fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
3839: fprintf(ficresprob,"# Age");
3840: pstamp(ficresprobcov);
3841: fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
3842: fprintf(ficresprobcov,"# Age");
3843: pstamp(ficresprobcor);
3844: fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
3845: fprintf(ficresprobcor,"# Age");
3846:
3847:
3848: for(i=1; i<=nlstate;i++)
3849: for(j=1; j<=(nlstate+ndeath);j++){
3850: fprintf(ficresprob," p%1d-%1d (SE)",i,j);
3851: fprintf(ficresprobcov," p%1d-%1d ",i,j);
3852: fprintf(ficresprobcor," p%1d-%1d ",i,j);
3853: }
3854: /* fprintf(ficresprob,"\n");
3855: fprintf(ficresprobcov,"\n");
3856: fprintf(ficresprobcor,"\n");
3857: */
3858: xp=vector(1,npar);
3859: dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3860: doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
3861: mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
3862: varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
3863: first=1;
3864: fprintf(ficgp,"\n# Routine varprob");
3865: fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
3866: fprintf(fichtm,"\n");
3867:
3868: fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
3869: fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
3870: file %s<br>\n",optionfilehtmcov);
3871: fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
3872: and drawn. It helps understanding how is the covariance between two incidences.\
3873: They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
3874: 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. \
3875: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
3876: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
3877: standard deviations wide on each axis. <br>\
3878: Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
3879: and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
3880: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
3881:
3882: cov[1]=1;
3883: /* tj=cptcoveff; */
3884: tj = (int) pow(2,cptcoveff);
3885: if (cptcovn<1) {tj=1;ncodemax[1]=1;}
3886: j1=0;
3887: for(j1=1; j1<=tj;j1++){
3888: /*for(i1=1; i1<=ncodemax[t];i1++){ */
3889: /*j1++;*/
3890: if (cptcovn>0) {
3891: fprintf(ficresprob, "\n#********** Variable ");
3892: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3893: fprintf(ficresprob, "**********\n#\n");
3894: fprintf(ficresprobcov, "\n#********** Variable ");
3895: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3896: fprintf(ficresprobcov, "**********\n#\n");
3897:
3898: fprintf(ficgp, "\n#********** Variable ");
3899: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3900: fprintf(ficgp, "**********\n#\n");
3901:
3902:
3903: fprintf(fichtmcov, "\n<hr size=\"2\" color=\"#EC5E5E\">********** Variable ");
3904: for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3905: fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
3906:
3907: fprintf(ficresprobcor, "\n#********** Variable ");
3908: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3909: fprintf(ficresprobcor, "**********\n#");
3910: }
3911:
3912: gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
3913: trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3914: gp=vector(1,(nlstate)*(nlstate+ndeath));
3915: gm=vector(1,(nlstate)*(nlstate+ndeath));
3916: for (age=bage; age<=fage; age ++){
3917: cov[2]=age;
3918: for (k=1; k<=cptcovn;k++) {
3919: cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
3920: * 1 1 1 1 1
3921: * 2 2 1 1 1
3922: * 3 1 2 1 1
3923: */
3924: /* nbcode[1][1]=0 nbcode[1][2]=1;*/
3925: }
3926: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
3927: for (k=1; k<=cptcovprod;k++)
3928: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
3929:
3930:
3931: for(theta=1; theta <=npar; theta++){
3932: for(i=1; i<=npar; i++)
3933: xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
3934:
3935: pmij(pmmij,cov,ncovmodel,xp,nlstate);
3936:
3937: k=0;
3938: for(i=1; i<= (nlstate); i++){
3939: for(j=1; j<=(nlstate+ndeath);j++){
3940: k=k+1;
3941: gp[k]=pmmij[i][j];
3942: }
3943: }
3944:
3945: for(i=1; i<=npar; i++)
3946: xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
3947:
3948: pmij(pmmij,cov,ncovmodel,xp,nlstate);
3949: k=0;
3950: for(i=1; i<=(nlstate); i++){
3951: for(j=1; j<=(nlstate+ndeath);j++){
3952: k=k+1;
3953: gm[k]=pmmij[i][j];
3954: }
3955: }
3956:
3957: for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
3958: gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];
3959: }
3960:
3961: for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
3962: for(theta=1; theta <=npar; theta++)
3963: trgradg[j][theta]=gradg[theta][j];
3964:
3965: matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
3966: matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
3967:
3968: pmij(pmmij,cov,ncovmodel,x,nlstate);
3969:
3970: k=0;
3971: for(i=1; i<=(nlstate); i++){
3972: for(j=1; j<=(nlstate+ndeath);j++){
3973: k=k+1;
3974: mu[k][(int) age]=pmmij[i][j];
3975: }
3976: }
3977: for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
3978: for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
3979: varpij[i][j][(int)age] = doldm[i][j];
3980:
3981: /*printf("\n%d ",(int)age);
3982: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
3983: printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
3984: fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
3985: }*/
3986:
3987: fprintf(ficresprob,"\n%d ",(int)age);
3988: fprintf(ficresprobcov,"\n%d ",(int)age);
3989: fprintf(ficresprobcor,"\n%d ",(int)age);
3990:
3991: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
3992: fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
3993: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
3994: fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
3995: fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
3996: }
3997: i=0;
3998: for (k=1; k<=(nlstate);k++){
3999: for (l=1; l<=(nlstate+ndeath);l++){
4000: i++;
4001: fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
4002: fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
4003: for (j=1; j<=i;j++){
4004: /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
4005: fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
4006: fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
4007: }
4008: }
4009: }/* end of loop for state */
4010: } /* end of loop for age */
4011: free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
4012: free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
4013: free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4014: free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4015:
4016: /* Confidence intervalle of pij */
4017: /*
4018: fprintf(ficgp,"\nunset parametric;unset label");
4019: fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
4020: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
4021: 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);
4022: fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
4023: fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
4024: fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
4025: */
4026:
4027: /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
4028: first1=1;first2=2;
4029: for (k2=1; k2<=(nlstate);k2++){
4030: for (l2=1; l2<=(nlstate+ndeath);l2++){
4031: if(l2==k2) continue;
4032: j=(k2-1)*(nlstate+ndeath)+l2;
4033: for (k1=1; k1<=(nlstate);k1++){
4034: for (l1=1; l1<=(nlstate+ndeath);l1++){
4035: if(l1==k1) continue;
4036: i=(k1-1)*(nlstate+ndeath)+l1;
4037: if(i<=j) continue;
4038: for (age=bage; age<=fage; age ++){
4039: if ((int)age %5==0){
4040: v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
4041: v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
4042: cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
4043: mu1=mu[i][(int) age]/stepm*YEARM ;
4044: mu2=mu[j][(int) age]/stepm*YEARM;
4045: c12=cv12/sqrt(v1*v2);
4046: /* Computing eigen value of matrix of covariance */
4047: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
4048: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
4049: if ((lc2 <0) || (lc1 <0) ){
4050: if(first2==1){
4051: first1=0;
4052: 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);
4053: }
4054: 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);
4055: /* lc1=fabs(lc1); */ /* If we want to have them positive */
4056: /* lc2=fabs(lc2); */
4057: }
4058:
4059: /* Eigen vectors */
4060: v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
4061: /*v21=sqrt(1.-v11*v11); *//* error */
4062: v21=(lc1-v1)/cv12*v11;
4063: v12=-v21;
4064: v22=v11;
4065: tnalp=v21/v11;
4066: if(first1==1){
4067: first1=0;
4068: 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);
4069: }
4070: 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);
4071: /*printf(fignu*/
4072: /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
4073: /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
4074: if(first==1){
4075: first=0;
4076: fprintf(ficgp,"\nset parametric;unset label");
4077: 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);
4078: fprintf(ficgp,"\nset ter png small size 320, 240");
4079: fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
4080: :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
4081: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
4082: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
4083: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4084: fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4085: fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
4086: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4087: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4088: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4089: 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",\
4090: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4091: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4092: }else{
4093: first=0;
4094: fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
4095: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4096: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4097: 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",\
4098: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4099: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4100: }/* if first */
4101: } /* age mod 5 */
4102: } /* end loop age */
4103: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4104: first=1;
4105: } /*l12 */
4106: } /* k12 */
4107: } /*l1 */
4108: }/* k1 */
4109: /* } */ /* loop covariates */
4110: }
4111: free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
4112: free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
4113: free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4114: free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
4115: free_vector(xp,1,npar);
4116: fclose(ficresprob);
4117: fclose(ficresprobcov);
4118: fclose(ficresprobcor);
4119: fflush(ficgp);
4120: fflush(fichtmcov);
4121: }
4122:
4123:
4124: /******************* Printing html file ***********/
4125: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
4126: int lastpass, int stepm, int weightopt, char model[],\
4127: int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
4128: int popforecast, int estepm ,\
4129: double jprev1, double mprev1,double anprev1, \
4130: double jprev2, double mprev2,double anprev2){
4131: int jj1, k1, i1, cpt;
4132:
4133: fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
4134: <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
4135: </ul>");
4136: fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
4137: - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
4138: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
4139: fprintf(fichtm,"\
4140: - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
4141: stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
4142: fprintf(fichtm,"\
4143: - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
4144: subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
4145: fprintf(fichtm,"\
4146: - (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): \
4147: <a href=\"%s\">%s</a> <br>\n",
4148: estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
4149: fprintf(fichtm,"\
4150: - Population projections by age and states: \
4151: <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
4152:
4153: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
4154:
4155: m=pow(2,cptcoveff);
4156: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4157:
4158: jj1=0;
4159: for(k1=1; k1<=m;k1++){
4160: for(i1=1; i1<=ncodemax[k1];i1++){
4161: jj1++;
4162: if (cptcovn > 0) {
4163: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4164: for (cpt=1; cpt<=cptcoveff;cpt++)
4165: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4166: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4167: }
4168: /* Pij */
4169: 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> \
4170: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
4171: /* Quasi-incidences */
4172: fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
4173: 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> \
4174: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
4175: /* Period (stable) prevalence in each health state */
4176: for(cpt=1; cpt<=nlstate;cpt++){
4177: fprintf(fichtm,"<br>- Convergence to period (stable) prevalence in state %d. Or probability to be in state %d being in state (1 to %d) at different ages. <a href=\"%s%d_%d.png\">%s%d_%d.png</a><br> \
4178: <img src=\"%s%d_%d.png\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
4179: }
4180: for(cpt=1; cpt<=nlstate;cpt++) {
4181: 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> \
4182: <img src=\"%s%d%d.png\">",cpt,nlstate,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
4183: }
4184: } /* end i1 */
4185: }/* End k1 */
4186: fprintf(fichtm,"</ul>");
4187:
4188:
4189: fprintf(fichtm,"\
4190: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
4191: - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
4192:
4193: fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4194: subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
4195: fprintf(fichtm,"\
4196: - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4197: subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
4198:
4199: fprintf(fichtm,"\
4200: - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4201: subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
4202: fprintf(fichtm,"\
4203: - 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): \
4204: <a href=\"%s\">%s</a> <br>\n</li>",
4205: estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
4206: fprintf(fichtm,"\
4207: - (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): \
4208: <a href=\"%s\">%s</a> <br>\n</li>",
4209: estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
4210: fprintf(fichtm,"\
4211: - 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",
4212: estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
4213: fprintf(fichtm,"\
4214: - 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",
4215: estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
4216: fprintf(fichtm,"\
4217: - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
4218: subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
4219:
4220: /* if(popforecast==1) fprintf(fichtm,"\n */
4221: /* - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
4222: /* - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
4223: /* <br>",fileres,fileres,fileres,fileres); */
4224: /* else */
4225: /* 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); */
4226: fflush(fichtm);
4227: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
4228:
4229: m=pow(2,cptcoveff);
4230: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4231:
4232: jj1=0;
4233: for(k1=1; k1<=m;k1++){
4234: for(i1=1; i1<=ncodemax[k1];i1++){
4235: jj1++;
4236: if (cptcovn > 0) {
4237: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4238: for (cpt=1; cpt<=cptcoveff;cpt++)
4239: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4240: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4241: }
4242: for(cpt=1; cpt<=nlstate;cpt++) {
4243: fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
4244: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
4245: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);
4246: }
4247: fprintf(fichtm,"\n<br>- Total life expectancy by age and \
4248: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
4249: true period expectancies (those weighted with period prevalences are also\
4250: drawn in addition to the population based expectancies computed using\
4251: observed and cahotic prevalences: %s%d.png<br>\
4252: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
4253: } /* end i1 */
4254: }/* End k1 */
4255: fprintf(fichtm,"</ul>");
4256: fflush(fichtm);
4257: }
4258:
4259: /******************* Gnuplot file **************/
4260: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4261:
4262: char dirfileres[132],optfileres[132];
4263: int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
4264: int ng=0;
4265: /* if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
4266: /* printf("Problem with file %s",optionfilegnuplot); */
4267: /* fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
4268: /* } */
4269:
4270: /*#ifdef windows */
4271: fprintf(ficgp,"cd \"%s\" \n",pathc);
4272: /*#endif */
4273: m=pow(2,cptcoveff);
4274:
4275: strcpy(dirfileres,optionfilefiname);
4276: strcpy(optfileres,"vpl");
4277: /* 1eme*/
4278: fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
4279: for (cpt=1; cpt<= nlstate ; cpt ++) {
4280: for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
4281: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
4282: fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
4283: fprintf(ficgp,"set xlabel \"Age\" \n\
4284: set ylabel \"Probability\" \n\
4285: set ter png small size 320, 240\n\
4286: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
4287:
4288: for (i=1; i<= nlstate ; i ++) {
4289: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4290: else fprintf(ficgp," %%*lf (%%*lf)");
4291: }
4292: 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);
4293: for (i=1; i<= nlstate ; i ++) {
4294: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4295: else fprintf(ficgp," %%*lf (%%*lf)");
4296: }
4297: 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);
4298: for (i=1; i<= nlstate ; i ++) {
4299: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4300: else fprintf(ficgp," %%*lf (%%*lf)");
4301: }
4302: 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));
4303: }
4304: }
4305: /*2 eme*/
4306: fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
4307: for (k1=1; k1<= m ; k1 ++) {
4308: fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
4309: fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
4310:
4311: for (i=1; i<= nlstate+1 ; i ++) {
4312: k=2*i;
4313: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4314: for (j=1; j<= nlstate+1 ; j ++) {
4315: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4316: else fprintf(ficgp," %%*lf (%%*lf)");
4317: }
4318: if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
4319: else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
4320: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4321: for (j=1; j<= nlstate+1 ; j ++) {
4322: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4323: else fprintf(ficgp," %%*lf (%%*lf)");
4324: }
4325: fprintf(ficgp,"\" t\"\" w l lt 0,");
4326: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4327: for (j=1; j<= nlstate+1 ; j ++) {
4328: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4329: else fprintf(ficgp," %%*lf (%%*lf)");
4330: }
4331: if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
4332: else fprintf(ficgp,"\" t\"\" w l lt 0,");
4333: }
4334: }
4335:
4336: /*3eme*/
4337:
4338: for (k1=1; k1<= m ; k1 ++) {
4339: for (cpt=1; cpt<= nlstate ; cpt ++) {
4340: /* k=2+nlstate*(2*cpt-2); */
4341: k=2+(nlstate+1)*(cpt-1);
4342: fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
4343: fprintf(ficgp,"set ter png small size 320, 240\n\
4344: 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);
4345: /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4346: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4347: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4348: fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4349: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4350: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4351:
4352: */
4353: for (i=1; i< nlstate ; i ++) {
4354: 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);
4355: /* 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);*/
4356:
4357: }
4358: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
4359: }
4360: }
4361:
4362: /* CV preval stable (period) */
4363: for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
4364: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
4365: k=3;
4366: fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
4367: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
4368: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
4369: set ter png small size 320, 240\n\
4370: unset log y\n\
4371: plot [%.f:%.f] ", ageminpar, agemaxpar);
4372: for (i=1; i<= nlstate ; i ++){
4373: if(i==1)
4374: fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
4375: else
4376: fprintf(ficgp,", '' ");
4377: l=(nlstate+ndeath)*(i-1)+1;
4378: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
4379: for (j=1; j<= (nlstate-1) ; j ++)
4380: fprintf(ficgp,"+$%d",k+l+j);
4381: fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
4382: } /* nlstate */
4383: fprintf(ficgp,"\n");
4384: } /* end cpt state*/
4385: } /* end covariate */
4386:
4387: /* proba elementaires */
4388: for(i=1,jk=1; i <=nlstate; i++){
4389: for(k=1; k <=(nlstate+ndeath); k++){
4390: if (k != i) {
4391: for(j=1; j <=ncovmodel; j++){
4392: fprintf(ficgp,"p%d=%f ",jk,p[jk]);
4393: jk++;
4394: fprintf(ficgp,"\n");
4395: }
4396: }
4397: }
4398: }
4399: /*goto avoid;*/
4400: for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
4401: for(jk=1; jk <=m; jk++) {
4402: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);
4403: if (ng==2)
4404: fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
4405: else
4406: fprintf(ficgp,"\nset title \"Probability\"\n");
4407: fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot [%.f:%.f] ",ageminpar,agemaxpar);
4408: i=1;
4409: for(k2=1; k2<=nlstate; k2++) {
4410: k3=i;
4411: for(k=1; k<=(nlstate+ndeath); k++) {
4412: if (k != k2){
4413: if(ng==2)
4414: fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
4415: else
4416: fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
4417: ij=1;/* To be checked else nbcode[0][0] wrong */
4418: for(j=3; j <=ncovmodel; j++) {
4419: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /\* Bug valgrind *\/ */
4420: /* /\*fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);*\/ */
4421: /* ij++; */
4422: /* } */
4423: /* else */
4424: fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4425: }
4426: fprintf(ficgp,")/(1");
4427:
4428: for(k1=1; k1 <=nlstate; k1++){
4429: fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
4430: ij=1;
4431: for(j=3; j <=ncovmodel; j++){
4432: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { */
4433: /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]); */
4434: /* ij++; */
4435: /* } */
4436: /* else */
4437: fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4438: }
4439: fprintf(ficgp,")");
4440: }
4441: fprintf(ficgp,") t \"p%d%d\" ", k2,k);
4442: if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
4443: i=i+ncovmodel;
4444: }
4445: } /* end k */
4446: } /* end k2 */
4447: } /* end jk */
4448: } /* end ng */
4449: /* avoid: */
4450: fflush(ficgp);
4451: } /* end gnuplot */
4452:
4453:
4454: /*************** Moving average **************/
4455: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
4456:
4457: int i, cpt, cptcod;
4458: int modcovmax =1;
4459: int mobilavrange, mob;
4460: double age;
4461:
4462: modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
4463: a covariate has 2 modalities */
4464: if (cptcovn<1) modcovmax=1; /* At least 1 pass */
4465:
4466: if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
4467: if(mobilav==1) mobilavrange=5; /* default */
4468: else mobilavrange=mobilav;
4469: for (age=bage; age<=fage; age++)
4470: for (i=1; i<=nlstate;i++)
4471: for (cptcod=1;cptcod<=modcovmax;cptcod++)
4472: mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
4473: /* We keep the original values on the extreme ages bage, fage and for
4474: fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
4475: we use a 5 terms etc. until the borders are no more concerned.
4476: */
4477: for (mob=3;mob <=mobilavrange;mob=mob+2){
4478: for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
4479: for (i=1; i<=nlstate;i++){
4480: for (cptcod=1;cptcod<=modcovmax;cptcod++){
4481: mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
4482: for (cpt=1;cpt<=(mob-1)/2;cpt++){
4483: mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
4484: mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
4485: }
4486: mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
4487: }
4488: }
4489: }/* end age */
4490: }/* end mob */
4491: }else return -1;
4492: return 0;
4493: }/* End movingaverage */
4494:
4495:
4496: /************** Forecasting ******************/
4497: void 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){
4498: /* proj1, year, month, day of starting projection
4499: agemin, agemax range of age
4500: dateprev1 dateprev2 range of dates during which prevalence is computed
4501: anproj2 year of en of projection (same day and month as proj1).
4502: */
4503: int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
4504: double agec; /* generic age */
4505: double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
4506: double *popeffectif,*popcount;
4507: double ***p3mat;
4508: double ***mobaverage;
4509: char fileresf[FILENAMELENGTH];
4510:
4511: agelim=AGESUP;
4512: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4513:
4514: strcpy(fileresf,"f");
4515: strcat(fileresf,fileres);
4516: if((ficresf=fopen(fileresf,"w"))==NULL) {
4517: printf("Problem with forecast resultfile: %s\n", fileresf);
4518: fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
4519: }
4520: printf("Computing forecasting: result on file '%s' \n", fileresf);
4521: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
4522:
4523: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4524:
4525: if (mobilav!=0) {
4526: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4527: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4528: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4529: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4530: }
4531: }
4532:
4533: stepsize=(int) (stepm+YEARM-1)/YEARM;
4534: if (stepm<=12) stepsize=1;
4535: if(estepm < stepm){
4536: printf ("Problem %d lower than %d\n",estepm, stepm);
4537: }
4538: else hstepm=estepm;
4539:
4540: hstepm=hstepm/stepm;
4541: yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp and
4542: fractional in yp1 */
4543: anprojmean=yp;
4544: yp2=modf((yp1*12),&yp);
4545: mprojmean=yp;
4546: yp1=modf((yp2*30.5),&yp);
4547: jprojmean=yp;
4548: if(jprojmean==0) jprojmean=1;
4549: if(mprojmean==0) jprojmean=1;
4550:
4551: i1=cptcoveff;
4552: if (cptcovn < 1){i1=1;}
4553:
4554: fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
4555:
4556: fprintf(ficresf,"#****** Routine prevforecast **\n");
4557:
4558: /* if (h==(int)(YEARM*yearp)){ */
4559: for(cptcov=1, k=0;cptcov<=i1;cptcov++){
4560: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4561: k=k+1;
4562: fprintf(ficresf,"\n#******");
4563: for(j=1;j<=cptcoveff;j++) {
4564: 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]]);
4565: }
4566: fprintf(ficresf,"******\n");
4567: fprintf(ficresf,"# Covariate valuofcovar yearproj age");
4568: for(j=1; j<=nlstate+ndeath;j++){
4569: for(i=1; i<=nlstate;i++)
4570: fprintf(ficresf," p%d%d",i,j);
4571: fprintf(ficresf," p.%d",j);
4572: }
4573: for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
4574: fprintf(ficresf,"\n");
4575: fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);
4576:
4577: for (agec=fage; agec>=(ageminpar-1); agec--){
4578: nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
4579: nhstepm = nhstepm/hstepm;
4580: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4581: oldm=oldms;savm=savms;
4582: hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
4583:
4584: for (h=0; h<=nhstepm; h++){
4585: if (h*hstepm/YEARM*stepm ==yearp) {
4586: fprintf(ficresf,"\n");
4587: for(j=1;j<=cptcoveff;j++)
4588: fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4589: fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
4590: }
4591: for(j=1; j<=nlstate+ndeath;j++) {
4592: ppij=0.;
4593: for(i=1; i<=nlstate;i++) {
4594: if (mobilav==1)
4595: ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
4596: else {
4597: ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
4598: }
4599: if (h*hstepm/YEARM*stepm== yearp) {
4600: fprintf(ficresf," %.3f", p3mat[i][j][h]);
4601: }
4602: } /* end i */
4603: if (h*hstepm/YEARM*stepm==yearp) {
4604: fprintf(ficresf," %.3f", ppij);
4605: }
4606: }/* end j */
4607: } /* end h */
4608: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4609: } /* end agec */
4610: } /* end yearp */
4611: } /* end cptcod */
4612: } /* end cptcov */
4613:
4614: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4615:
4616: fclose(ficresf);
4617: }
4618:
4619: /************** Forecasting *****not tested NB*************/
4620: void 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){
4621:
4622: int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
4623: int *popage;
4624: double calagedatem, agelim, kk1, kk2;
4625: double *popeffectif,*popcount;
4626: double ***p3mat,***tabpop,***tabpopprev;
4627: double ***mobaverage;
4628: char filerespop[FILENAMELENGTH];
4629:
4630: tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4631: tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4632: agelim=AGESUP;
4633: calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
4634:
4635: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4636:
4637:
4638: strcpy(filerespop,"pop");
4639: strcat(filerespop,fileres);
4640: if((ficrespop=fopen(filerespop,"w"))==NULL) {
4641: printf("Problem with forecast resultfile: %s\n", filerespop);
4642: fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
4643: }
4644: printf("Computing forecasting: result on file '%s' \n", filerespop);
4645: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
4646:
4647: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4648:
4649: if (mobilav!=0) {
4650: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4651: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4652: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4653: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4654: }
4655: }
4656:
4657: stepsize=(int) (stepm+YEARM-1)/YEARM;
4658: if (stepm<=12) stepsize=1;
4659:
4660: agelim=AGESUP;
4661:
4662: hstepm=1;
4663: hstepm=hstepm/stepm;
4664:
4665: if (popforecast==1) {
4666: if((ficpop=fopen(popfile,"r"))==NULL) {
4667: printf("Problem with population file : %s\n",popfile);exit(0);
4668: fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
4669: }
4670: popage=ivector(0,AGESUP);
4671: popeffectif=vector(0,AGESUP);
4672: popcount=vector(0,AGESUP);
4673:
4674: i=1;
4675: while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
4676:
4677: imx=i;
4678: for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
4679: }
4680:
4681: for(cptcov=1,k=0;cptcov<=i2;cptcov++){
4682: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4683: k=k+1;
4684: fprintf(ficrespop,"\n#******");
4685: for(j=1;j<=cptcoveff;j++) {
4686: fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4687: }
4688: fprintf(ficrespop,"******\n");
4689: fprintf(ficrespop,"# Age");
4690: for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
4691: if (popforecast==1) fprintf(ficrespop," [Population]");
4692:
4693: for (cpt=0; cpt<=0;cpt++) {
4694: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4695:
4696: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4697: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4698: nhstepm = nhstepm/hstepm;
4699:
4700: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4701: oldm=oldms;savm=savms;
4702: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4703:
4704: for (h=0; h<=nhstepm; h++){
4705: if (h==(int) (calagedatem+YEARM*cpt)) {
4706: fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4707: }
4708: for(j=1; j<=nlstate+ndeath;j++) {
4709: kk1=0.;kk2=0;
4710: for(i=1; i<=nlstate;i++) {
4711: if (mobilav==1)
4712: kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
4713: else {
4714: kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
4715: }
4716: }
4717: if (h==(int)(calagedatem+12*cpt)){
4718: tabpop[(int)(agedeb)][j][cptcod]=kk1;
4719: /*fprintf(ficrespop," %.3f", kk1);
4720: if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
4721: }
4722: }
4723: for(i=1; i<=nlstate;i++){
4724: kk1=0.;
4725: for(j=1; j<=nlstate;j++){
4726: kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
4727: }
4728: tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
4729: }
4730:
4731: if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
4732: fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
4733: }
4734: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4735: }
4736: }
4737:
4738: /******/
4739:
4740: for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
4741: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4742: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4743: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4744: nhstepm = nhstepm/hstepm;
4745:
4746: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4747: oldm=oldms;savm=savms;
4748: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4749: for (h=0; h<=nhstepm; h++){
4750: if (h==(int) (calagedatem+YEARM*cpt)) {
4751: fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4752: }
4753: for(j=1; j<=nlstate+ndeath;j++) {
4754: kk1=0.;kk2=0;
4755: for(i=1; i<=nlstate;i++) {
4756: kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];
4757: }
4758: if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);
4759: }
4760: }
4761: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4762: }
4763: }
4764: }
4765: }
4766:
4767: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4768:
4769: if (popforecast==1) {
4770: free_ivector(popage,0,AGESUP);
4771: free_vector(popeffectif,0,AGESUP);
4772: free_vector(popcount,0,AGESUP);
4773: }
4774: free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4775: free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4776: fclose(ficrespop);
4777: } /* End of popforecast */
4778:
4779: int fileappend(FILE *fichier, char *optionfich)
4780: {
4781: if((fichier=fopen(optionfich,"a"))==NULL) {
4782: printf("Problem with file: %s\n", optionfich);
4783: fprintf(ficlog,"Problem with file: %s\n", optionfich);
4784: return (0);
4785: }
4786: fflush(fichier);
4787: return (1);
4788: }
4789:
4790:
4791: /**************** function prwizard **********************/
4792: void prwizard(int ncovmodel, int nlstate, int ndeath, char model[], FILE *ficparo)
4793: {
4794:
4795: /* Wizard to print covariance matrix template */
4796:
4797: char ca[32], cb[32];
4798: int i,j, k, li, lj, lk, ll, jj, npar, itimes;
4799: int numlinepar;
4800:
4801: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4802: fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4803: for(i=1; i <=nlstate; i++){
4804: jj=0;
4805: for(j=1; j <=nlstate+ndeath; j++){
4806: if(j==i) continue;
4807: jj++;
4808: /*ca[0]= k+'a'-1;ca[1]='\0';*/
4809: printf("%1d%1d",i,j);
4810: fprintf(ficparo,"%1d%1d",i,j);
4811: for(k=1; k<=ncovmodel;k++){
4812: /* printf(" %lf",param[i][j][k]); */
4813: /* fprintf(ficparo," %lf",param[i][j][k]); */
4814: printf(" 0.");
4815: fprintf(ficparo," 0.");
4816: }
4817: printf("\n");
4818: fprintf(ficparo,"\n");
4819: }
4820: }
4821: printf("# Scales (for hessian or gradient estimation)\n");
4822: fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
4823: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
4824: for(i=1; i <=nlstate; i++){
4825: jj=0;
4826: for(j=1; j <=nlstate+ndeath; j++){
4827: if(j==i) continue;
4828: jj++;
4829: fprintf(ficparo,"%1d%1d",i,j);
4830: printf("%1d%1d",i,j);
4831: fflush(stdout);
4832: for(k=1; k<=ncovmodel;k++){
4833: /* printf(" %le",delti3[i][j][k]); */
4834: /* fprintf(ficparo," %le",delti3[i][j][k]); */
4835: printf(" 0.");
4836: fprintf(ficparo," 0.");
4837: }
4838: numlinepar++;
4839: printf("\n");
4840: fprintf(ficparo,"\n");
4841: }
4842: }
4843: printf("# Covariance matrix\n");
4844: /* # 121 Var(a12)\n\ */
4845: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4846: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
4847: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
4848: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
4849: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
4850: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
4851: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4852: fflush(stdout);
4853: fprintf(ficparo,"# Covariance matrix\n");
4854: /* # 121 Var(a12)\n\ */
4855: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4856: /* # ...\n\ */
4857: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4858:
4859: for(itimes=1;itimes<=2;itimes++){
4860: jj=0;
4861: for(i=1; i <=nlstate; i++){
4862: for(j=1; j <=nlstate+ndeath; j++){
4863: if(j==i) continue;
4864: for(k=1; k<=ncovmodel;k++){
4865: jj++;
4866: ca[0]= k+'a'-1;ca[1]='\0';
4867: if(itimes==1){
4868: printf("#%1d%1d%d",i,j,k);
4869: fprintf(ficparo,"#%1d%1d%d",i,j,k);
4870: }else{
4871: printf("%1d%1d%d",i,j,k);
4872: fprintf(ficparo,"%1d%1d%d",i,j,k);
4873: /* printf(" %.5le",matcov[i][j]); */
4874: }
4875: ll=0;
4876: for(li=1;li <=nlstate; li++){
4877: for(lj=1;lj <=nlstate+ndeath; lj++){
4878: if(lj==li) continue;
4879: for(lk=1;lk<=ncovmodel;lk++){
4880: ll++;
4881: if(ll<=jj){
4882: cb[0]= lk +'a'-1;cb[1]='\0';
4883: if(ll<jj){
4884: if(itimes==1){
4885: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4886: fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4887: }else{
4888: printf(" 0.");
4889: fprintf(ficparo," 0.");
4890: }
4891: }else{
4892: if(itimes==1){
4893: printf(" Var(%s%1d%1d)",ca,i,j);
4894: fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
4895: }else{
4896: printf(" 0.");
4897: fprintf(ficparo," 0.");
4898: }
4899: }
4900: }
4901: } /* end lk */
4902: } /* end lj */
4903: } /* end li */
4904: printf("\n");
4905: fprintf(ficparo,"\n");
4906: numlinepar++;
4907: } /* end k*/
4908: } /*end j */
4909: } /* end i */
4910: } /* end itimes */
4911:
4912: } /* end of prwizard */
4913: /******************* Gompertz Likelihood ******************************/
4914: double gompertz(double x[])
4915: {
4916: double A,B,L=0.0,sump=0.,num=0.;
4917: int i,n=0; /* n is the size of the sample */
4918:
4919: for (i=0;i<=imx-1 ; i++) {
4920: sump=sump+weight[i];
4921: /* sump=sump+1;*/
4922: num=num+1;
4923: }
4924:
4925:
4926: /* for (i=0; i<=imx; i++)
4927: 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]);*/
4928:
4929: for (i=1;i<=imx ; i++)
4930: {
4931: if (cens[i] == 1 && wav[i]>1)
4932: A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
4933:
4934: if (cens[i] == 0 && wav[i]>1)
4935: A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
4936: +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);
4937:
4938: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
4939: if (wav[i] > 1 ) { /* ??? */
4940: L=L+A*weight[i];
4941: /* 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]);*/
4942: }
4943: }
4944:
4945: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
4946:
4947: return -2*L*num/sump;
4948: }
4949:
4950: #ifdef GSL
4951: /******************* Gompertz_f Likelihood ******************************/
4952: double gompertz_f(const gsl_vector *v, void *params)
4953: {
4954: double A,B,LL=0.0,sump=0.,num=0.;
4955: double *x= (double *) v->data;
4956: int i,n=0; /* n is the size of the sample */
4957:
4958: for (i=0;i<=imx-1 ; i++) {
4959: sump=sump+weight[i];
4960: /* sump=sump+1;*/
4961: num=num+1;
4962: }
4963:
4964:
4965: /* for (i=0; i<=imx; i++)
4966: 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]);*/
4967: printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
4968: for (i=1;i<=imx ; i++)
4969: {
4970: if (cens[i] == 1 && wav[i]>1)
4971: A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
4972:
4973: if (cens[i] == 0 && wav[i]>1)
4974: A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
4975: +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);
4976:
4977: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
4978: if (wav[i] > 1 ) { /* ??? */
4979: LL=LL+A*weight[i];
4980: /* 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]);*/
4981: }
4982: }
4983:
4984: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
4985: printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
4986:
4987: return -2*LL*num/sump;
4988: }
4989: #endif
4990:
4991: /******************* Printing html file ***********/
4992: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
4993: int lastpass, int stepm, int weightopt, char model[],\
4994: int imx, double p[],double **matcov,double agemortsup){
4995: int i,k;
4996:
4997: fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
4998: fprintf(fichtm," mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
4999: for (i=1;i<=2;i++)
5000: 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]));
5001: fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
5002: fprintf(fichtm,"</ul>");
5003:
5004: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
5005:
5006: 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>");
5007:
5008: for (k=agegomp;k<(agemortsup-2);k++)
5009: 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]);
5010:
5011:
5012: fflush(fichtm);
5013: }
5014:
5015: /******************* Gnuplot file **************/
5016: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
5017:
5018: char dirfileres[132],optfileres[132];
5019:
5020: int ng;
5021:
5022:
5023: /*#ifdef windows */
5024: fprintf(ficgp,"cd \"%s\" \n",pathc);
5025: /*#endif */
5026:
5027:
5028: strcpy(dirfileres,optionfilefiname);
5029: strcpy(optfileres,"vpl");
5030: fprintf(ficgp,"set out \"graphmort.png\"\n ");
5031: fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
5032: fprintf(ficgp, "set ter png small size 320, 240\n set log y\n");
5033: /* fprintf(ficgp, "set size 0.65,0.65\n"); */
5034: fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
5035:
5036: }
5037:
5038: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
5039: {
5040:
5041: /*-------- data file ----------*/
5042: FILE *fic;
5043: char dummy[]=" ";
5044: int i=0, j=0, n=0;
5045: int linei, month, year,iout;
5046: char line[MAXLINE], linetmp[MAXLINE];
5047: char stra[MAXLINE], strb[MAXLINE];
5048: char *stratrunc;
5049: int lstra;
5050:
5051:
5052: if((fic=fopen(datafile,"r"))==NULL) {
5053: printf("Problem while opening datafile: %s\n", datafile);return 1;
5054: fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
5055: }
5056:
5057: i=1;
5058: linei=0;
5059: while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
5060: linei=linei+1;
5061: for(j=strlen(line); j>=0;j--){ /* Untabifies line */
5062: if(line[j] == '\t')
5063: line[j] = ' ';
5064: }
5065: for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
5066: ;
5067: };
5068: line[j+1]=0; /* Trims blanks at end of line */
5069: if(line[0]=='#'){
5070: fprintf(ficlog,"Comment line\n%s\n",line);
5071: printf("Comment line\n%s\n",line);
5072: continue;
5073: }
5074: trimbb(linetmp,line); /* Trims multiple blanks in line */
5075: strcpy(line, linetmp);
5076:
5077:
5078: for (j=maxwav;j>=1;j--){
5079: cutv(stra, strb, line, ' ');
5080: if(strb[0]=='.') { /* Missing status */
5081: lval=-1;
5082: }else{
5083: errno=0;
5084: lval=strtol(strb,&endptr,10);
5085: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
5086: if( strb[0]=='\0' || (*endptr != '\0')){
5087: 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);
5088: 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);
5089: return 1;
5090: }
5091: }
5092: s[j][i]=lval;
5093:
5094: strcpy(line,stra);
5095: cutv(stra, strb,line,' ');
5096: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
5097: }
5098: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
5099: month=99;
5100: year=9999;
5101: }else{
5102: 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);
5103: 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);
5104: return 1;
5105: }
5106: anint[j][i]= (double) year;
5107: mint[j][i]= (double)month;
5108: strcpy(line,stra);
5109: } /* ENd Waves */
5110:
5111: cutv(stra, strb,line,' ');
5112: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
5113: }
5114: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
5115: month=99;
5116: year=9999;
5117: }else{
5118: 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);
5119: 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);
5120: return 1;
5121: }
5122: andc[i]=(double) year;
5123: moisdc[i]=(double) month;
5124: strcpy(line,stra);
5125:
5126: cutv(stra, strb,line,' ');
5127: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
5128: }
5129: else if( (iout=sscanf(strb,"%s.", dummy)) != 0){
5130: month=99;
5131: year=9999;
5132: }else{
5133: 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);
5134: 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);
5135: return 1;
5136: }
5137: if (year==9999) {
5138: 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);
5139: 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);
5140: return 1;
5141:
5142: }
5143: annais[i]=(double)(year);
5144: moisnais[i]=(double)(month);
5145: strcpy(line,stra);
5146:
5147: cutv(stra, strb,line,' ');
5148: errno=0;
5149: dval=strtod(strb,&endptr);
5150: if( strb[0]=='\0' || (*endptr != '\0')){
5151: printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight. Exiting.\n",dval, i,line,linei);
5152: 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);
5153: fflush(ficlog);
5154: return 1;
5155: }
5156: weight[i]=dval;
5157: strcpy(line,stra);
5158:
5159: for (j=ncovcol;j>=1;j--){
5160: cutv(stra, strb,line,' ');
5161: if(strb[0]=='.') { /* Missing status */
5162: lval=-1;
5163: }else{
5164: errno=0;
5165: lval=strtol(strb,&endptr,10);
5166: if( strb[0]=='\0' || (*endptr != '\0')){
5167: 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);
5168: 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);
5169: return 1;
5170: }
5171: }
5172: if(lval <-1 || lval >1){
5173: printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
5174: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5175: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5176: For example, for multinomial values like 1, 2 and 3,\n \
5177: build V1=0 V2=0 for the reference value (1),\n \
5178: V1=1 V2=0 for (2) \n \
5179: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5180: output of IMaCh is often meaningless.\n \
5181: Exiting.\n",lval,linei, i,line,j);
5182: fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
5183: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5184: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5185: For example, for multinomial values like 1, 2 and 3,\n \
5186: build V1=0 V2=0 for the reference value (1),\n \
5187: V1=1 V2=0 for (2) \n \
5188: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5189: output of IMaCh is often meaningless.\n \
5190: Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
5191: return 1;
5192: }
5193: covar[j][i]=(double)(lval);
5194: strcpy(line,stra);
5195: }
5196: lstra=strlen(stra);
5197:
5198: if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
5199: stratrunc = &(stra[lstra-9]);
5200: num[i]=atol(stratrunc);
5201: }
5202: else
5203: num[i]=atol(stra);
5204: /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
5205: 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;}*/
5206:
5207: i=i+1;
5208: } /* End loop reading data */
5209:
5210: *imax=i-1; /* Number of individuals */
5211: fclose(fic);
5212:
5213: return (0);
5214: /* endread: */
5215: printf("Exiting readdata: ");
5216: fclose(fic);
5217: return (1);
5218:
5219:
5220:
5221: }
5222: void removespace(char *str) {
5223: char *p1 = str, *p2 = str;
5224: do
5225: while (*p2 == ' ')
5226: p2++;
5227: while (*p1++ == *p2++);
5228: }
5229:
5230: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
5231: * Model V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age
5232: * - cptcovt total number of covariates of the model nbocc(+)+1 = 8
5233: * - cptcovn or number of covariates k of the models excluding age*products =6
5234: * - cptcovage number of covariates with age*products =2
5235: * - cptcovs number of simple covariates
5236: * - 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
5237: * which is a new column after the 9 (ncovcol) variables.
5238: * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
5239: * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
5240: * Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
5241: * - Tvard[k] p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
5242: */
5243: {
5244: int i, j, k, ks;
5245: int j1, k1, k2;
5246: char modelsav[80];
5247: char stra[80], strb[80], strc[80], strd[80],stre[80];
5248:
5249: /*removespace(model);*/
5250: if (strlen(model) >1){ /* If there is at least 1 covariate */
5251: j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
5252: j=nbocc(model,'+'); /**< j=Number of '+' */
5253: j1=nbocc(model,'*'); /**< j1=Number of '*' */
5254: cptcovs=j+1-j1; /**< Number of simple covariates V1+V2*age+V3 +V3*V4=> V1 + V3 =2 */
5255: cptcovt= j+1; /* Number of total covariates in the model V1 + V2*age+ V3 + V3*V4=> 4*/
5256: /* including age products which are counted in cptcovage.
5257: * but the covariates which are products must be treated separately: ncovn=4- 2=2 (V1+V3). */
5258: cptcovprod=j1; /**< Number of products V1*V2 +v3*age = 2 */
5259: cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1 */
5260: strcpy(modelsav,model);
5261: if (strstr(model,"AGE") !=0){
5262: printf("Error. AGE must be in lower case 'age' model=%s ",model);
5263: fprintf(ficlog,"Error. AGE must be in lower case model=%s ",model);fflush(ficlog);
5264: return 1;
5265: }
5266: if (strstr(model,"v") !=0){
5267: printf("Error. 'v' must be in upper case 'V' model=%s ",model);
5268: fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
5269: return 1;
5270: }
5271:
5272: /* Design
5273: * V1 V2 V3 V4 V5 V6 V7 V8 V9 Weight
5274: * < ncovcol=8 >
5275: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
5276: * k= 1 2 3 4 5 6 7 8
5277: * cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
5278: * covar[k,i], value of kth covariate if not including age for individual i:
5279: * covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
5280: * Tvar[k] # of the kth covariate: Tvar[1]=2 Tvar[4]=3 Tvar[8]=8
5281: * if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and
5282: * Tage[++cptcovage]=k
5283: * if products, new covar are created after ncovcol with k1
5284: * Tvar[k]=ncovcol+k1; # of the kth covariate product: Tvar[5]=ncovcol+1=10 Tvar[6]=ncovcol+1=11
5285: * Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
5286: * 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
5287: * Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
5288: * Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
5289: * V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
5290: * < ncovcol=8 >
5291: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 d1 d1 d2 d2
5292: * k= 1 2 3 4 5 6 7 8 9 10 11 12
5293: * Tvar[k]= 2 1 3 3 10 11 8 8 5 6 7 8
5294: * p Tvar[1]@12={2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5295: * p Tprod[1]@2={ 6, 5}
5296: *p Tvard[1][1]@4= {7, 8, 5, 6}
5297: * covar[k][i]= V2 V1 ? V3 V5*V6? V7*V8? ? V8
5298: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
5299: *How to reorganize?
5300: * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
5301: * Tvars {2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5302: * {2, 1, 4, 8, 5, 6, 3, 7}
5303: * Struct []
5304: */
5305:
5306: /* This loop fills the array Tvar from the string 'model'.*/
5307: /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
5308: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 */
5309: /* k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
5310: /* k=3 V4 Tvar[k=3]= 4 (from V4) */
5311: /* k=2 V1 Tvar[k=2]= 1 (from V1) */
5312: /* k=1 Tvar[1]=2 (from V2) */
5313: /* k=5 Tvar[5] */
5314: /* for (k=1; k<=cptcovn;k++) { */
5315: /* cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
5316: /* } */
5317: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
5318: /*
5319: * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
5320: for(k=cptcovt; k>=1;k--) /**< Number of covariates */
5321: Tvar[k]=0;
5322: cptcovage=0;
5323: for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
5324: cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+'
5325: modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */
5326: if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
5327: /* printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
5328: /*scanf("%d",i);*/
5329: if (strchr(strb,'*')) { /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
5330: cutl(strc,strd,strb,'*'); /**< strd*strc Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
5331: if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
5332: /* covar is not filled and then is empty */
5333: cptcovprod--;
5334: cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
5335: Tvar[k]=atoi(stre); /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2 */
5336: cptcovage++; /* Sums the number of covariates which include age as a product */
5337: Tage[cptcovage]=k; /* Tage[1] = 4 */
5338: /*printf("stre=%s ", stre);*/
5339: } else if (strcmp(strd,"age")==0) { /* or age*Vn */
5340: cptcovprod--;
5341: cutl(stre,strb,strc,'V');
5342: Tvar[k]=atoi(stre);
5343: cptcovage++;
5344: Tage[cptcovage]=k;
5345: } else { /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2 strb=V3*V2*/
5346: /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
5347: cptcovn++;
5348: cptcovprodnoage++;k1++;
5349: cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
5350: Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
5351: because this model-covariate is a construction we invent a new column
5352: ncovcol + k1
5353: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
5354: Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
5355: cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
5356: Tprod[k1]=k; /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 */
5357: Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
5358: Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
5359: k2=k2+2;
5360: Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
5361: Tvar[cptcovt+k2+1]=Tvard[k1][2]; /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
5362: for (i=1; i<=lastobs;i++){
5363: /* Computes the new covariate which is a product of
5364: covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
5365: covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
5366: }
5367: } /* End age is not in the model */
5368: } /* End if model includes a product */
5369: else { /* no more sum */
5370: /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
5371: /* scanf("%d",i);*/
5372: cutl(strd,strc,strb,'V');
5373: ks++; /**< Number of simple covariates */
5374: cptcovn++;
5375: Tvar[k]=atoi(strd);
5376: }
5377: strcpy(modelsav,stra); /* modelsav=V2+V1+V4 stra=V2+V1+V4 */
5378: /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
5379: scanf("%d",i);*/
5380: } /* end of loop + */
5381: } /* end model */
5382:
5383: /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
5384: If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
5385:
5386: /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
5387: printf("cptcovprod=%d ", cptcovprod);
5388: fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
5389:
5390: scanf("%d ",i);*/
5391:
5392:
5393: return (0); /* with covar[new additional covariate if product] and Tage if age */
5394: /*endread:*/
5395: printf("Exiting decodemodel: ");
5396: return (1);
5397: }
5398:
5399: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
5400: {
5401: int i, m;
5402:
5403: for (i=1; i<=imx; i++) {
5404: for(m=2; (m<= maxwav); m++) {
5405: if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
5406: anint[m][i]=9999;
5407: s[m][i]=-1;
5408: }
5409: if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
5410: *nberr = *nberr + 1;
5411: 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 (%d)\n",(int)moisdc[i],(int)andc[i],num[i],i, *nberr);
5412: 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 (%d)\n",(int)moisdc[i],(int)andc[i],num[i],i, *nberr);
5413: s[m][i]=-1;
5414: }
5415: if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
5416: (*nberr)++;
5417: 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]);
5418: 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]);
5419: s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
5420: }
5421: }
5422: }
5423:
5424: for (i=1; i<=imx; i++) {
5425: agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
5426: for(m=firstpass; (m<= lastpass); m++){
5427: if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
5428: if (s[m][i] >= nlstate+1) {
5429: if(agedc[i]>0){
5430: if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
5431: agev[m][i]=agedc[i];
5432: /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
5433: }else {
5434: if ((int)andc[i]!=9999){
5435: nbwarn++;
5436: printf("Warning negative age at death: %ld line:%d\n",num[i],i);
5437: fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
5438: agev[m][i]=-1;
5439: }
5440: }
5441: } /* agedc > 0 */
5442: }
5443: else if(s[m][i] !=9){ /* Standard case, age in fractional
5444: years but with the precision of a month */
5445: agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
5446: if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
5447: agev[m][i]=1;
5448: else if(agev[m][i] < *agemin){
5449: *agemin=agev[m][i];
5450: printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
5451: }
5452: else if(agev[m][i] >*agemax){
5453: *agemax=agev[m][i];
5454: /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
5455: }
5456: /*agev[m][i]=anint[m][i]-annais[i];*/
5457: /* agev[m][i] = age[i]+2*m;*/
5458: }
5459: else { /* =9 */
5460: agev[m][i]=1;
5461: s[m][i]=-1;
5462: }
5463: }
5464: else /*= 0 Unknown */
5465: agev[m][i]=1;
5466: }
5467:
5468: }
5469: for (i=1; i<=imx; i++) {
5470: for(m=firstpass; (m<=lastpass); m++){
5471: if (s[m][i] > (nlstate+ndeath)) {
5472: (*nberr)++;
5473: 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);
5474: 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);
5475: return 1;
5476: }
5477: }
5478: }
5479:
5480: /*for (i=1; i<=imx; i++){
5481: for (m=firstpass; (m<lastpass); m++){
5482: printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
5483: }
5484:
5485: }*/
5486:
5487:
5488: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
5489: fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
5490:
5491: return (0);
5492: /* endread:*/
5493: printf("Exiting calandcheckages: ");
5494: return (1);
5495: }
5496:
5497: #if defined(_MSC_VER)
5498: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
5499: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
5500: //#include "stdafx.h"
5501: //#include <stdio.h>
5502: //#include <tchar.h>
5503: //#include <windows.h>
5504: //#include <iostream>
5505: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
5506:
5507: LPFN_ISWOW64PROCESS fnIsWow64Process;
5508:
5509: BOOL IsWow64()
5510: {
5511: BOOL bIsWow64 = FALSE;
5512:
5513: //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
5514: // (HANDLE, PBOOL);
5515:
5516: //LPFN_ISWOW64PROCESS fnIsWow64Process;
5517:
5518: HMODULE module = GetModuleHandle(_T("kernel32"));
5519: const char funcName[] = "IsWow64Process";
5520: fnIsWow64Process = (LPFN_ISWOW64PROCESS)
5521: GetProcAddress(module, funcName);
5522:
5523: if (NULL != fnIsWow64Process)
5524: {
5525: if (!fnIsWow64Process(GetCurrentProcess(),
5526: &bIsWow64))
5527: //throw std::exception("Unknown error");
5528: printf("Unknown error\n");
5529: }
5530: return bIsWow64 != FALSE;
5531: }
5532: #endif
5533:
5534: void syscompilerinfo()
5535: {
5536: /* #include "syscompilerinfo.h"*/
5537:
5538: #if defined __INTEL_COMPILER
5539: #if defined(__GNUC__)
5540: struct utsname sysInfo; /* For Intel on Linux and OS/X */
5541: #endif
5542: #elif defined(__GNUC__)
5543: #ifndef __APPLE__
5544: #include <gnu/libc-version.h> /* Only on gnu */
5545: #endif
5546: struct utsname sysInfo;
5547: int cross = CROSS;
5548: if (cross){
5549: printf("Cross-");
5550: fprintf(ficlog, "Cross-");
5551: }
5552: #endif
5553:
5554: #include <stdint.h>
5555:
5556: printf("Compiled with:");fprintf(ficlog,"Compiled with:");
5557: #if defined(__clang__)
5558: printf(" Clang/LLVM");fprintf(ficlog," Clang/LLVM"); /* Clang/LLVM. ---------------------------------------------- */
5559: #endif
5560: #if defined(__ICC) || defined(__INTEL_COMPILER)
5561: printf(" Intel ICC/ICPC");fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
5562: #endif
5563: #if defined(__GNUC__) || defined(__GNUG__)
5564: printf(" GNU GCC/G++");fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
5565: #endif
5566: #if defined(__HP_cc) || defined(__HP_aCC)
5567: printf(" Hewlett-Packard C/aC++");fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
5568: #endif
5569: #if defined(__IBMC__) || defined(__IBMCPP__)
5570: printf(" IBM XL C/C++"); fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
5571: #endif
5572: #if defined(_MSC_VER)
5573: printf(" Microsoft Visual Studio");fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
5574: #endif
5575: #if defined(__PGI)
5576: printf(" Portland Group PGCC/PGCPP");fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
5577: #endif
5578: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
5579: printf(" Oracle Solaris Studio");fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
5580: #endif
5581: printf(" for ");fprintf(ficlog," for ");
5582:
5583: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
5584: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
5585: // Windows (x64 and x86)
5586: printf("Windows (x64 and x86) ");fprintf(ficlog,"Windows (x64 and x86) ");
5587: #elif __unix__ // all unices, not all compilers
5588: // Unix
5589: printf("Unix ");fprintf(ficlog,"Unix ");
5590: #elif __linux__
5591: // linux
5592: printf("linux ");fprintf(ficlog,"linux ");
5593: #elif __APPLE__
5594: // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
5595: printf("Mac OS ");fprintf(ficlog,"Mac OS ");
5596: #endif
5597:
5598: /* __MINGW32__ */
5599: /* __CYGWIN__ */
5600: /* __MINGW64__ */
5601: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
5602: /* _MSC_VER //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /? */
5603: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
5604: /* _WIN64 // Defined for applications for Win64. */
5605: /* _M_X64 // Defined for compilations that target x64 processors. */
5606: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
5607:
5608: #if UINTPTR_MAX == 0xffffffff
5609: printf(" 32-bit"); fprintf(ficlog," 32-bit");/* 32-bit */
5610: #elif UINTPTR_MAX == 0xffffffffffffffff
5611: printf(" 64-bit"); fprintf(ficlog," 64-bit");/* 64-bit */
5612: #else
5613: printf(" wtf-bit"); fprintf(ficlog," wtf-bit");/* wtf */
5614: #endif
5615:
5616: #if defined(__GNUC__)
5617: # if defined(__GNUC_PATCHLEVEL__)
5618: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
5619: + __GNUC_MINOR__ * 100 \
5620: + __GNUC_PATCHLEVEL__)
5621: # else
5622: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
5623: + __GNUC_MINOR__ * 100)
5624: # endif
5625: printf(" using GNU C version %d.\n", __GNUC_VERSION__);
5626: fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
5627:
5628: if (uname(&sysInfo) != -1) {
5629: printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
5630: fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
5631: }
5632: else
5633: perror("uname() error");
5634: //#ifndef __INTEL_COMPILER
5635: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
5636: printf("GNU libc version: %s\n", gnu_get_libc_version());
5637: fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
5638: #endif
5639: #endif
5640:
5641: // void main()
5642: // {
5643: #if defined(_MSC_VER)
5644: if (IsWow64()){
5645: printf("The program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
5646: fprintf(ficlog, "The program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
5647: }
5648: else{
5649: printf("The process is not running under WOW64 (i.e probably on a 64bit Windows).\n");
5650: fprintf(ficlog,"The programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
5651: }
5652: // printf("\nPress Enter to continue...");
5653: // getchar();
5654: // }
5655:
5656: #endif
5657:
5658:
5659: }
5660:
5661: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar){
5662: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
5663: int i, j, k, i1 ;
5664: double ftolpl = 1.e-10;
5665: double age, agebase, agelim;
5666:
5667: strcpy(filerespl,"pl");
5668: strcat(filerespl,fileres);
5669: if((ficrespl=fopen(filerespl,"w"))==NULL) {
5670: printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
5671: fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
5672: }
5673: printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
5674: fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
5675: pstamp(ficrespl);
5676: fprintf(ficrespl,"# Period (stable) prevalence \n");
5677: fprintf(ficrespl,"#Age ");
5678: for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
5679: fprintf(ficrespl,"\n");
5680:
5681: /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
5682:
5683: agebase=ageminpar;
5684: agelim=agemaxpar;
5685:
5686: i1=pow(2,cptcoveff);
5687: if (cptcovn < 1){i1=1;}
5688:
5689: for(cptcov=1,k=0;cptcov<=i1;cptcov++){
5690: /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
5691: //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
5692: k=k+1;
5693: /* to clean */
5694: //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtab[cptcod][cptcov]);
5695: fprintf(ficrespl,"\n#******");
5696: printf("\n#******");
5697: fprintf(ficlog,"\n#******");
5698: for(j=1;j<=cptcoveff;j++) {
5699: fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5700: printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5701: fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5702: }
5703: fprintf(ficrespl,"******\n");
5704: printf("******\n");
5705: fprintf(ficlog,"******\n");
5706:
5707: fprintf(ficrespl,"#Age ");
5708: for(j=1;j<=cptcoveff;j++) {
5709: fprintf(ficrespl,"V%d %d",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5710: }
5711: for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
5712: fprintf(ficrespl,"\n");
5713:
5714: for (age=agebase; age<=agelim; age++){
5715: /* for (age=agebase; age<=agebase; age++){ */
5716: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
5717: fprintf(ficrespl,"%.0f ",age );
5718: for(j=1;j<=cptcoveff;j++)
5719: fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5720: for(i=1; i<=nlstate;i++)
5721: fprintf(ficrespl," %.5f", prlim[i][i]);
5722: fprintf(ficrespl,"\n");
5723: } /* Age */
5724: /* was end of cptcod */
5725: } /* cptcov */
5726: }
5727:
5728: int hPijx(double *p, int bage, int fage){
5729: /*------------- h Pij x at various ages ------------*/
5730:
5731: int stepsize;
5732: int agelim;
5733: int hstepm;
5734: int nhstepm;
5735: int h, i, i1, j, k;
5736:
5737: double agedeb;
5738: double ***p3mat;
5739:
5740: strcpy(filerespij,"pij"); strcat(filerespij,fileres);
5741: if((ficrespij=fopen(filerespij,"w"))==NULL) {
5742: printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
5743: fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
5744: }
5745: printf("Computing pij: result on file '%s' \n", filerespij);
5746: fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
5747:
5748: stepsize=(int) (stepm+YEARM-1)/YEARM;
5749: /*if (stepm<=24) stepsize=2;*/
5750:
5751: agelim=AGESUP;
5752: hstepm=stepsize*YEARM; /* Every year of age */
5753: hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
5754:
5755: /* hstepm=1; aff par mois*/
5756: pstamp(ficrespij);
5757: fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
5758: i1= pow(2,cptcoveff);
5759: for(cptcov=1,k=0;cptcov<=i1;cptcov++){
5760: /*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
5761: k=k+1;
5762: /* for (k=1; k <= (int) pow(2,cptcoveff); k++){*/
5763: fprintf(ficrespij,"\n#****** ");
5764: for(j=1;j<=cptcoveff;j++)
5765: fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5766: fprintf(ficrespij,"******\n");
5767:
5768: for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
5769: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
5770: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
5771:
5772: /* nhstepm=nhstepm*YEARM; aff par mois*/
5773:
5774: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5775: oldm=oldms;savm=savms;
5776: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
5777: fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
5778: for(i=1; i<=nlstate;i++)
5779: for(j=1; j<=nlstate+ndeath;j++)
5780: fprintf(ficrespij," %1d-%1d",i,j);
5781: fprintf(ficrespij,"\n");
5782: for (h=0; h<=nhstepm; h++){
5783: /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
5784: fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
5785: for(i=1; i<=nlstate;i++)
5786: for(j=1; j<=nlstate+ndeath;j++)
5787: fprintf(ficrespij," %.5f", p3mat[i][j][h]);
5788: fprintf(ficrespij,"\n");
5789: }
5790: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5791: fprintf(ficrespij,"\n");
5792: }
5793: /*}*/
5794: }
5795: }
5796:
5797:
5798: /***********************************************/
5799: /**************** Main Program *****************/
5800: /***********************************************/
5801:
5802: int main(int argc, char *argv[])
5803: {
5804: #ifdef GSL
5805: const gsl_multimin_fminimizer_type *T;
5806: size_t iteri = 0, it;
5807: int rval = GSL_CONTINUE;
5808: int status = GSL_SUCCESS;
5809: double ssval;
5810: #endif
5811: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
5812: int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
5813:
5814: int jj, ll, li, lj, lk;
5815: int numlinepar=0; /* Current linenumber of parameter file */
5816: int itimes;
5817: int NDIM=2;
5818: int vpopbased=0;
5819:
5820: char ca[32], cb[32];
5821: /* FILE *fichtm; *//* Html File */
5822: /* FILE *ficgp;*/ /*Gnuplot File */
5823: struct stat info;
5824: double agedeb;
5825: double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
5826:
5827: double fret;
5828: double dum; /* Dummy variable */
5829: double ***p3mat;
5830: double ***mobaverage;
5831:
5832: char line[MAXLINE];
5833: char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
5834: char pathr[MAXLINE], pathimach[MAXLINE];
5835: char *tok, *val; /* pathtot */
5836: int firstobs=1, lastobs=10;
5837: int c, h , cpt;
5838: int jl;
5839: int i1, j1, jk, stepsize;
5840: int *tab;
5841: int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
5842: int mobilav=0,popforecast=0;
5843: int hstepm, nhstepm;
5844: int agemortsup;
5845: float sumlpop=0.;
5846: double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
5847: double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
5848:
5849: double bage=0, fage=110, age, agelim, agebase;
5850: double ftolpl=FTOL;
5851: double **prlim;
5852: double ***param; /* Matrix of parameters */
5853: double *p;
5854: double **matcov; /* Matrix of covariance */
5855: double ***delti3; /* Scale */
5856: double *delti; /* Scale */
5857: double ***eij, ***vareij;
5858: double **varpl; /* Variances of prevalence limits by age */
5859: double *epj, vepp;
5860:
5861: double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
5862: double **ximort;
5863: char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
5864: int *dcwave;
5865:
5866: char z[1]="c";
5867:
5868: /*char *strt;*/
5869: char strtend[80];
5870:
5871:
5872: /* setlocale (LC_ALL, ""); */
5873: /* bindtextdomain (PACKAGE, LOCALEDIR); */
5874: /* textdomain (PACKAGE); */
5875: /* setlocale (LC_CTYPE, ""); */
5876: /* setlocale (LC_MESSAGES, ""); */
5877:
5878: /* gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
5879: rstart_time = time(NULL);
5880: /* (void) gettimeofday(&start_time,&tzp);*/
5881: start_time = *localtime(&rstart_time);
5882: curr_time=start_time;
5883: /*tml = *localtime(&start_time.tm_sec);*/
5884: /* strcpy(strstart,asctime(&tml)); */
5885: strcpy(strstart,asctime(&start_time));
5886:
5887: /* printf("Localtime (at start)=%s",strstart); */
5888: /* tp.tm_sec = tp.tm_sec +86400; */
5889: /* tm = *localtime(&start_time.tm_sec); */
5890: /* tmg.tm_year=tmg.tm_year +dsign*dyear; */
5891: /* tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
5892: /* tmg.tm_hour=tmg.tm_hour + 1; */
5893: /* tp.tm_sec = mktime(&tmg); */
5894: /* strt=asctime(&tmg); */
5895: /* printf("Time(after) =%s",strstart); */
5896: /* (void) time (&time_value);
5897: * printf("time=%d,t-=%d\n",time_value,time_value-86400);
5898: * tm = *localtime(&time_value);
5899: * strstart=asctime(&tm);
5900: * printf("tim_value=%d,asctime=%s\n",time_value,strstart);
5901: */
5902:
5903: nberr=0; /* Number of errors and warnings */
5904: nbwarn=0;
5905: getcwd(pathcd, size);
5906:
5907: printf("\n%s\n%s",version,fullversion);
5908: if(argc <=1){
5909: printf("\nEnter the parameter file name: ");
5910: fgets(pathr,FILENAMELENGTH,stdin);
5911: i=strlen(pathr);
5912: if(pathr[i-1]=='\n')
5913: pathr[i-1]='\0';
5914: i=strlen(pathr);
5915: if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
5916: pathr[i-1]='\0';
5917: for (tok = pathr; tok != NULL; ){
5918: printf("Pathr |%s|\n",pathr);
5919: while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
5920: printf("val= |%s| pathr=%s\n",val,pathr);
5921: strcpy (pathtot, val);
5922: if(pathr[0] == '\0') break; /* Dirty */
5923: }
5924: }
5925: else{
5926: strcpy(pathtot,argv[1]);
5927: }
5928: /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
5929: /*cygwin_split_path(pathtot,path,optionfile);
5930: printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
5931: /* cutv(path,optionfile,pathtot,'\\');*/
5932:
5933: /* Split argv[0], imach program to get pathimach */
5934: printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
5935: split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
5936: printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
5937: /* strcpy(pathimach,argv[0]); */
5938: /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
5939: split(pathtot,path,optionfile,optionfilext,optionfilefiname);
5940: printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
5941: chdir(path); /* Can be a relative path */
5942: if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
5943: printf("Current directory %s!\n",pathcd);
5944: strcpy(command,"mkdir ");
5945: strcat(command,optionfilefiname);
5946: if((outcmd=system(command)) != 0){
5947: printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
5948: /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
5949: /* fclose(ficlog); */
5950: /* exit(1); */
5951: }
5952: /* if((imk=mkdir(optionfilefiname))<0){ */
5953: /* perror("mkdir"); */
5954: /* } */
5955:
5956: /*-------- arguments in the command line --------*/
5957:
5958: /* Log file */
5959: strcat(filelog, optionfilefiname);
5960: strcat(filelog,".log"); /* */
5961: if((ficlog=fopen(filelog,"w"))==NULL) {
5962: printf("Problem with logfile %s\n",filelog);
5963: goto end;
5964: }
5965: fprintf(ficlog,"Log filename:%s\n",filelog);
5966: fprintf(ficlog,"\n%s\n%s",version,fullversion);
5967: fprintf(ficlog,"\nEnter the parameter file name: \n");
5968: fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
5969: path=%s \n\
5970: optionfile=%s\n\
5971: optionfilext=%s\n\
5972: optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
5973:
5974: syscompilerinfo();
5975:
5976: printf("Local time (at start):%s",strstart);
5977: fprintf(ficlog,"Local time (at start): %s",strstart);
5978: fflush(ficlog);
5979: /* (void) gettimeofday(&curr_time,&tzp); */
5980: /* printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
5981:
5982: /* */
5983: strcpy(fileres,"r");
5984: strcat(fileres, optionfilefiname);
5985: strcat(fileres,".txt"); /* Other files have txt extension */
5986:
5987: /*---------arguments file --------*/
5988:
5989: if((ficpar=fopen(optionfile,"r"))==NULL) {
5990: printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
5991: fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
5992: fflush(ficlog);
5993: /* goto end; */
5994: exit(70);
5995: }
5996:
5997:
5998:
5999: strcpy(filereso,"o");
6000: strcat(filereso,fileres);
6001: if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
6002: printf("Problem with Output resultfile: %s\n", filereso);
6003: fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
6004: fflush(ficlog);
6005: goto end;
6006: }
6007:
6008: /* Reads comments: lines beginning with '#' */
6009: numlinepar=0;
6010: while((c=getc(ficpar))=='#' && c!= EOF){
6011: ungetc(c,ficpar);
6012: fgets(line, MAXLINE, ficpar);
6013: numlinepar++;
6014: fputs(line,stdout);
6015: fputs(line,ficparo);
6016: fputs(line,ficlog);
6017: }
6018: ungetc(c,ficpar);
6019:
6020: 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);
6021: numlinepar++;
6022: 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);
6023: 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);
6024: 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);
6025: fflush(ficlog);
6026: while((c=getc(ficpar))=='#' && c!= EOF){
6027: ungetc(c,ficpar);
6028: fgets(line, MAXLINE, ficpar);
6029: numlinepar++;
6030: fputs(line, stdout);
6031: //puts(line);
6032: fputs(line,ficparo);
6033: fputs(line,ficlog);
6034: }
6035: ungetc(c,ficpar);
6036:
6037:
6038: covar=matrix(0,NCOVMAX,1,n); /**< used in readdata */
6039: cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
6040: /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
6041: v1+v2*age+v2*v3 makes cptcovn = 3
6042: */
6043: if (strlen(model)>1)
6044: 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*/
6045: else
6046: ncovmodel=2;
6047: nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
6048: nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
6049: npar= nforce*ncovmodel; /* Number of parameters like aij*/
6050: if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
6051: 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);
6052: 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);
6053: fflush(stdout);
6054: fclose (ficlog);
6055: goto end;
6056: }
6057: delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6058: delti=delti3[1][1];
6059: /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
6060: if(mle==-1){ /* Print a wizard for help writing covariance matrix */
6061: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
6062: printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
6063: fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
6064: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
6065: fclose (ficparo);
6066: fclose (ficlog);
6067: goto end;
6068: exit(0);
6069: }
6070: else if(mle==-3) {
6071: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
6072: printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
6073: fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
6074: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6075: matcov=matrix(1,npar,1,npar);
6076: }
6077: else{
6078: /* Read guessed parameters */
6079: /* Reads comments: lines beginning with '#' */
6080: while((c=getc(ficpar))=='#' && c!= EOF){
6081: ungetc(c,ficpar);
6082: fgets(line, MAXLINE, ficpar);
6083: numlinepar++;
6084: fputs(line,stdout);
6085: fputs(line,ficparo);
6086: fputs(line,ficlog);
6087: }
6088: ungetc(c,ficpar);
6089:
6090: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6091: for(i=1; i <=nlstate; i++){
6092: j=0;
6093: for(jj=1; jj <=nlstate+ndeath; jj++){
6094: if(jj==i) continue;
6095: j++;
6096: fscanf(ficpar,"%1d%1d",&i1,&j1);
6097: if ((i1 != i) && (j1 != j)){
6098: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
6099: It might be a problem of design; if ncovcol and the model are correct\n \
6100: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
6101: exit(1);
6102: }
6103: fprintf(ficparo,"%1d%1d",i1,j1);
6104: if(mle==1)
6105: printf("%1d%1d",i,j);
6106: fprintf(ficlog,"%1d%1d",i,j);
6107: for(k=1; k<=ncovmodel;k++){
6108: fscanf(ficpar," %lf",¶m[i][j][k]);
6109: if(mle==1){
6110: printf(" %lf",param[i][j][k]);
6111: fprintf(ficlog," %lf",param[i][j][k]);
6112: }
6113: else
6114: fprintf(ficlog," %lf",param[i][j][k]);
6115: fprintf(ficparo," %lf",param[i][j][k]);
6116: }
6117: fscanf(ficpar,"\n");
6118: numlinepar++;
6119: if(mle==1)
6120: printf("\n");
6121: fprintf(ficlog,"\n");
6122: fprintf(ficparo,"\n");
6123: }
6124: }
6125: fflush(ficlog);
6126:
6127: /* Reads scales values */
6128: p=param[1][1];
6129:
6130: /* Reads comments: lines beginning with '#' */
6131: while((c=getc(ficpar))=='#' && c!= EOF){
6132: ungetc(c,ficpar);
6133: fgets(line, MAXLINE, ficpar);
6134: numlinepar++;
6135: fputs(line,stdout);
6136: fputs(line,ficparo);
6137: fputs(line,ficlog);
6138: }
6139: ungetc(c,ficpar);
6140:
6141: for(i=1; i <=nlstate; i++){
6142: for(j=1; j <=nlstate+ndeath-1; j++){
6143: fscanf(ficpar,"%1d%1d",&i1,&j1);
6144: if ( (i1-i) * (j1-j) != 0){
6145: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
6146: exit(1);
6147: }
6148: printf("%1d%1d",i,j);
6149: fprintf(ficparo,"%1d%1d",i1,j1);
6150: fprintf(ficlog,"%1d%1d",i1,j1);
6151: for(k=1; k<=ncovmodel;k++){
6152: fscanf(ficpar,"%le",&delti3[i][j][k]);
6153: printf(" %le",delti3[i][j][k]);
6154: fprintf(ficparo," %le",delti3[i][j][k]);
6155: fprintf(ficlog," %le",delti3[i][j][k]);
6156: }
6157: fscanf(ficpar,"\n");
6158: numlinepar++;
6159: printf("\n");
6160: fprintf(ficparo,"\n");
6161: fprintf(ficlog,"\n");
6162: }
6163: }
6164: fflush(ficlog);
6165:
6166: /* Reads covariance matrix */
6167: delti=delti3[1][1];
6168:
6169:
6170: /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
6171:
6172: /* Reads comments: lines beginning with '#' */
6173: while((c=getc(ficpar))=='#' && c!= EOF){
6174: ungetc(c,ficpar);
6175: fgets(line, MAXLINE, ficpar);
6176: numlinepar++;
6177: fputs(line,stdout);
6178: fputs(line,ficparo);
6179: fputs(line,ficlog);
6180: }
6181: ungetc(c,ficpar);
6182:
6183: matcov=matrix(1,npar,1,npar);
6184: for(i=1; i <=npar; i++)
6185: for(j=1; j <=npar; j++) matcov[i][j]=0.;
6186:
6187: for(i=1; i <=npar; i++){
6188: fscanf(ficpar,"%s",str);
6189: if(mle==1)
6190: printf("%s",str);
6191: fprintf(ficlog,"%s",str);
6192: fprintf(ficparo,"%s",str);
6193: for(j=1; j <=i; j++){
6194: fscanf(ficpar," %le",&matcov[i][j]);
6195: if(mle==1){
6196: printf(" %.5le",matcov[i][j]);
6197: }
6198: fprintf(ficlog," %.5le",matcov[i][j]);
6199: fprintf(ficparo," %.5le",matcov[i][j]);
6200: }
6201: fscanf(ficpar,"\n");
6202: numlinepar++;
6203: if(mle==1)
6204: printf("\n");
6205: fprintf(ficlog,"\n");
6206: fprintf(ficparo,"\n");
6207: }
6208: for(i=1; i <=npar; i++)
6209: for(j=i+1;j<=npar;j++)
6210: matcov[i][j]=matcov[j][i];
6211:
6212: if(mle==1)
6213: printf("\n");
6214: fprintf(ficlog,"\n");
6215:
6216: fflush(ficlog);
6217:
6218: /*-------- Rewriting parameter file ----------*/
6219: strcpy(rfileres,"r"); /* "Rparameterfile */
6220: strcat(rfileres,optionfilefiname); /* Parameter file first name*/
6221: strcat(rfileres,"."); /* */
6222: strcat(rfileres,optionfilext); /* Other files have txt extension */
6223: if((ficres =fopen(rfileres,"w"))==NULL) {
6224: printf("Problem writing new parameter file: %s\n", fileres);goto end;
6225: fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
6226: }
6227: fprintf(ficres,"#%s\n",version);
6228: } /* End of mle != -3 */
6229:
6230:
6231: n= lastobs;
6232: num=lvector(1,n);
6233: moisnais=vector(1,n);
6234: annais=vector(1,n);
6235: moisdc=vector(1,n);
6236: andc=vector(1,n);
6237: agedc=vector(1,n);
6238: cod=ivector(1,n);
6239: weight=vector(1,n);
6240: for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
6241: mint=matrix(1,maxwav,1,n);
6242: anint=matrix(1,maxwav,1,n);
6243: s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */
6244: tab=ivector(1,NCOVMAX);
6245: ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
6246:
6247: /* Reads data from file datafile */
6248: if (readdata(datafile, firstobs, lastobs, &imx)==1)
6249: goto end;
6250:
6251: /* Calculation of the number of parameters from char model */
6252: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4
6253: k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
6254: k=3 V4 Tvar[k=3]= 4 (from V4)
6255: k=2 V1 Tvar[k=2]= 1 (from V1)
6256: k=1 Tvar[1]=2 (from V2)
6257: */
6258: Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
6259: /* V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs).
6260: For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4,
6261: Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
6262: */
6263: /* For model-covariate k tells which data-covariate to use but
6264: because this model-covariate is a construction we invent a new column
6265: ncovcol + k1
6266: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
6267: Tvar[3=V1*V4]=4+1 etc */
6268: Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
6269: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
6270: if V2+V1+V1*V4+age*V3+V3*V2 TProd[k1=2]=5 (V3*V2)
6271: */
6272: Tvaraff=ivector(1,NCOVMAX); /* Unclear */
6273: 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
6274: * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd.
6275: * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
6276: Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
6277: 4 covariates (3 plus signs)
6278: Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
6279: */
6280:
6281: if(decodemodel(model, lastobs) == 1)
6282: goto end;
6283:
6284: if((double)(lastobs-imx)/(double)imx > 1.10){
6285: nbwarn++;
6286: 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);
6287: 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);
6288: }
6289: /* if(mle==1){*/
6290: if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
6291: for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
6292: }
6293:
6294: /*-calculation of age at interview from date of interview and age at death -*/
6295: agev=matrix(1,maxwav,1,imx);
6296:
6297: if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
6298: goto end;
6299:
6300:
6301: agegomp=(int)agemin;
6302: free_vector(moisnais,1,n);
6303: free_vector(annais,1,n);
6304: /* free_matrix(mint,1,maxwav,1,n);
6305: free_matrix(anint,1,maxwav,1,n);*/
6306: free_vector(moisdc,1,n);
6307: free_vector(andc,1,n);
6308: /* */
6309:
6310: wav=ivector(1,imx);
6311: dh=imatrix(1,lastpass-firstpass+1,1,imx);
6312: bh=imatrix(1,lastpass-firstpass+1,1,imx);
6313: mw=imatrix(1,lastpass-firstpass+1,1,imx);
6314:
6315: /* Concatenates waves */
6316: concatwav(wav, dh, bh, mw, s, agedc, agev, firstpass, lastpass, imx, nlstate, stepm);
6317: /* */
6318:
6319: /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
6320:
6321: nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
6322: ncodemax[1]=1;
6323: Ndum =ivector(-1,NCOVMAX);
6324: if (ncovmodel > 2)
6325: tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
6326:
6327: codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
6328: /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
6329: h=0;
6330:
6331:
6332: /*if (cptcovn > 0) */
6333:
6334:
6335: m=pow(2,cptcoveff);
6336:
6337: for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
6338: 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 */
6339: for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
6340: for(cpt=1; cpt <=pow(2,k-1); cpt++){ /* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 */
6341: h++;
6342: if (h>m)
6343: h=1;
6344: /**< codtab(h,k) k = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
6345: * h 1 2 3 4
6346: *______________________________
6347: * 1 i=1 1 i=1 1 i=1 1 i=1 1
6348: * 2 2 1 1 1
6349: * 3 i=2 1 2 1 1
6350: * 4 2 2 1 1
6351: * 5 i=3 1 i=2 1 2 1
6352: * 6 2 1 2 1
6353: * 7 i=4 1 2 2 1
6354: * 8 2 2 2 1
6355: * 9 i=5 1 i=3 1 i=2 1 1
6356: * 10 2 1 1 1
6357: * 11 i=6 1 2 1 1
6358: * 12 2 2 1 1
6359: * 13 i=7 1 i=4 1 2 1
6360: * 14 2 1 2 1
6361: * 15 i=8 1 2 2 1
6362: * 16 2 2 2 1
6363: */
6364: codtab[h][k]=j;
6365: /*codtab[h][Tvar[k]]=j;*/
6366: 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]]);
6367: }
6368: }
6369: }
6370: }
6371: /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
6372: codtab[1][2]=1;codtab[2][2]=2; */
6373: /* for(i=1; i <=m ;i++){
6374: for(k=1; k <=cptcovn; k++){
6375: printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
6376: }
6377: printf("\n");
6378: }
6379: scanf("%d",i);*/
6380:
6381: free_ivector(Ndum,-1,NCOVMAX);
6382:
6383:
6384:
6385: /*------------ gnuplot -------------*/
6386: strcpy(optionfilegnuplot,optionfilefiname);
6387: if(mle==-3)
6388: strcat(optionfilegnuplot,"-mort");
6389: strcat(optionfilegnuplot,".gp");
6390:
6391: if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
6392: printf("Problem with file %s",optionfilegnuplot);
6393: }
6394: else{
6395: fprintf(ficgp,"\n# %s\n", version);
6396: fprintf(ficgp,"# %s\n", optionfilegnuplot);
6397: //fprintf(ficgp,"set missing 'NaNq'\n");
6398: fprintf(ficgp,"set datafile missing 'NaNq'\n");
6399: }
6400: /* fclose(ficgp);*/
6401: /*--------- index.htm --------*/
6402:
6403: strcpy(optionfilehtm,optionfilefiname); /* Main html file */
6404: if(mle==-3)
6405: strcat(optionfilehtm,"-mort");
6406: strcat(optionfilehtm,".htm");
6407: if((fichtm=fopen(optionfilehtm,"w"))==NULL) {
6408: printf("Problem with %s \n",optionfilehtm);
6409: exit(0);
6410: }
6411:
6412: strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
6413: strcat(optionfilehtmcov,"-cov.htm");
6414: if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL) {
6415: printf("Problem with %s \n",optionfilehtmcov), exit(0);
6416: }
6417: else{
6418: fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6419: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6420: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
6421: optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
6422: }
6423:
6424: fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6425: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6426: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
6427: \n\
6428: <hr size=\"2\" color=\"#EC5E5E\">\
6429: <ul><li><h4>Parameter files</h4>\n\
6430: - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
6431: - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
6432: - Log file of the run: <a href=\"%s\">%s</a><br>\n\
6433: - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
6434: - Date and time at start: %s</ul>\n",\
6435: optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
6436: optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
6437: fileres,fileres,\
6438: filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
6439: fflush(fichtm);
6440:
6441: strcpy(pathr,path);
6442: strcat(pathr,optionfilefiname);
6443: chdir(optionfilefiname); /* Move to directory named optionfile */
6444:
6445: /* Calculates basic frequencies. Computes observed prevalence at single age
6446: and prints on file fileres'p'. */
6447: freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
6448:
6449: fprintf(fichtm,"\n");
6450: fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
6451: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
6452: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
6453: imx,agemin,agemax,jmin,jmax,jmean);
6454: pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6455: oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6456: newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6457: savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6458: oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
6459:
6460:
6461: /* For Powell, parameters are in a vector p[] starting at p[1]
6462: so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
6463: p=param[1][1]; /* *(*(*(param +1)+1)+0) */
6464:
6465: globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
6466:
6467: if (mle==-3){
6468: ximort=matrix(1,NDIM,1,NDIM);
6469: /* ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
6470: cens=ivector(1,n);
6471: ageexmed=vector(1,n);
6472: agecens=vector(1,n);
6473: dcwave=ivector(1,n);
6474:
6475: for (i=1; i<=imx; i++){
6476: dcwave[i]=-1;
6477: for (m=firstpass; m<=lastpass; m++)
6478: if (s[m][i]>nlstate) {
6479: dcwave[i]=m;
6480: /* printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
6481: break;
6482: }
6483: }
6484:
6485: for (i=1; i<=imx; i++) {
6486: if (wav[i]>0){
6487: ageexmed[i]=agev[mw[1][i]][i];
6488: j=wav[i];
6489: agecens[i]=1.;
6490:
6491: if (ageexmed[i]> 1 && wav[i] > 0){
6492: agecens[i]=agev[mw[j][i]][i];
6493: cens[i]= 1;
6494: }else if (ageexmed[i]< 1)
6495: cens[i]= -1;
6496: if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
6497: cens[i]=0 ;
6498: }
6499: else cens[i]=-1;
6500: }
6501:
6502: for (i=1;i<=NDIM;i++) {
6503: for (j=1;j<=NDIM;j++)
6504: ximort[i][j]=(i == j ? 1.0 : 0.0);
6505: }
6506:
6507: /*p[1]=0.0268; p[NDIM]=0.083;*/
6508: /*printf("%lf %lf", p[1], p[2]);*/
6509:
6510:
6511: #ifdef GSL
6512: printf("GSL optimization\n"); fprintf(ficlog,"Powell\n");
6513: #else
6514: printf("Powell\n"); fprintf(ficlog,"Powell\n");
6515: #endif
6516: strcpy(filerespow,"pow-mort");
6517: strcat(filerespow,fileres);
6518: if((ficrespow=fopen(filerespow,"w"))==NULL) {
6519: printf("Problem with resultfile: %s\n", filerespow);
6520: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
6521: }
6522: #ifdef GSL
6523: fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
6524: #else
6525: fprintf(ficrespow,"# Powell\n# iter -2*LL");
6526: #endif
6527: /* for (i=1;i<=nlstate;i++)
6528: for(j=1;j<=nlstate+ndeath;j++)
6529: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
6530: */
6531: fprintf(ficrespow,"\n");
6532: #ifdef GSL
6533: /* gsl starts here */
6534: T = gsl_multimin_fminimizer_nmsimplex;
6535: gsl_multimin_fminimizer *sfm = NULL;
6536: gsl_vector *ss, *x;
6537: gsl_multimin_function minex_func;
6538:
6539: /* Initial vertex size vector */
6540: ss = gsl_vector_alloc (NDIM);
6541:
6542: if (ss == NULL){
6543: GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
6544: }
6545: /* Set all step sizes to 1 */
6546: gsl_vector_set_all (ss, 0.001);
6547:
6548: /* Starting point */
6549:
6550: x = gsl_vector_alloc (NDIM);
6551:
6552: if (x == NULL){
6553: gsl_vector_free(ss);
6554: GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
6555: }
6556:
6557: /* Initialize method and iterate */
6558: /* p[1]=0.0268; p[NDIM]=0.083; */
6559: /* gsl_vector_set(x, 0, 0.0268); */
6560: /* gsl_vector_set(x, 1, 0.083); */
6561: gsl_vector_set(x, 0, p[1]);
6562: gsl_vector_set(x, 1, p[2]);
6563:
6564: minex_func.f = &gompertz_f;
6565: minex_func.n = NDIM;
6566: minex_func.params = (void *)&p; /* ??? */
6567:
6568: sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
6569: gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
6570:
6571: printf("Iterations beginning .....\n\n");
6572: printf("Iter. # Intercept Slope -Log Likelihood Simplex size\n");
6573:
6574: iteri=0;
6575: while (rval == GSL_CONTINUE){
6576: iteri++;
6577: status = gsl_multimin_fminimizer_iterate(sfm);
6578:
6579: if (status) printf("error: %s\n", gsl_strerror (status));
6580: fflush(0);
6581:
6582: if (status)
6583: break;
6584:
6585: rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
6586: ssval = gsl_multimin_fminimizer_size (sfm);
6587:
6588: if (rval == GSL_SUCCESS)
6589: printf ("converged to a local maximum at\n");
6590:
6591: printf("%5d ", iteri);
6592: for (it = 0; it < NDIM; it++){
6593: printf ("%10.5f ", gsl_vector_get (sfm->x, it));
6594: }
6595: printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
6596: }
6597:
6598: printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
6599:
6600: gsl_vector_free(x); /* initial values */
6601: gsl_vector_free(ss); /* inital step size */
6602: for (it=0; it<NDIM; it++){
6603: p[it+1]=gsl_vector_get(sfm->x,it);
6604: fprintf(ficrespow," %.12lf", p[it]);
6605: }
6606: gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1) */
6607: #endif
6608: #ifdef POWELL
6609: powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
6610: #endif
6611: fclose(ficrespow);
6612:
6613: hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);
6614:
6615: for(i=1; i <=NDIM; i++)
6616: for(j=i+1;j<=NDIM;j++)
6617: matcov[i][j]=matcov[j][i];
6618:
6619: printf("\nCovariance matrix\n ");
6620: for(i=1; i <=NDIM; i++) {
6621: for(j=1;j<=NDIM;j++){
6622: printf("%f ",matcov[i][j]);
6623: }
6624: printf("\n ");
6625: }
6626:
6627: printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
6628: for (i=1;i<=NDIM;i++)
6629: printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
6630:
6631: lsurv=vector(1,AGESUP);
6632: lpop=vector(1,AGESUP);
6633: tpop=vector(1,AGESUP);
6634: lsurv[agegomp]=100000;
6635:
6636: for (k=agegomp;k<=AGESUP;k++) {
6637: agemortsup=k;
6638: if (p[1]*exp(p[2]*(k-agegomp))>1) break;
6639: }
6640:
6641: for (k=agegomp;k<agemortsup;k++)
6642: lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
6643:
6644: for (k=agegomp;k<agemortsup;k++){
6645: lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
6646: sumlpop=sumlpop+lpop[k];
6647: }
6648:
6649: tpop[agegomp]=sumlpop;
6650: for (k=agegomp;k<(agemortsup-3);k++){
6651: /* tpop[k+1]=2;*/
6652: tpop[k+1]=tpop[k]-lpop[k];
6653: }
6654:
6655:
6656: printf("\nAge lx qx dx Lx Tx e(x)\n");
6657: for (k=agegomp;k<(agemortsup-2);k++)
6658: 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]);
6659:
6660:
6661: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6662: printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6663:
6664: printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
6665: stepm, weightopt,\
6666: model,imx,p,matcov,agemortsup);
6667:
6668: free_vector(lsurv,1,AGESUP);
6669: free_vector(lpop,1,AGESUP);
6670: free_vector(tpop,1,AGESUP);
6671: #ifdef GSL
6672: free_ivector(cens,1,n);
6673: free_vector(agecens,1,n);
6674: free_ivector(dcwave,1,n);
6675: free_matrix(ximort,1,NDIM,1,NDIM);
6676: #endif
6677: } /* Endof if mle==-3 */
6678:
6679: else{ /* For mle >=1 */
6680: globpr=0;/* debug */
6681: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
6682: printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6683: for (k=1; k<=npar;k++)
6684: printf(" %d %8.5f",k,p[k]);
6685: printf("\n");
6686: globpr=1; /* to print the contributions */
6687: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
6688: printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6689: for (k=1; k<=npar;k++)
6690: printf(" %d %8.5f",k,p[k]);
6691: printf("\n");
6692: if(mle>=1){ /* Could be 1 or 2 */
6693: mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
6694: }
6695:
6696: /*--------- results files --------------*/
6697: 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);
6698:
6699:
6700: fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6701: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6702: fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6703: for(i=1,jk=1; i <=nlstate; i++){
6704: for(k=1; k <=(nlstate+ndeath); k++){
6705: if (k != i) {
6706: printf("%d%d ",i,k);
6707: fprintf(ficlog,"%d%d ",i,k);
6708: fprintf(ficres,"%1d%1d ",i,k);
6709: for(j=1; j <=ncovmodel; j++){
6710: printf("%lf ",p[jk]);
6711: fprintf(ficlog,"%lf ",p[jk]);
6712: fprintf(ficres,"%lf ",p[jk]);
6713: jk++;
6714: }
6715: printf("\n");
6716: fprintf(ficlog,"\n");
6717: fprintf(ficres,"\n");
6718: }
6719: }
6720: }
6721: if(mle!=0){
6722: /* Computing hessian and covariance matrix */
6723: ftolhess=ftol; /* Usually correct */
6724: hesscov(matcov, p, npar, delti, ftolhess, func);
6725: }
6726: fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
6727: printf("# Scales (for hessian or gradient estimation)\n");
6728: fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
6729: for(i=1,jk=1; i <=nlstate; i++){
6730: for(j=1; j <=nlstate+ndeath; j++){
6731: if (j!=i) {
6732: fprintf(ficres,"%1d%1d",i,j);
6733: printf("%1d%1d",i,j);
6734: fprintf(ficlog,"%1d%1d",i,j);
6735: for(k=1; k<=ncovmodel;k++){
6736: printf(" %.5e",delti[jk]);
6737: fprintf(ficlog," %.5e",delti[jk]);
6738: fprintf(ficres," %.5e",delti[jk]);
6739: jk++;
6740: }
6741: printf("\n");
6742: fprintf(ficlog,"\n");
6743: fprintf(ficres,"\n");
6744: }
6745: }
6746: }
6747:
6748: 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");
6749: if(mle>=1)
6750: 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");
6751: 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");
6752: /* # 121 Var(a12)\n\ */
6753: /* # 122 Cov(b12,a12) Var(b12)\n\ */
6754: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
6755: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
6756: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
6757: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
6758: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
6759: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
6760:
6761:
6762: /* Just to have a covariance matrix which will be more understandable
6763: even is we still don't want to manage dictionary of variables
6764: */
6765: for(itimes=1;itimes<=2;itimes++){
6766: jj=0;
6767: for(i=1; i <=nlstate; i++){
6768: for(j=1; j <=nlstate+ndeath; j++){
6769: if(j==i) continue;
6770: for(k=1; k<=ncovmodel;k++){
6771: jj++;
6772: ca[0]= k+'a'-1;ca[1]='\0';
6773: if(itimes==1){
6774: if(mle>=1)
6775: printf("#%1d%1d%d",i,j,k);
6776: fprintf(ficlog,"#%1d%1d%d",i,j,k);
6777: fprintf(ficres,"#%1d%1d%d",i,j,k);
6778: }else{
6779: if(mle>=1)
6780: printf("%1d%1d%d",i,j,k);
6781: fprintf(ficlog,"%1d%1d%d",i,j,k);
6782: fprintf(ficres,"%1d%1d%d",i,j,k);
6783: }
6784: ll=0;
6785: for(li=1;li <=nlstate; li++){
6786: for(lj=1;lj <=nlstate+ndeath; lj++){
6787: if(lj==li) continue;
6788: for(lk=1;lk<=ncovmodel;lk++){
6789: ll++;
6790: if(ll<=jj){
6791: cb[0]= lk +'a'-1;cb[1]='\0';
6792: if(ll<jj){
6793: if(itimes==1){
6794: if(mle>=1)
6795: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6796: fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6797: fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6798: }else{
6799: if(mle>=1)
6800: printf(" %.5e",matcov[jj][ll]);
6801: fprintf(ficlog," %.5e",matcov[jj][ll]);
6802: fprintf(ficres," %.5e",matcov[jj][ll]);
6803: }
6804: }else{
6805: if(itimes==1){
6806: if(mle>=1)
6807: printf(" Var(%s%1d%1d)",ca,i,j);
6808: fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
6809: fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
6810: }else{
6811: if(mle>=1)
6812: printf(" %.5e",matcov[jj][ll]);
6813: fprintf(ficlog," %.5e",matcov[jj][ll]);
6814: fprintf(ficres," %.5e",matcov[jj][ll]);
6815: }
6816: }
6817: }
6818: } /* end lk */
6819: } /* end lj */
6820: } /* end li */
6821: if(mle>=1)
6822: printf("\n");
6823: fprintf(ficlog,"\n");
6824: fprintf(ficres,"\n");
6825: numlinepar++;
6826: } /* end k*/
6827: } /*end j */
6828: } /* end i */
6829: } /* end itimes */
6830:
6831: fflush(ficlog);
6832: fflush(ficres);
6833:
6834: while((c=getc(ficpar))=='#' && c!= EOF){
6835: ungetc(c,ficpar);
6836: fgets(line, MAXLINE, ficpar);
6837: fputs(line,stdout);
6838: fputs(line,ficparo);
6839: }
6840: ungetc(c,ficpar);
6841:
6842: estepm=0;
6843: fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
6844: if (estepm==0 || estepm < stepm) estepm=stepm;
6845: if (fage <= 2) {
6846: bage = ageminpar;
6847: fage = agemaxpar;
6848: }
6849:
6850: fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
6851: fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6852: fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6853:
6854: while((c=getc(ficpar))=='#' && c!= EOF){
6855: ungetc(c,ficpar);
6856: fgets(line, MAXLINE, ficpar);
6857: fputs(line,stdout);
6858: fputs(line,ficparo);
6859: }
6860: ungetc(c,ficpar);
6861:
6862: 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);
6863: 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);
6864: 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);
6865: printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
6866: 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);
6867:
6868: while((c=getc(ficpar))=='#' && c!= EOF){
6869: ungetc(c,ficpar);
6870: fgets(line, MAXLINE, ficpar);
6871: fputs(line,stdout);
6872: fputs(line,ficparo);
6873: }
6874: ungetc(c,ficpar);
6875:
6876:
6877: dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
6878: dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
6879:
6880: fscanf(ficpar,"pop_based=%d\n",&popbased);
6881: fprintf(ficparo,"pop_based=%d\n",popbased);
6882: fprintf(ficres,"pop_based=%d\n",popbased);
6883:
6884: while((c=getc(ficpar))=='#' && c!= EOF){
6885: ungetc(c,ficpar);
6886: fgets(line, MAXLINE, ficpar);
6887: fputs(line,stdout);
6888: fputs(line,ficparo);
6889: }
6890: ungetc(c,ficpar);
6891:
6892: 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);
6893: 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);
6894: 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);
6895: 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);
6896: 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);
6897: /* day and month of proj2 are not used but only year anproj2.*/
6898:
6899:
6900:
6901: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
6902: /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
6903:
6904: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6905: printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6906:
6907: printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
6908: model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
6909: jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
6910:
6911: /*------------ free_vector -------------*/
6912: /* chdir(path); */
6913:
6914: free_ivector(wav,1,imx);
6915: free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
6916: free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
6917: free_imatrix(mw,1,lastpass-firstpass+1,1,imx);
6918: free_lvector(num,1,n);
6919: free_vector(agedc,1,n);
6920: /*free_matrix(covar,0,NCOVMAX,1,n);*/
6921: /*free_matrix(covar,1,NCOVMAX,1,n);*/
6922: fclose(ficparo);
6923: fclose(ficres);
6924:
6925:
6926: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
6927: /*#include "prevlim.h"*/ /* Use ficrespl, ficlog */
6928: prlim=matrix(1,nlstate,1,nlstate);
6929: prevalence_limit(p, prlim, ageminpar, agemaxpar);
6930: fclose(ficrespl);
6931:
6932: #ifdef FREEEXIT2
6933: #include "freeexit2.h"
6934: #endif
6935:
6936: /*------------- h Pij x at various ages ------------*/
6937: /*#include "hpijx.h"*/
6938: hPijx(p, bage, fage);
6939: fclose(ficrespij);
6940:
6941: /*-------------- Variance of one-step probabilities---*/
6942: k=1;
6943: varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
6944:
6945:
6946: probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
6947: for(i=1;i<=AGESUP;i++)
6948: for(j=1;j<=NCOVMAX;j++)
6949: for(k=1;k<=NCOVMAX;k++)
6950: probs[i][j][k]=0.;
6951:
6952: /*---------- Forecasting ------------------*/
6953: /*if((stepm == 1) && (strcmp(model,".")==0)){*/
6954: if(prevfcast==1){
6955: /* if(stepm ==1){*/
6956: prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
6957: /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
6958: /* } */
6959: /* else{ */
6960: /* erreur=108; */
6961: /* 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); */
6962: /* 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); */
6963: /* } */
6964: }
6965:
6966:
6967: /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
6968:
6969: prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
6970: /* 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",\
6971: ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
6972: */
6973:
6974: if (mobilav!=0) {
6975: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
6976: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
6977: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
6978: printf(" Error in movingaverage mobilav=%d\n",mobilav);
6979: }
6980: }
6981:
6982:
6983: /*---------- Health expectancies, no variances ------------*/
6984:
6985: strcpy(filerese,"e");
6986: strcat(filerese,fileres);
6987: if((ficreseij=fopen(filerese,"w"))==NULL) {
6988: printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
6989: fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
6990: }
6991: printf("Computing Health Expectancies: result on file '%s' \n", filerese);
6992: fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
6993: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6994: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6995:
6996: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6997: fprintf(ficreseij,"\n#****** ");
6998: for(j=1;j<=cptcoveff;j++) {
6999: fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7000: }
7001: fprintf(ficreseij,"******\n");
7002:
7003: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
7004: oldm=oldms;savm=savms;
7005: evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);
7006:
7007: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
7008: /*}*/
7009: }
7010: fclose(ficreseij);
7011:
7012:
7013: /*---------- Health expectancies and variances ------------*/
7014:
7015:
7016: strcpy(filerest,"t");
7017: strcat(filerest,fileres);
7018: if((ficrest=fopen(filerest,"w"))==NULL) {
7019: printf("Problem with total LE resultfile: %s\n", filerest);goto end;
7020: fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
7021: }
7022: printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
7023: fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
7024:
7025:
7026: strcpy(fileresstde,"stde");
7027: strcat(fileresstde,fileres);
7028: if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
7029: printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
7030: fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
7031: }
7032: printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
7033: fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
7034:
7035: strcpy(filerescve,"cve");
7036: strcat(filerescve,fileres);
7037: if((ficrescveij=fopen(filerescve,"w"))==NULL) {
7038: printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
7039: fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
7040: }
7041: printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
7042: fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
7043:
7044: strcpy(fileresv,"v");
7045: strcat(fileresv,fileres);
7046: if((ficresvij=fopen(fileresv,"w"))==NULL) {
7047: printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
7048: fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
7049: }
7050: printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
7051: fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
7052:
7053: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
7054: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
7055:
7056: for (k=1; k <= (int) pow(2,cptcoveff); k++){
7057: fprintf(ficrest,"\n#****** ");
7058: for(j=1;j<=cptcoveff;j++)
7059: fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7060: fprintf(ficrest,"******\n");
7061:
7062: fprintf(ficresstdeij,"\n#****** ");
7063: fprintf(ficrescveij,"\n#****** ");
7064: for(j=1;j<=cptcoveff;j++) {
7065: fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7066: fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7067: }
7068: fprintf(ficresstdeij,"******\n");
7069: fprintf(ficrescveij,"******\n");
7070:
7071: fprintf(ficresvij,"\n#****** ");
7072: for(j=1;j<=cptcoveff;j++)
7073: fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7074: fprintf(ficresvij,"******\n");
7075:
7076: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
7077: oldm=oldms;savm=savms;
7078: cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
7079: /*
7080: */
7081: /* goto endfree; */
7082:
7083: vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
7084: pstamp(ficrest);
7085:
7086:
7087: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
7088: oldm=oldms;savm=savms; /* Segmentation fault */
7089: cptcod= 0; /* To be deleted */
7090: 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 */
7091: 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 ");
7092: if(vpopbased==1)
7093: 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);
7094: else
7095: fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
7096: fprintf(ficrest,"# Age e.. (std) ");
7097: for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
7098: fprintf(ficrest,"\n");
7099:
7100: epj=vector(1,nlstate+1);
7101: for(age=bage; age <=fage ;age++){
7102: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
7103: if (vpopbased==1) {
7104: if(mobilav ==0){
7105: for(i=1; i<=nlstate;i++)
7106: prlim[i][i]=probs[(int)age][i][k];
7107: }else{ /* mobilav */
7108: for(i=1; i<=nlstate;i++)
7109: prlim[i][i]=mobaverage[(int)age][i][k];
7110: }
7111: }
7112:
7113: fprintf(ficrest," %4.0f",age);
7114: for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
7115: for(i=1, epj[j]=0.;i <=nlstate;i++) {
7116: epj[j] += prlim[i][i]*eij[i][j][(int)age];
7117: /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
7118: }
7119: epj[nlstate+1] +=epj[j];
7120: }
7121:
7122: for(i=1, vepp=0.;i <=nlstate;i++)
7123: for(j=1;j <=nlstate;j++)
7124: vepp += vareij[i][j][(int)age];
7125: fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
7126: for(j=1;j <=nlstate;j++){
7127: fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
7128: }
7129: fprintf(ficrest,"\n");
7130: }
7131: }
7132: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
7133: free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
7134: free_vector(epj,1,nlstate+1);
7135: /*}*/
7136: }
7137: free_vector(weight,1,n);
7138: free_imatrix(Tvard,1,NCOVMAX,1,2);
7139: free_imatrix(s,1,maxwav+1,1,n);
7140: free_matrix(anint,1,maxwav,1,n);
7141: free_matrix(mint,1,maxwav,1,n);
7142: free_ivector(cod,1,n);
7143: free_ivector(tab,1,NCOVMAX);
7144: fclose(ficresstdeij);
7145: fclose(ficrescveij);
7146: fclose(ficresvij);
7147: fclose(ficrest);
7148: fclose(ficpar);
7149:
7150: /*------- Variance of period (stable) prevalence------*/
7151:
7152: strcpy(fileresvpl,"vpl");
7153: strcat(fileresvpl,fileres);
7154: if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
7155: printf("Problem with variance of period (stable) prevalence resultfile: %s\n", fileresvpl);
7156: exit(0);
7157: }
7158: printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
7159:
7160: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
7161: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
7162:
7163: for (k=1; k <= (int) pow(2,cptcoveff); k++){
7164: fprintf(ficresvpl,"\n#****** ");
7165: for(j=1;j<=cptcoveff;j++)
7166: fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7167: fprintf(ficresvpl,"******\n");
7168:
7169: varpl=matrix(1,nlstate,(int) bage, (int) fage);
7170: oldm=oldms;savm=savms;
7171: varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
7172: free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
7173: /*}*/
7174: }
7175:
7176: fclose(ficresvpl);
7177:
7178: /*---------- End : free ----------------*/
7179: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
7180: free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
7181: } /* mle==-3 arrives here for freeing */
7182: /* endfree:*/
7183: free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
7184: free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
7185: free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
7186: free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
7187: free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
7188: free_matrix(covar,0,NCOVMAX,1,n);
7189: free_matrix(matcov,1,npar,1,npar);
7190: /*free_vector(delti,1,npar);*/
7191: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
7192: free_matrix(agev,1,maxwav,1,imx);
7193: free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
7194:
7195: free_ivector(ncodemax,1,NCOVMAX);
7196: free_ivector(Tvar,1,NCOVMAX);
7197: free_ivector(Tprod,1,NCOVMAX);
7198: free_ivector(Tvaraff,1,NCOVMAX);
7199: free_ivector(Tage,1,NCOVMAX);
7200:
7201: free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
7202: free_imatrix(codtab,1,100,1,10);
7203: fflush(fichtm);
7204: fflush(ficgp);
7205:
7206:
7207: if((nberr >0) || (nbwarn>0)){
7208: printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
7209: fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
7210: }else{
7211: printf("End of Imach\n");
7212: fprintf(ficlog,"End of Imach\n");
7213: }
7214: printf("See log file on %s\n",filelog);
7215: /* gettimeofday(&end_time, (struct timezone*)0);*/ /* after time */
7216: /*(void) gettimeofday(&end_time,&tzp);*/
7217: rend_time = time(NULL);
7218: end_time = *localtime(&rend_time);
7219: /* tml = *localtime(&end_time.tm_sec); */
7220: strcpy(strtend,asctime(&end_time));
7221: printf("Local time at start %s\nLocal time at end %s",strstart, strtend);
7222: fprintf(ficlog,"Local time at start %s\nLocal time at end %s\n",strstart, strtend);
7223: printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
7224:
7225: printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
7226: fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
7227: fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
7228: /* printf("Total time was %d uSec.\n", total_usecs);*/
7229: /* if(fileappend(fichtm,optionfilehtm)){ */
7230: fprintf(fichtm,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
7231: fclose(fichtm);
7232: fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
7233: fclose(fichtmcov);
7234: fclose(ficgp);
7235: fclose(ficlog);
7236: /*------ End -----------*/
7237:
7238:
7239: printf("Before Current directory %s!\n",pathcd);
7240: if(chdir(pathcd) != 0)
7241: printf("Can't move to directory %s!\n",path);
7242: if(getcwd(pathcd,MAXLINE) > 0)
7243: printf("Current directory %s!\n",pathcd);
7244: /*strcat(plotcmd,CHARSEPARATOR);*/
7245: sprintf(plotcmd,"gnuplot");
7246: #ifdef _WIN32
7247: sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
7248: #endif
7249: if(!stat(plotcmd,&info)){
7250: printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
7251: if(!stat(getenv("GNUPLOTBIN"),&info)){
7252: printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
7253: }else
7254: strcpy(pplotcmd,plotcmd);
7255: #ifdef __unix
7256: strcpy(plotcmd,GNUPLOTPROGRAM);
7257: if(!stat(plotcmd,&info)){
7258: printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
7259: }else
7260: strcpy(pplotcmd,plotcmd);
7261: #endif
7262: }else
7263: strcpy(pplotcmd,plotcmd);
7264:
7265: sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
7266: printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
7267:
7268: if((outcmd=system(plotcmd)) != 0){
7269: printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
7270: printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
7271: sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
7272: if((outcmd=system(plotcmd)) != 0)
7273: printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
7274: }
7275: printf(" Successful, please wait...");
7276: while (z[0] != 'q') {
7277: /* chdir(path); */
7278: printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
7279: scanf("%s",z);
7280: /* if (z[0] == 'c') system("./imach"); */
7281: if (z[0] == 'e') {
7282: #ifdef __APPLE__
7283: sprintf(pplotcmd, "open %s", optionfilehtm);
7284: #elif __linux
7285: sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
7286: #else
7287: sprintf(pplotcmd, "%s", optionfilehtm);
7288: #endif
7289: printf("Starting browser with: %s",pplotcmd);fflush(stdout);
7290: system(pplotcmd);
7291: }
7292: else if (z[0] == 'g') system(plotcmd);
7293: else if (z[0] == 'q') exit(0);
7294: }
7295: end:
7296: while (z[0] != 'q') {
7297: printf("\nType q for exiting: ");
7298: scanf("%s",z);
7299: }
7300: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>