1: /* $Id: imach.c,v 1.180 2015/02/11 17:33:45 brouard Exp $
2: $State: Exp $
3: $Log: imach.c,v $
4: Revision 1.180 2015/02/11 17:33:45 brouard
5: Summary: Finishing move from main to function (hpijx and prevalence_limit)
6:
7: Revision 1.179 2015/01/04 09:57:06 brouard
8: Summary: back to OS/X
9:
10: Revision 1.178 2015/01/04 09:35:48 brouard
11: *** empty log message ***
12:
13: Revision 1.177 2015/01/03 18:40:56 brouard
14: Summary: Still testing ilc32 on OSX
15:
16: Revision 1.176 2015/01/03 16:45:04 brouard
17: *** empty log message ***
18:
19: Revision 1.175 2015/01/03 16:33:42 brouard
20: *** empty log message ***
21:
22: Revision 1.174 2015/01/03 16:15:49 brouard
23: Summary: Still in cross-compilation
24:
25: Revision 1.173 2015/01/03 12:06:26 brouard
26: Summary: trying to detect cross-compilation
27:
28: Revision 1.172 2014/12/27 12:07:47 brouard
29: Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
30:
31: Revision 1.171 2014/12/23 13:26:59 brouard
32: Summary: Back from Visual C
33:
34: Still problem with utsname.h on Windows
35:
36: Revision 1.170 2014/12/23 11:17:12 brouard
37: Summary: Cleaning some \%% back to %%
38:
39: The escape was mandatory for a specific compiler (which one?), but too many warnings.
40:
41: Revision 1.169 2014/12/22 23:08:31 brouard
42: Summary: 0.98p
43:
44: Outputs some informations on compiler used, OS etc. Testing on different platforms.
45:
46: Revision 1.168 2014/12/22 15:17:42 brouard
47: Summary: update
48:
49: Revision 1.167 2014/12/22 13:50:56 brouard
50: Summary: Testing uname and compiler version and if compiled 32 or 64
51:
52: Testing on Linux 64
53:
54: Revision 1.166 2014/12/22 11:40:47 brouard
55: *** empty log message ***
56:
57: Revision 1.165 2014/12/16 11:20:36 brouard
58: Summary: After compiling on Visual C
59:
60: * imach.c (Module): Merging 1.61 to 1.162
61:
62: Revision 1.164 2014/12/16 10:52:11 brouard
63: Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
64:
65: * imach.c (Module): Merging 1.61 to 1.162
66:
67: Revision 1.163 2014/12/16 10:30:11 brouard
68: * imach.c (Module): Merging 1.61 to 1.162
69:
70: Revision 1.162 2014/09/25 11:43:39 brouard
71: Summary: temporary backup 0.99!
72:
73: Revision 1.1 2014/09/16 11:06:58 brouard
74: Summary: With some code (wrong) for nlopt
75:
76: Author:
77:
78: Revision 1.161 2014/09/15 20:41:41 brouard
79: Summary: Problem with macro SQR on Intel compiler
80:
81: Revision 1.160 2014/09/02 09:24:05 brouard
82: *** empty log message ***
83:
84: Revision 1.159 2014/09/01 10:34:10 brouard
85: Summary: WIN32
86: Author: Brouard
87:
88: Revision 1.158 2014/08/27 17:11:51 brouard
89: *** empty log message ***
90:
91: Revision 1.157 2014/08/27 16:26:55 brouard
92: Summary: Preparing windows Visual studio version
93: Author: Brouard
94:
95: In order to compile on Visual studio, time.h is now correct and time_t
96: and tm struct should be used. difftime should be used but sometimes I
97: just make the differences in raw time format (time(&now).
98: Trying to suppress #ifdef LINUX
99: Add xdg-open for __linux in order to open default browser.
100:
101: Revision 1.156 2014/08/25 20:10:10 brouard
102: *** empty log message ***
103:
104: Revision 1.155 2014/08/25 18:32:34 brouard
105: Summary: New compile, minor changes
106: Author: Brouard
107:
108: Revision 1.154 2014/06/20 17:32:08 brouard
109: Summary: Outputs now all graphs of convergence to period prevalence
110:
111: Revision 1.153 2014/06/20 16:45:46 brouard
112: Summary: If 3 live state, convergence to period prevalence on same graph
113: Author: Brouard
114:
115: Revision 1.152 2014/06/18 17:54:09 brouard
116: Summary: open browser, use gnuplot on same dir than imach if not found in the path
117:
118: Revision 1.151 2014/06/18 16:43:30 brouard
119: *** empty log message ***
120:
121: Revision 1.150 2014/06/18 16:42:35 brouard
122: Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
123: Author: brouard
124:
125: Revision 1.149 2014/06/18 15:51:14 brouard
126: Summary: Some fixes in parameter files errors
127: Author: Nicolas Brouard
128:
129: Revision 1.148 2014/06/17 17:38:48 brouard
130: Summary: Nothing new
131: Author: Brouard
132:
133: Just a new packaging for OS/X version 0.98nS
134:
135: Revision 1.147 2014/06/16 10:33:11 brouard
136: *** empty log message ***
137:
138: Revision 1.146 2014/06/16 10:20:28 brouard
139: Summary: Merge
140: Author: Brouard
141:
142: Merge, before building revised version.
143:
144: Revision 1.145 2014/06/10 21:23:15 brouard
145: Summary: Debugging with valgrind
146: Author: Nicolas Brouard
147:
148: Lot of changes in order to output the results with some covariates
149: After the Edimburgh REVES conference 2014, it seems mandatory to
150: improve the code.
151: No more memory valgrind error but a lot has to be done in order to
152: continue the work of splitting the code into subroutines.
153: Also, decodemodel has been improved. Tricode is still not
154: optimal. nbcode should be improved. Documentation has been added in
155: the source code.
156:
157: Revision 1.143 2014/01/26 09:45:38 brouard
158: Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
159:
160: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
161: (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
162:
163: Revision 1.142 2014/01/26 03:57:36 brouard
164: Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
165:
166: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
167:
168: Revision 1.141 2014/01/26 02:42:01 brouard
169: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
170:
171: Revision 1.140 2011/09/02 10:37:54 brouard
172: Summary: times.h is ok with mingw32 now.
173:
174: Revision 1.139 2010/06/14 07:50:17 brouard
175: After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
176: I remember having already fixed agemin agemax which are pointers now but not cvs saved.
177:
178: Revision 1.138 2010/04/30 18:19:40 brouard
179: *** empty log message ***
180:
181: Revision 1.137 2010/04/29 18:11:38 brouard
182: (Module): Checking covariates for more complex models
183: than V1+V2. A lot of change to be done. Unstable.
184:
185: Revision 1.136 2010/04/26 20:30:53 brouard
186: (Module): merging some libgsl code. Fixing computation
187: of likelione (using inter/intrapolation if mle = 0) in order to
188: get same likelihood as if mle=1.
189: Some cleaning of code and comments added.
190:
191: Revision 1.135 2009/10/29 15:33:14 brouard
192: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
193:
194: Revision 1.134 2009/10/29 13:18:53 brouard
195: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
196:
197: Revision 1.133 2009/07/06 10:21:25 brouard
198: just nforces
199:
200: Revision 1.132 2009/07/06 08:22:05 brouard
201: Many tings
202:
203: Revision 1.131 2009/06/20 16:22:47 brouard
204: Some dimensions resccaled
205:
206: Revision 1.130 2009/05/26 06:44:34 brouard
207: (Module): Max Covariate is now set to 20 instead of 8. A
208: lot of cleaning with variables initialized to 0. Trying to make
209: V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
210:
211: Revision 1.129 2007/08/31 13:49:27 lievre
212: Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
213:
214: Revision 1.128 2006/06/30 13:02:05 brouard
215: (Module): Clarifications on computing e.j
216:
217: Revision 1.127 2006/04/28 18:11:50 brouard
218: (Module): Yes the sum of survivors was wrong since
219: imach-114 because nhstepm was no more computed in the age
220: loop. Now we define nhstepma in the age loop.
221: (Module): In order to speed up (in case of numerous covariates) we
222: compute health expectancies (without variances) in a first step
223: and then all the health expectancies with variances or standard
224: deviation (needs data from the Hessian matrices) which slows the
225: computation.
226: In the future we should be able to stop the program is only health
227: expectancies and graph are needed without standard deviations.
228:
229: Revision 1.126 2006/04/28 17:23:28 brouard
230: (Module): Yes the sum of survivors was wrong since
231: imach-114 because nhstepm was no more computed in the age
232: loop. Now we define nhstepma in the age loop.
233: Version 0.98h
234:
235: Revision 1.125 2006/04/04 15:20:31 lievre
236: Errors in calculation of health expectancies. Age was not initialized.
237: Forecasting file added.
238:
239: Revision 1.124 2006/03/22 17:13:53 lievre
240: Parameters are printed with %lf instead of %f (more numbers after the comma).
241: The log-likelihood is printed in the log file
242:
243: Revision 1.123 2006/03/20 10:52:43 brouard
244: * imach.c (Module): <title> changed, corresponds to .htm file
245: name. <head> headers where missing.
246:
247: * imach.c (Module): Weights can have a decimal point as for
248: English (a comma might work with a correct LC_NUMERIC environment,
249: otherwise the weight is truncated).
250: Modification of warning when the covariates values are not 0 or
251: 1.
252: Version 0.98g
253:
254: Revision 1.122 2006/03/20 09:45:41 brouard
255: (Module): Weights can have a decimal point as for
256: English (a comma might work with a correct LC_NUMERIC environment,
257: otherwise the weight is truncated).
258: Modification of warning when the covariates values are not 0 or
259: 1.
260: Version 0.98g
261:
262: Revision 1.121 2006/03/16 17:45:01 lievre
263: * imach.c (Module): Comments concerning covariates added
264:
265: * imach.c (Module): refinements in the computation of lli if
266: status=-2 in order to have more reliable computation if stepm is
267: not 1 month. Version 0.98f
268:
269: Revision 1.120 2006/03/16 15:10:38 lievre
270: (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.119 2006/03/15 17:42:26 brouard
275: (Module): Bug if status = -2, the loglikelihood was
276: computed as likelihood omitting the logarithm. Version O.98e
277:
278: Revision 1.118 2006/03/14 18:20:07 brouard
279: (Module): varevsij Comments added explaining the second
280: table of variances if popbased=1 .
281: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
282: (Module): Function pstamp added
283: (Module): Version 0.98d
284:
285: Revision 1.117 2006/03/14 17:16:22 brouard
286: (Module): varevsij Comments added explaining the second
287: table of variances if popbased=1 .
288: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
289: (Module): Function pstamp added
290: (Module): Version 0.98d
291:
292: Revision 1.116 2006/03/06 10:29:27 brouard
293: (Module): Variance-covariance wrong links and
294: varian-covariance of ej. is needed (Saito).
295:
296: Revision 1.115 2006/02/27 12:17:45 brouard
297: (Module): One freematrix added in mlikeli! 0.98c
298:
299: Revision 1.114 2006/02/26 12:57:58 brouard
300: (Module): Some improvements in processing parameter
301: filename with strsep.
302:
303: Revision 1.113 2006/02/24 14:20:24 brouard
304: (Module): Memory leaks checks with valgrind and:
305: datafile was not closed, some imatrix were not freed and on matrix
306: allocation too.
307:
308: Revision 1.112 2006/01/30 09:55:26 brouard
309: (Module): Back to gnuplot.exe instead of wgnuplot.exe
310:
311: Revision 1.111 2006/01/25 20:38:18 brouard
312: (Module): Lots of cleaning and bugs added (Gompertz)
313: (Module): Comments can be added in data file. Missing date values
314: can be a simple dot '.'.
315:
316: Revision 1.110 2006/01/25 00:51:50 brouard
317: (Module): Lots of cleaning and bugs added (Gompertz)
318:
319: Revision 1.109 2006/01/24 19:37:15 brouard
320: (Module): Comments (lines starting with a #) are allowed in data.
321:
322: Revision 1.108 2006/01/19 18:05:42 lievre
323: Gnuplot problem appeared...
324: To be fixed
325:
326: Revision 1.107 2006/01/19 16:20:37 brouard
327: Test existence of gnuplot in imach path
328:
329: Revision 1.106 2006/01/19 13:24:36 brouard
330: Some cleaning and links added in html output
331:
332: Revision 1.105 2006/01/05 20:23:19 lievre
333: *** empty log message ***
334:
335: Revision 1.104 2005/09/30 16:11:43 lievre
336: (Module): sump fixed, loop imx fixed, and simplifications.
337: (Module): If the status is missing at the last wave but we know
338: that the person is alive, then we can code his/her status as -2
339: (instead of missing=-1 in earlier versions) and his/her
340: contributions to the likelihood is 1 - Prob of dying from last
341: health status (= 1-p13= p11+p12 in the easiest case of somebody in
342: the healthy state at last known wave). Version is 0.98
343:
344: Revision 1.103 2005/09/30 15:54:49 lievre
345: (Module): sump fixed, loop imx fixed, and simplifications.
346:
347: Revision 1.102 2004/09/15 17:31:30 brouard
348: Add the possibility to read data file including tab characters.
349:
350: Revision 1.101 2004/09/15 10:38:38 brouard
351: Fix on curr_time
352:
353: Revision 1.100 2004/07/12 18:29:06 brouard
354: Add version for Mac OS X. Just define UNIX in Makefile
355:
356: Revision 1.99 2004/06/05 08:57:40 brouard
357: *** empty log message ***
358:
359: Revision 1.98 2004/05/16 15:05:56 brouard
360: New version 0.97 . First attempt to estimate force of mortality
361: directly from the data i.e. without the need of knowing the health
362: state at each age, but using a Gompertz model: log u =a + b*age .
363: This is the basic analysis of mortality and should be done before any
364: other analysis, in order to test if the mortality estimated from the
365: cross-longitudinal survey is different from the mortality estimated
366: from other sources like vital statistic data.
367:
368: The same imach parameter file can be used but the option for mle should be -3.
369:
370: Agnès, who wrote this part of the code, tried to keep most of the
371: former routines in order to include the new code within the former code.
372:
373: The output is very simple: only an estimate of the intercept and of
374: the slope with 95% confident intervals.
375:
376: Current limitations:
377: A) Even if you enter covariates, i.e. with the
378: model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
379: B) There is no computation of Life Expectancy nor Life Table.
380:
381: Revision 1.97 2004/02/20 13:25:42 lievre
382: Version 0.96d. Population forecasting command line is (temporarily)
383: suppressed.
384:
385: Revision 1.96 2003/07/15 15:38:55 brouard
386: * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
387: rewritten within the same printf. Workaround: many printfs.
388:
389: Revision 1.95 2003/07/08 07:54:34 brouard
390: * imach.c (Repository):
391: (Repository): Using imachwizard code to output a more meaningful covariance
392: matrix (cov(a12,c31) instead of numbers.
393:
394: Revision 1.94 2003/06/27 13:00:02 brouard
395: Just cleaning
396:
397: Revision 1.93 2003/06/25 16:33:55 brouard
398: (Module): On windows (cygwin) function asctime_r doesn't
399: exist so I changed back to asctime which exists.
400: (Module): Version 0.96b
401:
402: Revision 1.92 2003/06/25 16:30:45 brouard
403: (Module): On windows (cygwin) function asctime_r doesn't
404: exist so I changed back to asctime which exists.
405:
406: Revision 1.91 2003/06/25 15:30:29 brouard
407: * imach.c (Repository): Duplicated warning errors corrected.
408: (Repository): Elapsed time after each iteration is now output. It
409: helps to forecast when convergence will be reached. Elapsed time
410: is stamped in powell. We created a new html file for the graphs
411: concerning matrix of covariance. It has extension -cov.htm.
412:
413: Revision 1.90 2003/06/24 12:34:15 brouard
414: (Module): Some bugs corrected for windows. Also, when
415: mle=-1 a template is output in file "or"mypar.txt with the design
416: of the covariance matrix to be input.
417:
418: Revision 1.89 2003/06/24 12:30:52 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.88 2003/06/23 17:54:56 brouard
424: * 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.
425:
426: Revision 1.87 2003/06/18 12:26:01 brouard
427: Version 0.96
428:
429: Revision 1.86 2003/06/17 20:04:08 brouard
430: (Module): Change position of html and gnuplot routines and added
431: routine fileappend.
432:
433: Revision 1.85 2003/06/17 13:12:43 brouard
434: * imach.c (Repository): Check when date of death was earlier that
435: current date of interview. It may happen when the death was just
436: prior to the death. In this case, dh was negative and likelihood
437: was wrong (infinity). We still send an "Error" but patch by
438: assuming that the date of death was just one stepm after the
439: interview.
440: (Repository): Because some people have very long ID (first column)
441: we changed int to long in num[] and we added a new lvector for
442: memory allocation. But we also truncated to 8 characters (left
443: truncation)
444: (Repository): No more line truncation errors.
445:
446: Revision 1.84 2003/06/13 21:44:43 brouard
447: * imach.c (Repository): Replace "freqsummary" at a correct
448: place. It differs from routine "prevalence" which may be called
449: many times. Probs is memory consuming and must be used with
450: parcimony.
451: Version 0.95a3 (should output exactly the same maximization than 0.8a2)
452:
453: Revision 1.83 2003/06/10 13:39:11 lievre
454: *** empty log message ***
455:
456: Revision 1.82 2003/06/05 15:57:20 brouard
457: Add log in imach.c and fullversion number is now printed.
458:
459: */
460: /*
461: Interpolated Markov Chain
462:
463: Short summary of the programme:
464:
465: This program computes Healthy Life Expectancies from
466: cross-longitudinal data. Cross-longitudinal data consist in: -1- a
467: first survey ("cross") where individuals from different ages are
468: interviewed on their health status or degree of disability (in the
469: case of a health survey which is our main interest) -2- at least a
470: second wave of interviews ("longitudinal") which measure each change
471: (if any) in individual health status. Health expectancies are
472: computed from the time spent in each health state according to a
473: model. More health states you consider, more time is necessary to reach the
474: Maximum Likelihood of the parameters involved in the model. The
475: simplest model is the multinomial logistic model where pij is the
476: probability to be observed in state j at the second wave
477: conditional to be observed in state i at the first wave. Therefore
478: the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
479: 'age' is age and 'sex' is a covariate. If you want to have a more
480: complex model than "constant and age", you should modify the program
481: where the markup *Covariates have to be included here again* invites
482: you to do it. More covariates you add, slower the
483: convergence.
484:
485: The advantage of this computer programme, compared to a simple
486: multinomial logistic model, is clear when the delay between waves is not
487: identical for each individual. Also, if a individual missed an
488: intermediate interview, the information is lost, but taken into
489: account using an interpolation or extrapolation.
490:
491: hPijx is the probability to be observed in state i at age x+h
492: conditional to the observed state i at age x. The delay 'h' can be
493: split into an exact number (nh*stepm) of unobserved intermediate
494: states. This elementary transition (by month, quarter,
495: semester or year) is modelled as a multinomial logistic. The hPx
496: matrix is simply the matrix product of nh*stepm elementary matrices
497: and the contribution of each individual to the likelihood is simply
498: hPijx.
499:
500: Also this programme outputs the covariance matrix of the parameters but also
501: of the life expectancies. It also computes the period (stable) prevalence.
502:
503: Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
504: Institut national d'études démographiques, Paris.
505: This software have been partly granted by Euro-REVES, a concerted action
506: from the European Union.
507: It is copyrighted identically to a GNU software product, ie programme and
508: software can be distributed freely for non commercial use. Latest version
509: can be accessed at http://euroreves.ined.fr/imach .
510:
511: Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
512: or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
513:
514: **********************************************************************/
515: /*
516: main
517: read parameterfile
518: read datafile
519: concatwav
520: freqsummary
521: if (mle >= 1)
522: mlikeli
523: print results files
524: if mle==1
525: computes hessian
526: read end of parameter file: agemin, agemax, bage, fage, estepm
527: begin-prev-date,...
528: open gnuplot file
529: open html file
530: period (stable) prevalence | pl_nom 1-1 2-2 etc by covariate
531: for age prevalim() | #****** V1=0 V2=1 V3=1 V4=0 ******
532: | 65 1 0 2 1 3 1 4 0 0.96326 0.03674
533: freexexit2 possible for memory heap.
534:
535: h Pij x | pij_nom ficrestpij
536: # Cov Agex agex+h hpijx with i,j= 1-1 1-2 1-3 2-1 2-2 2-3
537: 1 85 85 1.00000 0.00000 0.00000 0.00000 1.00000 0.00000
538: 1 85 86 0.68299 0.22291 0.09410 0.71093 0.00000 0.28907
539:
540: 1 65 99 0.00364 0.00322 0.99314 0.00350 0.00310 0.99340
541: 1 65 100 0.00214 0.00204 0.99581 0.00206 0.00196 0.99597
542: variance of p one-step probabilities varprob | prob_nom ficresprob #One-step probabilities and stand. devi in ()
543: Standard deviation of one-step probabilities | probcor_nom ficresprobcor #One-step probabilities and correlation matrix
544: Matrix of variance covariance of one-step probabilities | probcov_nom ficresprobcov #One-step probabilities and covariance matrix
545:
546: forecasting if prevfcast==1 prevforecast call prevalence()
547: health expectancies
548: Variance-covariance of DFLE
549: prevalence()
550: movingaverage()
551: varevsij()
552: if popbased==1 varevsij(,popbased)
553: total life expectancies
554: Variance of period (stable) prevalence
555: end
556: */
557:
558: #define POWELL /* Instead of NLOPT */
559:
560: #include <math.h>
561: #include <stdio.h>
562: #include <stdlib.h>
563: #include <string.h>
564:
565: #ifdef _WIN32
566: #include <io.h>
567: #include <windows.h>
568: #include <tchar.h>
569: #else
570: #include <unistd.h>
571: #endif
572:
573: #include <limits.h>
574: #include <sys/types.h>
575:
576: #if defined(__GNUC__)
577: #include <sys/utsname.h> /* Doesn't work on Windows */
578: #endif
579:
580: #include <sys/stat.h>
581: #include <errno.h>
582: /* extern int errno; */
583:
584: /* #ifdef LINUX */
585: /* #include <time.h> */
586: /* #include "timeval.h" */
587: /* #else */
588: /* #include <sys/time.h> */
589: /* #endif */
590:
591: #include <time.h>
592:
593: #ifdef GSL
594: #include <gsl/gsl_errno.h>
595: #include <gsl/gsl_multimin.h>
596: #endif
597:
598:
599: #ifdef NLOPT
600: #include <nlopt.h>
601: typedef struct {
602: double (* function)(double [] );
603: } myfunc_data ;
604: #endif
605:
606: /* #include <libintl.h> */
607: /* #define _(String) gettext (String) */
608:
609: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
610:
611: #define GNUPLOTPROGRAM "gnuplot"
612: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
613: #define FILENAMELENGTH 132
614:
615: #define GLOCK_ERROR_NOPATH -1 /* empty path */
616: #define GLOCK_ERROR_GETCWD -2 /* cannot get cwd */
617:
618: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
619: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
620:
621: #define NINTERVMAX 8
622: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
623: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
624: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
625: #define codtabm(h,k) 1 & (h-1) >> (k-1) ;
626: #define MAXN 20000
627: #define YEARM 12. /**< Number of months per year */
628: #define AGESUP 130
629: #define AGEBASE 40
630: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
631: #ifdef _WIN32
632: #define DIRSEPARATOR '\\'
633: #define CHARSEPARATOR "\\"
634: #define ODIRSEPARATOR '/'
635: #else
636: #define DIRSEPARATOR '/'
637: #define CHARSEPARATOR "/"
638: #define ODIRSEPARATOR '\\'
639: #endif
640:
641: /* $Id: imach.c,v 1.180 2015/02/11 17:33:45 brouard Exp $ */
642: /* $State: Exp $ */
643:
644: 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";
645: char fullversion[]="$Revision: 1.180 $ $Date: 2015/02/11 17:33:45 $";
646: char strstart[80];
647: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
648: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings */
649: int nvar=0, nforce=0; /* Number of variables, number of forces */
650: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
651: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
652: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
653: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
654: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
655: int cptcovprodnoage=0; /**< Number of covariate products without age */
656: int cptcoveff=0; /* Total number of covariates to vary for printing results */
657: int cptcov=0; /* Working variable */
658: int npar=NPARMAX;
659: int nlstate=2; /* Number of live states */
660: int ndeath=1; /* Number of dead states */
661: int ncovmodel=0, ncovcol=0; /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
662: int popbased=0;
663:
664: int *wav; /* Number of waves for this individuual 0 is possible */
665: int maxwav=0; /* Maxim number of waves */
666: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
667: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */
668: int gipmx=0, gsw=0; /* Global variables on the number of contributions
669: to the likelihood and the sum of weights (done by funcone)*/
670: int mle=1, weightopt=0;
671: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
672: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
673: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
674: * wave mi and wave mi+1 is not an exact multiple of stepm. */
675: int countcallfunc=0; /* Count the number of calls to func */
676: double jmean=1; /* Mean space between 2 waves */
677: double **matprod2(); /* test */
678: double **oldm, **newm, **savm; /* Working pointers to matrices */
679: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
680: /*FILE *fic ; */ /* Used in readdata only */
681: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
682: FILE *ficlog, *ficrespow;
683: int globpr=0; /* Global variable for printing or not */
684: double fretone; /* Only one call to likelihood */
685: long ipmx=0; /* Number of contributions */
686: double sw; /* Sum of weights */
687: char filerespow[FILENAMELENGTH];
688: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
689: FILE *ficresilk;
690: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
691: FILE *ficresprobmorprev;
692: FILE *fichtm, *fichtmcov; /* Html File */
693: FILE *ficreseij;
694: char filerese[FILENAMELENGTH];
695: FILE *ficresstdeij;
696: char fileresstde[FILENAMELENGTH];
697: FILE *ficrescveij;
698: char filerescve[FILENAMELENGTH];
699: FILE *ficresvij;
700: char fileresv[FILENAMELENGTH];
701: FILE *ficresvpl;
702: char fileresvpl[FILENAMELENGTH];
703: char title[MAXLINE];
704: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH], filerespl[FILENAMELENGTH];
705: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
706: char tmpout[FILENAMELENGTH], tmpout2[FILENAMELENGTH];
707: char command[FILENAMELENGTH];
708: int outcmd=0;
709:
710: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
711:
712: char filelog[FILENAMELENGTH]; /* Log file */
713: char filerest[FILENAMELENGTH];
714: char fileregp[FILENAMELENGTH];
715: char popfile[FILENAMELENGTH];
716:
717: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
718:
719: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
720: /* struct timezone tzp; */
721: /* extern int gettimeofday(); */
722: struct tm tml, *gmtime(), *localtime();
723:
724: extern time_t time();
725:
726: struct tm start_time, end_time, curr_time, last_time, forecast_time;
727: time_t rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
728: struct tm tm;
729:
730: char strcurr[80], strfor[80];
731:
732: char *endptr;
733: long lval;
734: double dval;
735:
736: #define NR_END 1
737: #define FREE_ARG char*
738: #define FTOL 1.0e-10
739:
740: #define NRANSI
741: #define ITMAX 200
742:
743: #define TOL 2.0e-4
744:
745: #define CGOLD 0.3819660
746: #define ZEPS 1.0e-10
747: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
748:
749: #define GOLD 1.618034
750: #define GLIMIT 100.0
751: #define TINY 1.0e-20
752:
753: static double maxarg1,maxarg2;
754: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
755: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
756:
757: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
758: #define rint(a) floor(a+0.5)
759: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
760: /* #define mytinydouble 1.0e-16 */
761: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
762: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
763: /* static double dsqrarg; */
764: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
765: static double sqrarg;
766: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
767: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
768: int agegomp= AGEGOMP;
769:
770: int imx;
771: int stepm=1;
772: /* Stepm, step in month: minimum step interpolation*/
773:
774: int estepm;
775: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
776:
777: int m,nb;
778: long *num;
779: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
780: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
781: double **pmmij, ***probs;
782: double *ageexmed,*agecens;
783: double dateintmean=0;
784:
785: double *weight;
786: int **s; /* Status */
787: double *agedc;
788: double **covar; /**< covar[j,i], value of jth covariate for individual i,
789: * covar=matrix(0,NCOVMAX,1,n);
790: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; */
791: double idx;
792: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
793: int *Ndum; /** Freq of modality (tricode */
794: int **codtab; /**< codtab=imatrix(1,100,1,10); */
795: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
796: double *lsurv, *lpop, *tpop;
797:
798: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
799: double ftolhess; /**< Tolerance for computing hessian */
800:
801: /**************** split *************************/
802: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
803: {
804: /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
805: the name of the file (name), its extension only (ext) and its first part of the name (finame)
806: */
807: char *ss; /* pointer */
808: int l1, l2; /* length counters */
809:
810: l1 = strlen(path ); /* length of path */
811: if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
812: ss= strrchr( path, DIRSEPARATOR ); /* find last / */
813: if ( ss == NULL ) { /* no directory, so determine current directory */
814: strcpy( name, path ); /* we got the fullname name because no directory */
815: /*if(strrchr(path, ODIRSEPARATOR )==NULL)
816: printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
817: /* get current working directory */
818: /* extern char* getcwd ( char *buf , int len);*/
819: if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
820: return( GLOCK_ERROR_GETCWD );
821: }
822: /* got dirc from getcwd*/
823: printf(" DIRC = %s \n",dirc);
824: } else { /* strip direcotry from path */
825: ss++; /* after this, the filename */
826: l2 = strlen( ss ); /* length of filename */
827: if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
828: strcpy( name, ss ); /* save file name */
829: strncpy( dirc, path, l1 - l2 ); /* now the directory */
830: dirc[l1-l2] = 0; /* add zero */
831: printf(" DIRC2 = %s \n",dirc);
832: }
833: /* We add a separator at the end of dirc if not exists */
834: l1 = strlen( dirc ); /* length of directory */
835: if( dirc[l1-1] != DIRSEPARATOR ){
836: dirc[l1] = DIRSEPARATOR;
837: dirc[l1+1] = 0;
838: printf(" DIRC3 = %s \n",dirc);
839: }
840: ss = strrchr( name, '.' ); /* find last / */
841: if (ss >0){
842: ss++;
843: strcpy(ext,ss); /* save extension */
844: l1= strlen( name);
845: l2= strlen(ss)+1;
846: strncpy( finame, name, l1-l2);
847: finame[l1-l2]= 0;
848: }
849:
850: return( 0 ); /* we're done */
851: }
852:
853:
854: /******************************************/
855:
856: void replace_back_to_slash(char *s, char*t)
857: {
858: int i;
859: int lg=0;
860: i=0;
861: lg=strlen(t);
862: for(i=0; i<= lg; i++) {
863: (s[i] = t[i]);
864: if (t[i]== '\\') s[i]='/';
865: }
866: }
867:
868: char *trimbb(char *out, char *in)
869: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
870: char *s;
871: s=out;
872: while (*in != '\0'){
873: while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
874: in++;
875: }
876: *out++ = *in++;
877: }
878: *out='\0';
879: return s;
880: }
881:
882: char *cutl(char *blocc, char *alocc, char *in, char occ)
883: {
884: /* cuts string in into blocc and alocc where blocc ends before first occurence of char 'occ'
885: and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
886: gives blocc="abcdef2ghi" and alocc="j".
887: If occ is not found blocc is null and alocc is equal to in. Returns blocc
888: */
889: char *s, *t;
890: t=in;s=in;
891: while ((*in != occ) && (*in != '\0')){
892: *alocc++ = *in++;
893: }
894: if( *in == occ){
895: *(alocc)='\0';
896: s=++in;
897: }
898:
899: if (s == t) {/* occ not found */
900: *(alocc-(in-s))='\0';
901: in=s;
902: }
903: while ( *in != '\0'){
904: *blocc++ = *in++;
905: }
906:
907: *blocc='\0';
908: return t;
909: }
910: char *cutv(char *blocc, char *alocc, char *in, char occ)
911: {
912: /* cuts string in into blocc and alocc where blocc ends before last occurence of char 'occ'
913: and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
914: gives blocc="abcdef2ghi" and alocc="j".
915: If occ is not found blocc is null and alocc is equal to in. Returns alocc
916: */
917: char *s, *t;
918: t=in;s=in;
919: while (*in != '\0'){
920: while( *in == occ){
921: *blocc++ = *in++;
922: s=in;
923: }
924: *blocc++ = *in++;
925: }
926: if (s == t) /* occ not found */
927: *(blocc-(in-s))='\0';
928: else
929: *(blocc-(in-s)-1)='\0';
930: in=s;
931: while ( *in != '\0'){
932: *alocc++ = *in++;
933: }
934:
935: *alocc='\0';
936: return s;
937: }
938:
939: int nbocc(char *s, char occ)
940: {
941: int i,j=0;
942: int lg=20;
943: i=0;
944: lg=strlen(s);
945: for(i=0; i<= lg; i++) {
946: if (s[i] == occ ) j++;
947: }
948: return j;
949: }
950:
951: /* void cutv(char *u,char *v, char*t, char occ) */
952: /* { */
953: /* /\* cuts string t into u and v where u ends before last occurence of char 'occ' */
954: /* and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
955: /* gives u="abcdef2ghi" and v="j" *\/ */
956: /* int i,lg,j,p=0; */
957: /* i=0; */
958: /* lg=strlen(t); */
959: /* for(j=0; j<=lg-1; j++) { */
960: /* if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
961: /* } */
962:
963: /* for(j=0; j<p; j++) { */
964: /* (u[j] = t[j]); */
965: /* } */
966: /* u[p]='\0'; */
967:
968: /* for(j=0; j<= lg; j++) { */
969: /* if (j>=(p+1))(v[j-p-1] = t[j]); */
970: /* } */
971: /* } */
972:
973: #ifdef _WIN32
974: char * strsep(char **pp, const char *delim)
975: {
976: char *p, *q;
977:
978: if ((p = *pp) == NULL)
979: return 0;
980: if ((q = strpbrk (p, delim)) != NULL)
981: {
982: *pp = q + 1;
983: *q = '\0';
984: }
985: else
986: *pp = 0;
987: return p;
988: }
989: #endif
990:
991: /********************** nrerror ********************/
992:
993: void nrerror(char error_text[])
994: {
995: fprintf(stderr,"ERREUR ...\n");
996: fprintf(stderr,"%s\n",error_text);
997: exit(EXIT_FAILURE);
998: }
999: /*********************** vector *******************/
1000: double *vector(int nl, int nh)
1001: {
1002: double *v;
1003: v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
1004: if (!v) nrerror("allocation failure in vector");
1005: return v-nl+NR_END;
1006: }
1007:
1008: /************************ free vector ******************/
1009: void free_vector(double*v, int nl, int nh)
1010: {
1011: free((FREE_ARG)(v+nl-NR_END));
1012: }
1013:
1014: /************************ivector *******************************/
1015: int *ivector(long nl,long nh)
1016: {
1017: int *v;
1018: v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
1019: if (!v) nrerror("allocation failure in ivector");
1020: return v-nl+NR_END;
1021: }
1022:
1023: /******************free ivector **************************/
1024: void free_ivector(int *v, long nl, long nh)
1025: {
1026: free((FREE_ARG)(v+nl-NR_END));
1027: }
1028:
1029: /************************lvector *******************************/
1030: long *lvector(long nl,long nh)
1031: {
1032: long *v;
1033: v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
1034: if (!v) nrerror("allocation failure in ivector");
1035: return v-nl+NR_END;
1036: }
1037:
1038: /******************free lvector **************************/
1039: void free_lvector(long *v, long nl, long nh)
1040: {
1041: free((FREE_ARG)(v+nl-NR_END));
1042: }
1043:
1044: /******************* imatrix *******************************/
1045: int **imatrix(long nrl, long nrh, long ncl, long nch)
1046: /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
1047: {
1048: long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
1049: int **m;
1050:
1051: /* allocate pointers to rows */
1052: m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
1053: if (!m) nrerror("allocation failure 1 in matrix()");
1054: m += NR_END;
1055: m -= nrl;
1056:
1057:
1058: /* allocate rows and set pointers to them */
1059: m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
1060: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1061: m[nrl] += NR_END;
1062: m[nrl] -= ncl;
1063:
1064: for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
1065:
1066: /* return pointer to array of pointers to rows */
1067: return m;
1068: }
1069:
1070: /****************** free_imatrix *************************/
1071: void free_imatrix(m,nrl,nrh,ncl,nch)
1072: int **m;
1073: long nch,ncl,nrh,nrl;
1074: /* free an int matrix allocated by imatrix() */
1075: {
1076: free((FREE_ARG) (m[nrl]+ncl-NR_END));
1077: free((FREE_ARG) (m+nrl-NR_END));
1078: }
1079:
1080: /******************* matrix *******************************/
1081: double **matrix(long nrl, long nrh, long ncl, long nch)
1082: {
1083: long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
1084: double **m;
1085:
1086: m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1087: if (!m) nrerror("allocation failure 1 in matrix()");
1088: m += NR_END;
1089: m -= nrl;
1090:
1091: m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1092: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1093: m[nrl] += NR_END;
1094: m[nrl] -= ncl;
1095:
1096: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1097: return m;
1098: /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
1099: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
1100: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1101: */
1102: }
1103:
1104: /*************************free matrix ************************/
1105: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
1106: {
1107: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1108: free((FREE_ARG)(m+nrl-NR_END));
1109: }
1110:
1111: /******************* ma3x *******************************/
1112: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
1113: {
1114: long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
1115: double ***m;
1116:
1117: m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1118: if (!m) nrerror("allocation failure 1 in matrix()");
1119: m += NR_END;
1120: m -= nrl;
1121:
1122: m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1123: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1124: m[nrl] += NR_END;
1125: m[nrl] -= ncl;
1126:
1127: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1128:
1129: m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
1130: if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
1131: m[nrl][ncl] += NR_END;
1132: m[nrl][ncl] -= nll;
1133: for (j=ncl+1; j<=nch; j++)
1134: m[nrl][j]=m[nrl][j-1]+nlay;
1135:
1136: for (i=nrl+1; i<=nrh; i++) {
1137: m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
1138: for (j=ncl+1; j<=nch; j++)
1139: m[i][j]=m[i][j-1]+nlay;
1140: }
1141: return m;
1142: /* gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
1143: &(m[i][j][k]) <=> *((*(m+i) + j)+k)
1144: */
1145: }
1146:
1147: /*************************free ma3x ************************/
1148: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
1149: {
1150: free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
1151: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1152: free((FREE_ARG)(m+nrl-NR_END));
1153: }
1154:
1155: /*************** function subdirf ***********/
1156: char *subdirf(char fileres[])
1157: {
1158: /* Caution optionfilefiname is hidden */
1159: strcpy(tmpout,optionfilefiname);
1160: strcat(tmpout,"/"); /* Add to the right */
1161: strcat(tmpout,fileres);
1162: return tmpout;
1163: }
1164:
1165: /*************** function subdirf2 ***********/
1166: char *subdirf2(char fileres[], char *preop)
1167: {
1168:
1169: /* Caution optionfilefiname is hidden */
1170: strcpy(tmpout,optionfilefiname);
1171: strcat(tmpout,"/");
1172: strcat(tmpout,preop);
1173: strcat(tmpout,fileres);
1174: return tmpout;
1175: }
1176:
1177: /*************** function subdirf3 ***********/
1178: char *subdirf3(char fileres[], char *preop, char *preop2)
1179: {
1180:
1181: /* Caution optionfilefiname is hidden */
1182: strcpy(tmpout,optionfilefiname);
1183: strcat(tmpout,"/");
1184: strcat(tmpout,preop);
1185: strcat(tmpout,preop2);
1186: strcat(tmpout,fileres);
1187: return tmpout;
1188: }
1189:
1190: char *asc_diff_time(long time_sec, char ascdiff[])
1191: {
1192: long sec_left, days, hours, minutes;
1193: days = (time_sec) / (60*60*24);
1194: sec_left = (time_sec) % (60*60*24);
1195: hours = (sec_left) / (60*60) ;
1196: sec_left = (sec_left) %(60*60);
1197: minutes = (sec_left) /60;
1198: sec_left = (sec_left) % (60);
1199: sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);
1200: return ascdiff;
1201: }
1202:
1203: /***************** f1dim *************************/
1204: extern int ncom;
1205: extern double *pcom,*xicom;
1206: extern double (*nrfunc)(double []);
1207:
1208: double f1dim(double x)
1209: {
1210: int j;
1211: double f;
1212: double *xt;
1213:
1214: xt=vector(1,ncom);
1215: for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
1216: f=(*nrfunc)(xt);
1217: free_vector(xt,1,ncom);
1218: return f;
1219: }
1220:
1221: /*****************brent *************************/
1222: double brent(double ax, double bx, double cx, double (*f)(double), double tol, double *xmin)
1223: {
1224: int iter;
1225: double a,b,d,etemp;
1226: double fu=0,fv,fw,fx;
1227: double ftemp=0.;
1228: double p,q,r,tol1,tol2,u,v,w,x,xm;
1229: double e=0.0;
1230:
1231: a=(ax < cx ? ax : cx);
1232: b=(ax > cx ? ax : cx);
1233: x=w=v=bx;
1234: fw=fv=fx=(*f)(x);
1235: for (iter=1;iter<=ITMAX;iter++) {
1236: xm=0.5*(a+b);
1237: tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
1238: /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
1239: printf(".");fflush(stdout);
1240: fprintf(ficlog,".");fflush(ficlog);
1241: #ifdef DEBUGBRENT
1242: 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);
1243: 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);
1244: /* if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
1245: #endif
1246: if (fabs(x-xm) <= (tol2-0.5*(b-a))){
1247: *xmin=x;
1248: return fx;
1249: }
1250: ftemp=fu;
1251: if (fabs(e) > tol1) {
1252: r=(x-w)*(fx-fv);
1253: q=(x-v)*(fx-fw);
1254: p=(x-v)*q-(x-w)*r;
1255: q=2.0*(q-r);
1256: if (q > 0.0) p = -p;
1257: q=fabs(q);
1258: etemp=e;
1259: e=d;
1260: if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
1261: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1262: else {
1263: d=p/q;
1264: u=x+d;
1265: if (u-a < tol2 || b-u < tol2)
1266: d=SIGN(tol1,xm-x);
1267: }
1268: } else {
1269: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1270: }
1271: u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
1272: fu=(*f)(u);
1273: if (fu <= fx) {
1274: if (u >= x) a=x; else b=x;
1275: SHFT(v,w,x,u)
1276: SHFT(fv,fw,fx,fu)
1277: } else {
1278: if (u < x) a=u; else b=u;
1279: if (fu <= fw || w == x) {
1280: v=w;
1281: w=u;
1282: fv=fw;
1283: fw=fu;
1284: } else if (fu <= fv || v == x || v == w) {
1285: v=u;
1286: fv=fu;
1287: }
1288: }
1289: }
1290: nrerror("Too many iterations in brent");
1291: *xmin=x;
1292: return fx;
1293: }
1294:
1295: /****************** mnbrak ***********************/
1296:
1297: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
1298: double (*func)(double))
1299: {
1300: double ulim,u,r,q, dum;
1301: double fu;
1302:
1303: *fa=(*func)(*ax);
1304: *fb=(*func)(*bx);
1305: if (*fb > *fa) {
1306: SHFT(dum,*ax,*bx,dum)
1307: SHFT(dum,*fb,*fa,dum)
1308: }
1309: *cx=(*bx)+GOLD*(*bx-*ax);
1310: *fc=(*func)(*cx);
1311: while (*fb > *fc) { /* Declining fa, fb, fc */
1312: r=(*bx-*ax)*(*fb-*fc);
1313: q=(*bx-*cx)*(*fb-*fa);
1314: u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
1315: (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscisse of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
1316: ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscisse where function can be evaluated */
1317: if ((*bx-u)*(u-*cx) > 0.0) { /* if u between b and c */
1318: fu=(*func)(u);
1319: #ifdef DEBUG
1320: /* f(x)=A(x-u)**2+f(u) */
1321: double A, fparabu;
1322: A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
1323: fparabu= *fa - A*(*ax-u)*(*ax-u);
1324: 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);
1325: 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);
1326: #endif
1327: } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1328: fu=(*func)(u);
1329: if (fu < *fc) {
1330: SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
1331: SHFT(*fb,*fc,fu,(*func)(u))
1332: }
1333: } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1334: u=ulim;
1335: fu=(*func)(u);
1336: } else {
1337: u=(*cx)+GOLD*(*cx-*bx);
1338: fu=(*func)(u);
1339: }
1340: SHFT(*ax,*bx,*cx,u)
1341: SHFT(*fa,*fb,*fc,fu)
1342: }
1343: }
1344:
1345: /*************** linmin ************************/
1346: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
1347: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
1348: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
1349: the value of func at the returned location p . This is actually all accomplished by calling the
1350: routines mnbrak and brent .*/
1351: int ncom;
1352: double *pcom,*xicom;
1353: double (*nrfunc)(double []);
1354:
1355: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
1356: {
1357: double brent(double ax, double bx, double cx,
1358: double (*f)(double), double tol, double *xmin);
1359: double f1dim(double x);
1360: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
1361: double *fc, double (*func)(double));
1362: int j;
1363: double xx,xmin,bx,ax;
1364: double fx,fb,fa;
1365:
1366: ncom=n;
1367: pcom=vector(1,n);
1368: xicom=vector(1,n);
1369: nrfunc=func;
1370: for (j=1;j<=n;j++) {
1371: pcom[j]=p[j];
1372: xicom[j]=xi[j];
1373: }
1374: ax=0.0;
1375: xx=1.0;
1376: mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Find a bracket a,x,b in direction n=xi ie xicom */
1377: *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Find a minimum P+lambda n in that direction (lambdamin), with TOL between abscisses */
1378: #ifdef DEBUG
1379: printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1380: fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1381: #endif
1382: for (j=1;j<=n;j++) {
1383: xi[j] *= xmin;
1384: p[j] += xi[j];
1385: }
1386: free_vector(xicom,1,n);
1387: free_vector(pcom,1,n);
1388: }
1389:
1390:
1391: /*************** powell ************************/
1392: /*
1393: Minimization of a function func of n variables. Input consists of an initial starting point
1394: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
1395: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
1396: such that failure to decrease by more than this amount on one iteration signals doneness. On
1397: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
1398: function value at p , and iter is the number of iterations taken. The routine linmin is used.
1399: */
1400: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
1401: double (*func)(double []))
1402: {
1403: void linmin(double p[], double xi[], int n, double *fret,
1404: double (*func)(double []));
1405: int i,ibig,j;
1406: double del,t,*pt,*ptt,*xit;
1407: double fp,fptt;
1408: double *xits;
1409: int niterf, itmp;
1410:
1411: pt=vector(1,n);
1412: ptt=vector(1,n);
1413: xit=vector(1,n);
1414: xits=vector(1,n);
1415: *fret=(*func)(p);
1416: for (j=1;j<=n;j++) pt[j]=p[j];
1417: rcurr_time = time(NULL);
1418: for (*iter=1;;++(*iter)) {
1419: fp=(*fret);
1420: ibig=0;
1421: del=0.0;
1422: rlast_time=rcurr_time;
1423: /* (void) gettimeofday(&curr_time,&tzp); */
1424: rcurr_time = time(NULL);
1425: curr_time = *localtime(&rcurr_time);
1426: printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
1427: fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1428: /* fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1429: for (i=1;i<=n;i++) {
1430: printf(" %d %.12f",i, p[i]);
1431: fprintf(ficlog," %d %.12lf",i, p[i]);
1432: fprintf(ficrespow," %.12lf", p[i]);
1433: }
1434: printf("\n");
1435: fprintf(ficlog,"\n");
1436: fprintf(ficrespow,"\n");fflush(ficrespow);
1437: if(*iter <=3){
1438: tml = *localtime(&rcurr_time);
1439: strcpy(strcurr,asctime(&tml));
1440: rforecast_time=rcurr_time;
1441: itmp = strlen(strcurr);
1442: if(strcurr[itmp-1]=='\n') /* Windows outputs with a new line */
1443: strcurr[itmp-1]='\0';
1444: printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1445: fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1446: for(niterf=10;niterf<=30;niterf+=10){
1447: rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
1448: forecast_time = *localtime(&rforecast_time);
1449: strcpy(strfor,asctime(&forecast_time));
1450: itmp = strlen(strfor);
1451: if(strfor[itmp-1]=='\n')
1452: strfor[itmp-1]='\0';
1453: 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);
1454: 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);
1455: }
1456: }
1457: for (i=1;i<=n;i++) {
1458: for (j=1;j<=n;j++) xit[j]=xi[j][i];
1459: fptt=(*fret);
1460: #ifdef DEBUG
1461: printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1462: fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1463: #endif
1464: printf("%d",i);fflush(stdout);
1465: fprintf(ficlog,"%d",i);fflush(ficlog);
1466: linmin(p,xit,n,fret,func);
1467: if (fabs(fptt-(*fret)) > del) {
1468: del=fabs(fptt-(*fret));
1469: ibig=i;
1470: }
1471: #ifdef DEBUG
1472: printf("%d %.12e",i,(*fret));
1473: fprintf(ficlog,"%d %.12e",i,(*fret));
1474: for (j=1;j<=n;j++) {
1475: xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
1476: printf(" x(%d)=%.12e",j,xit[j]);
1477: fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1478: }
1479: for(j=1;j<=n;j++) {
1480: printf(" p(%d)=%.12e",j,p[j]);
1481: fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1482: }
1483: printf("\n");
1484: fprintf(ficlog,"\n");
1485: #endif
1486: } /* end i */
1487: if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
1488: #ifdef DEBUG
1489: int k[2],l;
1490: k[0]=1;
1491: k[1]=-1;
1492: printf("Max: %.12e",(*func)(p));
1493: fprintf(ficlog,"Max: %.12e",(*func)(p));
1494: for (j=1;j<=n;j++) {
1495: printf(" %.12e",p[j]);
1496: fprintf(ficlog," %.12e",p[j]);
1497: }
1498: printf("\n");
1499: fprintf(ficlog,"\n");
1500: for(l=0;l<=1;l++) {
1501: for (j=1;j<=n;j++) {
1502: ptt[j]=p[j]+(p[j]-pt[j])*k[l];
1503: printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1504: fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1505: }
1506: printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1507: fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1508: }
1509: #endif
1510:
1511:
1512: free_vector(xit,1,n);
1513: free_vector(xits,1,n);
1514: free_vector(ptt,1,n);
1515: free_vector(pt,1,n);
1516: return;
1517: }
1518: if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
1519: for (j=1;j<=n;j++) { /* Computes an extrapolated point */
1520: ptt[j]=2.0*p[j]-pt[j];
1521: xit[j]=p[j]-pt[j];
1522: pt[j]=p[j];
1523: }
1524: fptt=(*func)(ptt);
1525: if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1526: /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1527: /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1528: /* Let f"(x2) be the 2nd derivative equal everywhere. */
1529: /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
1530: /* will reach at f3 = fm + h^2/2 f"m ; f" = (f1 -2f2 +f3 ) / h**2 */
1531: /* f1-f3 = delta(2h) = 2 h**2 f'' = 2(f1- 2f2 +f3) */
1532: /* Thus we compare delta(2h) with observed f1-f3 */
1533: /* or best gain on one ancient line 'del' with total */
1534: /* gain f1-f2 = f1 - f2 - 'del' with del */
1535: /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1536:
1537: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del);
1538: t= t- del*SQR(fp-fptt);
1539: printf("t1= %.12lf, t2= %.12lf, t=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t);
1540: fprintf(ficlog,"t1= %.12lf, t2= %.12lf, t=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t);
1541: #ifdef DEBUG
1542: printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1543: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1544: fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1545: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1546: 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);
1547: 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);
1548: #endif
1549: if (t < 0.0) { /* Then we use it for last direction */
1550: linmin(p,xit,n,fret,func); /* computes mean on the extrapolated direction.*/
1551: for (j=1;j<=n;j++) {
1552: xi[j][ibig]=xi[j][n]; /* Replace the direction with biggest decrease by n */
1553: xi[j][n]=xit[j]; /* and nth direction by the extrapolated */
1554: }
1555: printf("Gaining to use average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1556: fprintf(ficlog,"Gaining to use average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1557:
1558: #ifdef DEBUG
1559: printf("Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1560: fprintf(ficlog,"Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1561: for(j=1;j<=n;j++){
1562: printf(" %.12e",xit[j]);
1563: fprintf(ficlog," %.12e",xit[j]);
1564: }
1565: printf("\n");
1566: fprintf(ficlog,"\n");
1567: #endif
1568: } /* end of t negative */
1569: } /* end if (fptt < fp) */
1570: }
1571: }
1572:
1573: /**** Prevalence limit (stable or period prevalence) ****************/
1574:
1575: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
1576: {
1577: /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1578: matrix by transitions matrix until convergence is reached */
1579:
1580: int i, ii,j,k;
1581: double min, max, maxmin, maxmax,sumnew=0.;
1582: /* double **matprod2(); */ /* test */
1583: double **out, cov[NCOVMAX+1], **pmij();
1584: double **newm;
1585: double agefin, delaymax=50 ; /* Max number of years to converge */
1586:
1587: for (ii=1;ii<=nlstate+ndeath;ii++)
1588: for (j=1;j<=nlstate+ndeath;j++){
1589: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1590: }
1591:
1592: cov[1]=1.;
1593:
1594: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1595: for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1596: newm=savm;
1597: /* Covariates have to be included here again */
1598: cov[2]=agefin;
1599:
1600: for (k=1; k<=cptcovn;k++) {
1601: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1602: /*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]]);*/
1603: }
1604: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1605: /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
1606: /* cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]] * nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]]; */
1607:
1608: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
1609: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
1610: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1611: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1612: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1613: out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1614:
1615: savm=oldm;
1616: oldm=newm;
1617: maxmax=0.;
1618: for(j=1;j<=nlstate;j++){
1619: min=1.;
1620: max=0.;
1621: for(i=1; i<=nlstate; i++) {
1622: sumnew=0;
1623: for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
1624: prlim[i][j]= newm[i][j]/(1-sumnew);
1625: /*printf(" prevalim i=%d, j=%d, prmlim[%d][%d]=%f, agefin=%d \n", i, j, i, j, prlim[i][j],(int)agefin);*/
1626: max=FMAX(max,prlim[i][j]);
1627: min=FMIN(min,prlim[i][j]);
1628: }
1629: maxmin=max-min;
1630: maxmax=FMAX(maxmax,maxmin);
1631: } /* j loop */
1632: if(maxmax < ftolpl){
1633: return prlim;
1634: }
1635: } /* age loop */
1636: return prlim; /* should not reach here */
1637: }
1638:
1639: /*************** transition probabilities ***************/
1640:
1641: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1642: {
1643: /* According to parameters values stored in x and the covariate's values stored in cov,
1644: computes the probability to be observed in state j being in state i by appying the
1645: model to the ncovmodel covariates (including constant and age).
1646: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
1647: and, according on how parameters are entered, the position of the coefficient xij(nc) of the
1648: ncth covariate in the global vector x is given by the formula:
1649: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
1650: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
1651: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
1652: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1653: Outputs ps[i][j] the probability to be observed in j being in j according to
1654: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1655: */
1656: double s1, lnpijopii;
1657: /*double t34;*/
1658: int i,j, nc, ii, jj;
1659:
1660: for(i=1; i<= nlstate; i++){
1661: for(j=1; j<i;j++){
1662: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1663: /*lnpijopii += param[i][j][nc]*cov[nc];*/
1664: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
1665: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1666: }
1667: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1668: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1669: }
1670: for(j=i+1; j<=nlstate+ndeath;j++){
1671: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1672: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
1673: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
1674: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1675: }
1676: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1677: }
1678: }
1679:
1680: for(i=1; i<= nlstate; i++){
1681: s1=0;
1682: for(j=1; j<i; j++){
1683: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1684: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1685: }
1686: for(j=i+1; j<=nlstate+ndeath; j++){
1687: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1688: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1689: }
1690: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1691: ps[i][i]=1./(s1+1.);
1692: /* Computing other pijs */
1693: for(j=1; j<i; j++)
1694: ps[i][j]= exp(ps[i][j])*ps[i][i];
1695: for(j=i+1; j<=nlstate+ndeath; j++)
1696: ps[i][j]= exp(ps[i][j])*ps[i][i];
1697: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
1698: } /* end i */
1699:
1700: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
1701: for(jj=1; jj<= nlstate+ndeath; jj++){
1702: ps[ii][jj]=0;
1703: ps[ii][ii]=1;
1704: }
1705: }
1706:
1707:
1708: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
1709: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */
1710: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
1711: /* } */
1712: /* printf("\n "); */
1713: /* } */
1714: /* printf("\n ");printf("%lf ",cov[2]);*/
1715: /*
1716: for(i=1; i<= npar; i++) printf("%f ",x[i]);
1717: goto end;*/
1718: return ps;
1719: }
1720:
1721: /**************** Product of 2 matrices ******************/
1722:
1723: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1724: {
1725: /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
1726: b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
1727: /* in, b, out are matrice of pointers which should have been initialized
1728: before: only the contents of out is modified. The function returns
1729: a pointer to pointers identical to out */
1730: int i, j, k;
1731: for(i=nrl; i<= nrh; i++)
1732: for(k=ncolol; k<=ncoloh; k++){
1733: out[i][k]=0.;
1734: for(j=ncl; j<=nch; j++)
1735: out[i][k] +=in[i][j]*b[j][k];
1736: }
1737: return out;
1738: }
1739:
1740:
1741: /************* Higher Matrix Product ***************/
1742:
1743: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
1744: {
1745: /* Computes the transition matrix starting at age 'age' over
1746: 'nhstepm*hstepm*stepm' months (i.e. until
1747: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
1748: nhstepm*hstepm matrices.
1749: Output is stored in matrix po[i][j][h] for h every 'hstepm' step
1750: (typically every 2 years instead of every month which is too big
1751: for the memory).
1752: Model is determined by parameters x and covariates have to be
1753: included manually here.
1754:
1755: */
1756:
1757: int i, j, d, h, k;
1758: double **out, cov[NCOVMAX+1];
1759: double **newm;
1760:
1761: /* Hstepm could be zero and should return the unit matrix */
1762: for (i=1;i<=nlstate+ndeath;i++)
1763: for (j=1;j<=nlstate+ndeath;j++){
1764: oldm[i][j]=(i==j ? 1.0 : 0.0);
1765: po[i][j][0]=(i==j ? 1.0 : 0.0);
1766: }
1767: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1768: for(h=1; h <=nhstepm; h++){
1769: for(d=1; d <=hstepm; d++){
1770: newm=savm;
1771: /* Covariates have to be included here again */
1772: cov[1]=1.;
1773: cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
1774: for (k=1; k<=cptcovn;k++)
1775: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1776: for (k=1; k<=cptcovage;k++)
1777: cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
1778: for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1779: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
1780:
1781:
1782: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
1783: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1784: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
1785: pmij(pmmij,cov,ncovmodel,x,nlstate));
1786: savm=oldm;
1787: oldm=newm;
1788: }
1789: for(i=1; i<=nlstate+ndeath; i++)
1790: for(j=1;j<=nlstate+ndeath;j++) {
1791: po[i][j][h]=newm[i][j];
1792: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1793: }
1794: /*printf("h=%d ",h);*/
1795: } /* end h */
1796: /* printf("\n H=%d \n",h); */
1797: return po;
1798: }
1799:
1800: #ifdef NLOPT
1801: double myfunc(unsigned n, const double *p1, double *grad, void *pd){
1802: double fret;
1803: double *xt;
1804: int j;
1805: myfunc_data *d2 = (myfunc_data *) pd;
1806: /* xt = (p1-1); */
1807: xt=vector(1,n);
1808: for (j=1;j<=n;j++) xt[j]=p1[j-1]; /* xt[1]=p1[0] */
1809:
1810: fret=(d2->function)(xt); /* p xt[1]@8 is fine */
1811: /* fret=(*func)(xt); /\* p xt[1]@8 is fine *\/ */
1812: printf("Function = %.12lf ",fret);
1813: for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]);
1814: printf("\n");
1815: free_vector(xt,1,n);
1816: return fret;
1817: }
1818: #endif
1819:
1820: /*************** log-likelihood *************/
1821: double func( double *x)
1822: {
1823: int i, ii, j, k, mi, d, kk;
1824: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1825: double **out;
1826: double sw; /* Sum of weights */
1827: double lli; /* Individual log likelihood */
1828: int s1, s2;
1829: double bbh, survp;
1830: long ipmx;
1831: /*extern weight */
1832: /* We are differentiating ll according to initial status */
1833: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
1834: /*for(i=1;i<imx;i++)
1835: printf(" %d\n",s[4][i]);
1836: */
1837:
1838: ++countcallfunc;
1839:
1840: cov[1]=1.;
1841:
1842: for(k=1; k<=nlstate; k++) ll[k]=0.;
1843:
1844: if(mle==1){
1845: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1846: /* Computes the values of the ncovmodel covariates of the model
1847: depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
1848: Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
1849: to be observed in j being in i according to the model.
1850: */
1851: for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1852: cov[2+k]=covar[Tvar[k]][i];
1853: }
1854: /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4]
1855: is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]
1856: has been calculated etc */
1857: for(mi=1; mi<= wav[i]-1; mi++){
1858: for (ii=1;ii<=nlstate+ndeath;ii++)
1859: for (j=1;j<=nlstate+ndeath;j++){
1860: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1861: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1862: }
1863: for(d=0; d<dh[mi][i]; d++){
1864: newm=savm;
1865: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1866: for (kk=1; kk<=cptcovage;kk++) {
1867: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; /* Tage[kk] gives the data-covariate associated with age */
1868: }
1869: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1870: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1871: savm=oldm;
1872: oldm=newm;
1873: } /* end mult */
1874:
1875: /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
1876: /* But now since version 0.9 we anticipate for bias at large stepm.
1877: * If stepm is larger than one month (smallest stepm) and if the exact delay
1878: * (in months) between two waves is not a multiple of stepm, we rounded to
1879: * the nearest (and in case of equal distance, to the lowest) interval but now
1880: * we keep into memory the bias bh[mi][i] and also the previous matrix product
1881: * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
1882: * probability in order to take into account the bias as a fraction of the way
1883: * from savm to out if bh is negative or even beyond if bh is positive. bh varies
1884: * -stepm/2 to stepm/2 .
1885: * For stepm=1 the results are the same as for previous versions of Imach.
1886: * For stepm > 1 the results are less biased than in previous versions.
1887: */
1888: s1=s[mw[mi][i]][i];
1889: s2=s[mw[mi+1][i]][i];
1890: bbh=(double)bh[mi][i]/(double)stepm;
1891: /* bias bh is positive if real duration
1892: * is higher than the multiple of stepm and negative otherwise.
1893: */
1894: /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
1895: if( s2 > nlstate){
1896: /* i.e. if s2 is a death state and if the date of death is known
1897: then the contribution to the likelihood is the probability to
1898: die between last step unit time and current step unit time,
1899: which is also equal to probability to die before dh
1900: minus probability to die before dh-stepm .
1901: In version up to 0.92 likelihood was computed
1902: as if date of death was unknown. Death was treated as any other
1903: health state: the date of the interview describes the actual state
1904: and not the date of a change in health state. The former idea was
1905: to consider that at each interview the state was recorded
1906: (healthy, disable or death) and IMaCh was corrected; but when we
1907: introduced the exact date of death then we should have modified
1908: the contribution of an exact death to the likelihood. This new
1909: contribution is smaller and very dependent of the step unit
1910: stepm. It is no more the probability to die between last interview
1911: and month of death but the probability to survive from last
1912: interview up to one month before death multiplied by the
1913: probability to die within a month. Thanks to Chris
1914: Jackson for correcting this bug. Former versions increased
1915: mortality artificially. The bad side is that we add another loop
1916: which slows down the processing. The difference can be up to 10%
1917: lower mortality.
1918: */
1919: lli=log(out[s1][s2] - savm[s1][s2]);
1920:
1921:
1922: } else if (s2==-2) {
1923: for (j=1,survp=0. ; j<=nlstate; j++)
1924: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1925: /*survp += out[s1][j]; */
1926: lli= log(survp);
1927: }
1928:
1929: else if (s2==-4) {
1930: for (j=3,survp=0. ; j<=nlstate; j++)
1931: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1932: lli= log(survp);
1933: }
1934:
1935: else if (s2==-5) {
1936: for (j=1,survp=0. ; j<=2; j++)
1937: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1938: lli= log(survp);
1939: }
1940:
1941: else{
1942: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1943: /* 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 */
1944: }
1945: /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
1946: /*if(lli ==000.0)*/
1947: /*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); */
1948: ipmx +=1;
1949: sw += weight[i];
1950: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1951: } /* end of wave */
1952: } /* end of individual */
1953: } else if(mle==2){
1954: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1955: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1956: for(mi=1; mi<= wav[i]-1; mi++){
1957: for (ii=1;ii<=nlstate+ndeath;ii++)
1958: for (j=1;j<=nlstate+ndeath;j++){
1959: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1960: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1961: }
1962: for(d=0; d<=dh[mi][i]; d++){
1963: newm=savm;
1964: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1965: for (kk=1; kk<=cptcovage;kk++) {
1966: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1967: }
1968: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1969: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1970: savm=oldm;
1971: oldm=newm;
1972: } /* end mult */
1973:
1974: s1=s[mw[mi][i]][i];
1975: s2=s[mw[mi+1][i]][i];
1976: bbh=(double)bh[mi][i]/(double)stepm;
1977: 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 */
1978: ipmx +=1;
1979: sw += weight[i];
1980: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1981: } /* end of wave */
1982: } /* end of individual */
1983: } else if(mle==3){ /* exponential inter-extrapolation */
1984: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1985: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1986: for(mi=1; mi<= wav[i]-1; mi++){
1987: for (ii=1;ii<=nlstate+ndeath;ii++)
1988: for (j=1;j<=nlstate+ndeath;j++){
1989: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1990: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1991: }
1992: for(d=0; d<dh[mi][i]; d++){
1993: newm=savm;
1994: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1995: for (kk=1; kk<=cptcovage;kk++) {
1996: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1997: }
1998: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1999: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2000: savm=oldm;
2001: oldm=newm;
2002: } /* end mult */
2003:
2004: s1=s[mw[mi][i]][i];
2005: s2=s[mw[mi+1][i]][i];
2006: bbh=(double)bh[mi][i]/(double)stepm;
2007: 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 */
2008: ipmx +=1;
2009: sw += weight[i];
2010: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2011: } /* end of wave */
2012: } /* end of individual */
2013: }else if (mle==4){ /* ml=4 no inter-extrapolation */
2014: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2015: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2016: for(mi=1; mi<= wav[i]-1; mi++){
2017: for (ii=1;ii<=nlstate+ndeath;ii++)
2018: for (j=1;j<=nlstate+ndeath;j++){
2019: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2020: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2021: }
2022: for(d=0; d<dh[mi][i]; d++){
2023: newm=savm;
2024: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2025: for (kk=1; kk<=cptcovage;kk++) {
2026: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2027: }
2028:
2029: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2030: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2031: savm=oldm;
2032: oldm=newm;
2033: } /* end mult */
2034:
2035: s1=s[mw[mi][i]][i];
2036: s2=s[mw[mi+1][i]][i];
2037: if( s2 > nlstate){
2038: lli=log(out[s1][s2] - savm[s1][s2]);
2039: }else{
2040: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2041: }
2042: ipmx +=1;
2043: sw += weight[i];
2044: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2045: /* 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]); */
2046: } /* end of wave */
2047: } /* end of individual */
2048: }else{ /* ml=5 no inter-extrapolation no jackson =0.8a */
2049: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2050: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2051: for(mi=1; mi<= wav[i]-1; mi++){
2052: for (ii=1;ii<=nlstate+ndeath;ii++)
2053: for (j=1;j<=nlstate+ndeath;j++){
2054: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2055: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2056: }
2057: for(d=0; d<dh[mi][i]; d++){
2058: newm=savm;
2059: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2060: for (kk=1; kk<=cptcovage;kk++) {
2061: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2062: }
2063:
2064: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2065: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2066: savm=oldm;
2067: oldm=newm;
2068: } /* end mult */
2069:
2070: s1=s[mw[mi][i]][i];
2071: s2=s[mw[mi+1][i]][i];
2072: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2073: ipmx +=1;
2074: sw += weight[i];
2075: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2076: /*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]);*/
2077: } /* end of wave */
2078: } /* end of individual */
2079: } /* End of if */
2080: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2081: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2082: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2083: return -l;
2084: }
2085:
2086: /*************** log-likelihood *************/
2087: double funcone( double *x)
2088: {
2089: /* Same as likeli but slower because of a lot of printf and if */
2090: int i, ii, j, k, mi, d, kk;
2091: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
2092: double **out;
2093: double lli; /* Individual log likelihood */
2094: double llt;
2095: int s1, s2;
2096: double bbh, survp;
2097: /*extern weight */
2098: /* We are differentiating ll according to initial status */
2099: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2100: /*for(i=1;i<imx;i++)
2101: printf(" %d\n",s[4][i]);
2102: */
2103: cov[1]=1.;
2104:
2105: for(k=1; k<=nlstate; k++) ll[k]=0.;
2106:
2107: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2108: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2109: for(mi=1; mi<= wav[i]-1; mi++){
2110: for (ii=1;ii<=nlstate+ndeath;ii++)
2111: for (j=1;j<=nlstate+ndeath;j++){
2112: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2113: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2114: }
2115: for(d=0; d<dh[mi][i]; d++){
2116: newm=savm;
2117: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2118: for (kk=1; kk<=cptcovage;kk++) {
2119: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2120: }
2121: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
2122: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2123: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2124: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
2125: /* 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
2126: savm=oldm;
2127: oldm=newm;
2128: } /* end mult */
2129:
2130: s1=s[mw[mi][i]][i];
2131: s2=s[mw[mi+1][i]][i];
2132: bbh=(double)bh[mi][i]/(double)stepm;
2133: /* bias is positive if real duration
2134: * is higher than the multiple of stepm and negative otherwise.
2135: */
2136: if( s2 > nlstate && (mle <5) ){ /* Jackson */
2137: lli=log(out[s1][s2] - savm[s1][s2]);
2138: } else if (s2==-2) {
2139: for (j=1,survp=0. ; j<=nlstate; j++)
2140: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2141: lli= log(survp);
2142: }else if (mle==1){
2143: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2144: } else if(mle==2){
2145: 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 */
2146: } else if(mle==3){ /* exponential inter-extrapolation */
2147: 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 */
2148: } else if (mle==4){ /* mle=4 no inter-extrapolation */
2149: lli=log(out[s1][s2]); /* Original formula */
2150: } else{ /* mle=0 back to 1 */
2151: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2152: /*lli=log(out[s1][s2]); */ /* Original formula */
2153: } /* End of if */
2154: ipmx +=1;
2155: sw += weight[i];
2156: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2157: /*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]); */
2158: if(globpr){
2159: fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
2160: %11.6f %11.6f %11.6f ", \
2161: num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
2162: 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
2163: for(k=1,llt=0.,l=0.; k<=nlstate; k++){
2164: llt +=ll[k]*gipmx/gsw;
2165: fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
2166: }
2167: fprintf(ficresilk," %10.6f\n", -llt);
2168: }
2169: } /* end of wave */
2170: } /* end of individual */
2171: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2172: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2173: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2174: if(globpr==0){ /* First time we count the contributions and weights */
2175: gipmx=ipmx;
2176: gsw=sw;
2177: }
2178: return -l;
2179: }
2180:
2181:
2182: /*************** function likelione ***********/
2183: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
2184: {
2185: /* This routine should help understanding what is done with
2186: the selection of individuals/waves and
2187: to check the exact contribution to the likelihood.
2188: Plotting could be done.
2189: */
2190: int k;
2191:
2192: if(*globpri !=0){ /* Just counts and sums, no printings */
2193: strcpy(fileresilk,"ilk");
2194: strcat(fileresilk,fileres);
2195: if((ficresilk=fopen(fileresilk,"w"))==NULL) {
2196: printf("Problem with resultfile: %s\n", fileresilk);
2197: fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
2198: }
2199: 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");
2200: fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
2201: /* i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
2202: for(k=1; k<=nlstate; k++)
2203: fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
2204: fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
2205: }
2206:
2207: *fretone=(*funcone)(p);
2208: if(*globpri !=0){
2209: fclose(ficresilk);
2210: fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
2211: fflush(fichtm);
2212: }
2213: return;
2214: }
2215:
2216:
2217: /*********** Maximum Likelihood Estimation ***************/
2218:
2219: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
2220: {
2221: int i,j, iter=0;
2222: double **xi;
2223: double fret;
2224: double fretone; /* Only one call to likelihood */
2225: /* char filerespow[FILENAMELENGTH];*/
2226:
2227: #ifdef NLOPT
2228: int creturn;
2229: nlopt_opt opt;
2230: /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
2231: double *lb;
2232: double minf; /* the minimum objective value, upon return */
2233: double * p1; /* Shifted parameters from 0 instead of 1 */
2234: myfunc_data dinst, *d = &dinst;
2235: #endif
2236:
2237:
2238: xi=matrix(1,npar,1,npar);
2239: for (i=1;i<=npar;i++)
2240: for (j=1;j<=npar;j++)
2241: xi[i][j]=(i==j ? 1.0 : 0.0);
2242: printf("Powell\n"); fprintf(ficlog,"Powell\n");
2243: strcpy(filerespow,"pow");
2244: strcat(filerespow,fileres);
2245: if((ficrespow=fopen(filerespow,"w"))==NULL) {
2246: printf("Problem with resultfile: %s\n", filerespow);
2247: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
2248: }
2249: fprintf(ficrespow,"# Powell\n# iter -2*LL");
2250: for (i=1;i<=nlstate;i++)
2251: for(j=1;j<=nlstate+ndeath;j++)
2252: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
2253: fprintf(ficrespow,"\n");
2254: #ifdef POWELL
2255: powell(p,xi,npar,ftol,&iter,&fret,func);
2256: #endif
2257:
2258: #ifdef NLOPT
2259: #ifdef NEWUOA
2260: opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
2261: #else
2262: opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
2263: #endif
2264: lb=vector(0,npar-1);
2265: for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
2266: nlopt_set_lower_bounds(opt, lb);
2267: nlopt_set_initial_step1(opt, 0.1);
2268:
2269: p1= (p+1); /* p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
2270: d->function = func;
2271: printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
2272: nlopt_set_min_objective(opt, myfunc, d);
2273: nlopt_set_xtol_rel(opt, ftol);
2274: if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
2275: printf("nlopt failed! %d\n",creturn);
2276: }
2277: else {
2278: printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
2279: printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
2280: iter=1; /* not equal */
2281: }
2282: nlopt_destroy(opt);
2283: #endif
2284: free_matrix(xi,1,npar,1,npar);
2285: fclose(ficrespow);
2286: printf("#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2287: fprintf(ficlog,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2288: fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2289:
2290: }
2291:
2292: /**** Computes Hessian and covariance matrix ***/
2293: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
2294: {
2295: double **a,**y,*x,pd;
2296: double **hess;
2297: int i, j;
2298: int *indx;
2299:
2300: double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
2301: double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
2302: void lubksb(double **a, int npar, int *indx, double b[]) ;
2303: void ludcmp(double **a, int npar, int *indx, double *d) ;
2304: double gompertz(double p[]);
2305: hess=matrix(1,npar,1,npar);
2306:
2307: printf("\nCalculation of the hessian matrix. Wait...\n");
2308: fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
2309: for (i=1;i<=npar;i++){
2310: printf("%d",i);fflush(stdout);
2311: fprintf(ficlog,"%d",i);fflush(ficlog);
2312:
2313: hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
2314:
2315: /* printf(" %f ",p[i]);
2316: printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
2317: }
2318:
2319: for (i=1;i<=npar;i++) {
2320: for (j=1;j<=npar;j++) {
2321: if (j>i) {
2322: printf(".%d%d",i,j);fflush(stdout);
2323: fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
2324: hess[i][j]=hessij(p,delti,i,j,func,npar);
2325:
2326: hess[j][i]=hess[i][j];
2327: /*printf(" %lf ",hess[i][j]);*/
2328: }
2329: }
2330: }
2331: printf("\n");
2332: fprintf(ficlog,"\n");
2333:
2334: printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
2335: fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
2336:
2337: a=matrix(1,npar,1,npar);
2338: y=matrix(1,npar,1,npar);
2339: x=vector(1,npar);
2340: indx=ivector(1,npar);
2341: for (i=1;i<=npar;i++)
2342: for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
2343: ludcmp(a,npar,indx,&pd);
2344:
2345: for (j=1;j<=npar;j++) {
2346: for (i=1;i<=npar;i++) x[i]=0;
2347: x[j]=1;
2348: lubksb(a,npar,indx,x);
2349: for (i=1;i<=npar;i++){
2350: matcov[i][j]=x[i];
2351: }
2352: }
2353:
2354: printf("\n#Hessian matrix#\n");
2355: fprintf(ficlog,"\n#Hessian matrix#\n");
2356: for (i=1;i<=npar;i++) {
2357: for (j=1;j<=npar;j++) {
2358: printf("%.3e ",hess[i][j]);
2359: fprintf(ficlog,"%.3e ",hess[i][j]);
2360: }
2361: printf("\n");
2362: fprintf(ficlog,"\n");
2363: }
2364:
2365: /* Recompute Inverse */
2366: for (i=1;i<=npar;i++)
2367: for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
2368: ludcmp(a,npar,indx,&pd);
2369:
2370: /* printf("\n#Hessian matrix recomputed#\n");
2371:
2372: for (j=1;j<=npar;j++) {
2373: for (i=1;i<=npar;i++) x[i]=0;
2374: x[j]=1;
2375: lubksb(a,npar,indx,x);
2376: for (i=1;i<=npar;i++){
2377: y[i][j]=x[i];
2378: printf("%.3e ",y[i][j]);
2379: fprintf(ficlog,"%.3e ",y[i][j]);
2380: }
2381: printf("\n");
2382: fprintf(ficlog,"\n");
2383: }
2384: */
2385:
2386: free_matrix(a,1,npar,1,npar);
2387: free_matrix(y,1,npar,1,npar);
2388: free_vector(x,1,npar);
2389: free_ivector(indx,1,npar);
2390: free_matrix(hess,1,npar,1,npar);
2391:
2392:
2393: }
2394:
2395: /*************** hessian matrix ****************/
2396: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
2397: {
2398: int i;
2399: int l=1, lmax=20;
2400: double k1,k2;
2401: double p2[MAXPARM+1]; /* identical to x */
2402: double res;
2403: double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
2404: double fx;
2405: int k=0,kmax=10;
2406: double l1;
2407:
2408: fx=func(x);
2409: for (i=1;i<=npar;i++) p2[i]=x[i];
2410: for(l=0 ; l <=lmax; l++){ /* Enlarging the zone around the Maximum */
2411: l1=pow(10,l);
2412: delts=delt;
2413: for(k=1 ; k <kmax; k=k+1){
2414: delt = delta*(l1*k);
2415: p2[theta]=x[theta] +delt;
2416: k1=func(p2)-fx; /* Might be negative if too close to the theoretical maximum */
2417: p2[theta]=x[theta]-delt;
2418: k2=func(p2)-fx;
2419: /*res= (k1-2.0*fx+k2)/delt/delt; */
2420: res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
2421:
2422: #ifdef DEBUGHESS
2423: 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);
2424: 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);
2425: #endif
2426: /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
2427: if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
2428: k=kmax;
2429: }
2430: else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
2431: k=kmax; l=lmax*10;
2432: }
2433: else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
2434: delts=delt;
2435: }
2436: }
2437: }
2438: delti[theta]=delts;
2439: return res;
2440:
2441: }
2442:
2443: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
2444: {
2445: int i;
2446: int l=1, lmax=20;
2447: double k1,k2,k3,k4,res,fx;
2448: double p2[MAXPARM+1];
2449: int k;
2450:
2451: fx=func(x);
2452: for (k=1; k<=2; k++) {
2453: for (i=1;i<=npar;i++) p2[i]=x[i];
2454: p2[thetai]=x[thetai]+delti[thetai]/k;
2455: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2456: k1=func(p2)-fx;
2457:
2458: p2[thetai]=x[thetai]+delti[thetai]/k;
2459: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2460: k2=func(p2)-fx;
2461:
2462: p2[thetai]=x[thetai]-delti[thetai]/k;
2463: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2464: k3=func(p2)-fx;
2465:
2466: p2[thetai]=x[thetai]-delti[thetai]/k;
2467: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2468: k4=func(p2)-fx;
2469: res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
2470: #ifdef DEBUG
2471: 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);
2472: 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);
2473: #endif
2474: }
2475: return res;
2476: }
2477:
2478: /************** Inverse of matrix **************/
2479: void ludcmp(double **a, int n, int *indx, double *d)
2480: {
2481: int i,imax,j,k;
2482: double big,dum,sum,temp;
2483: double *vv;
2484:
2485: vv=vector(1,n);
2486: *d=1.0;
2487: for (i=1;i<=n;i++) {
2488: big=0.0;
2489: for (j=1;j<=n;j++)
2490: if ((temp=fabs(a[i][j])) > big) big=temp;
2491: if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
2492: vv[i]=1.0/big;
2493: }
2494: for (j=1;j<=n;j++) {
2495: for (i=1;i<j;i++) {
2496: sum=a[i][j];
2497: for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
2498: a[i][j]=sum;
2499: }
2500: big=0.0;
2501: for (i=j;i<=n;i++) {
2502: sum=a[i][j];
2503: for (k=1;k<j;k++)
2504: sum -= a[i][k]*a[k][j];
2505: a[i][j]=sum;
2506: if ( (dum=vv[i]*fabs(sum)) >= big) {
2507: big=dum;
2508: imax=i;
2509: }
2510: }
2511: if (j != imax) {
2512: for (k=1;k<=n;k++) {
2513: dum=a[imax][k];
2514: a[imax][k]=a[j][k];
2515: a[j][k]=dum;
2516: }
2517: *d = -(*d);
2518: vv[imax]=vv[j];
2519: }
2520: indx[j]=imax;
2521: if (a[j][j] == 0.0) a[j][j]=TINY;
2522: if (j != n) {
2523: dum=1.0/(a[j][j]);
2524: for (i=j+1;i<=n;i++) a[i][j] *= dum;
2525: }
2526: }
2527: free_vector(vv,1,n); /* Doesn't work */
2528: ;
2529: }
2530:
2531: void lubksb(double **a, int n, int *indx, double b[])
2532: {
2533: int i,ii=0,ip,j;
2534: double sum;
2535:
2536: for (i=1;i<=n;i++) {
2537: ip=indx[i];
2538: sum=b[ip];
2539: b[ip]=b[i];
2540: if (ii)
2541: for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
2542: else if (sum) ii=i;
2543: b[i]=sum;
2544: }
2545: for (i=n;i>=1;i--) {
2546: sum=b[i];
2547: for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
2548: b[i]=sum/a[i][i];
2549: }
2550: }
2551:
2552: void pstamp(FILE *fichier)
2553: {
2554: fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
2555: }
2556:
2557: /************ Frequencies ********************/
2558: 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[])
2559: { /* Some frequencies */
2560:
2561: int i, m, jk, j1, bool, z1,j;
2562: int first;
2563: double ***freq; /* Frequencies */
2564: double *pp, **prop;
2565: double pos,posprop, k2, dateintsum=0,k2cpt=0;
2566: char fileresp[FILENAMELENGTH];
2567:
2568: pp=vector(1,nlstate);
2569: prop=matrix(1,nlstate,iagemin,iagemax+3);
2570: strcpy(fileresp,"p");
2571: strcat(fileresp,fileres);
2572: if((ficresp=fopen(fileresp,"w"))==NULL) {
2573: printf("Problem with prevalence resultfile: %s\n", fileresp);
2574: fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
2575: exit(0);
2576: }
2577: freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
2578: j1=0;
2579:
2580: j=cptcoveff;
2581: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2582:
2583: first=1;
2584:
2585: /* for(k1=1; k1<=j ; k1++){ */ /* Loop on covariates */
2586: /* for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
2587: /* j1++; */
2588: for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
2589: /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
2590: scanf("%d", i);*/
2591: for (i=-5; i<=nlstate+ndeath; i++)
2592: for (jk=-5; jk<=nlstate+ndeath; jk++)
2593: for(m=iagemin; m <= iagemax+3; m++)
2594: freq[i][jk][m]=0;
2595:
2596: for (i=1; i<=nlstate; i++)
2597: for(m=iagemin; m <= iagemax+3; m++)
2598: prop[i][m]=0;
2599:
2600: dateintsum=0;
2601: k2cpt=0;
2602: for (i=1; i<=imx; i++) {
2603: bool=1;
2604: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
2605: for (z1=1; z1<=cptcoveff; z1++)
2606: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
2607: /* Tests if the value of each of the covariates of i is equal to filter j1 */
2608: bool=0;
2609: /* 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",
2610: bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
2611: j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
2612: /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
2613: }
2614: }
2615:
2616: if (bool==1){
2617: for(m=firstpass; m<=lastpass; m++){
2618: k2=anint[m][i]+(mint[m][i]/12.);
2619: /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
2620: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2621: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2622: if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
2623: if (m<lastpass) {
2624: freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
2625: freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
2626: }
2627:
2628: if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
2629: dateintsum=dateintsum+k2;
2630: k2cpt++;
2631: }
2632: /*}*/
2633: }
2634: }
2635: } /* end i */
2636:
2637: /* fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
2638: pstamp(ficresp);
2639: if (cptcovn>0) {
2640: fprintf(ficresp, "\n#********** Variable ");
2641: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2642: fprintf(ficresp, "**********\n#");
2643: fprintf(ficlog, "\n#********** Variable ");
2644: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2645: fprintf(ficlog, "**********\n#");
2646: }
2647: for(i=1; i<=nlstate;i++)
2648: fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
2649: fprintf(ficresp, "\n");
2650:
2651: for(i=iagemin; i <= iagemax+3; i++){
2652: if(i==iagemax+3){
2653: fprintf(ficlog,"Total");
2654: }else{
2655: if(first==1){
2656: first=0;
2657: printf("See log file for details...\n");
2658: }
2659: fprintf(ficlog,"Age %d", i);
2660: }
2661: for(jk=1; jk <=nlstate ; jk++){
2662: for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
2663: pp[jk] += freq[jk][m][i];
2664: }
2665: for(jk=1; jk <=nlstate ; jk++){
2666: for(m=-1, pos=0; m <=0 ; m++)
2667: pos += freq[jk][m][i];
2668: if(pp[jk]>=1.e-10){
2669: if(first==1){
2670: printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
2671: }
2672: fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
2673: }else{
2674: if(first==1)
2675: printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2676: fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2677: }
2678: }
2679:
2680: for(jk=1; jk <=nlstate ; jk++){
2681: for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
2682: pp[jk] += freq[jk][m][i];
2683: }
2684: for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
2685: pos += pp[jk];
2686: posprop += prop[jk][i];
2687: }
2688: for(jk=1; jk <=nlstate ; jk++){
2689: if(pos>=1.e-5){
2690: if(first==1)
2691: printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2692: fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2693: }else{
2694: if(first==1)
2695: printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2696: fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2697: }
2698: if( i <= iagemax){
2699: if(pos>=1.e-5){
2700: fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
2701: /*probs[i][jk][j1]= pp[jk]/pos;*/
2702: /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
2703: }
2704: else
2705: fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
2706: }
2707: }
2708:
2709: for(jk=-1; jk <=nlstate+ndeath; jk++)
2710: for(m=-1; m <=nlstate+ndeath; m++)
2711: if(freq[jk][m][i] !=0 ) {
2712: if(first==1)
2713: printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
2714: fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
2715: }
2716: if(i <= iagemax)
2717: fprintf(ficresp,"\n");
2718: if(first==1)
2719: printf("Others in log...\n");
2720: fprintf(ficlog,"\n");
2721: }
2722: /*}*/
2723: }
2724: dateintmean=dateintsum/k2cpt;
2725:
2726: fclose(ficresp);
2727: free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
2728: free_vector(pp,1,nlstate);
2729: free_matrix(prop,1,nlstate,iagemin, iagemax+3);
2730: /* End of Freq */
2731: }
2732:
2733: /************ Prevalence ********************/
2734: 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)
2735: {
2736: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
2737: in each health status at the date of interview (if between dateprev1 and dateprev2).
2738: We still use firstpass and lastpass as another selection.
2739: */
2740:
2741: int i, m, jk, j1, bool, z1,j;
2742:
2743: double **prop;
2744: double posprop;
2745: double y2; /* in fractional years */
2746: int iagemin, iagemax;
2747: int first; /** to stop verbosity which is redirected to log file */
2748:
2749: iagemin= (int) agemin;
2750: iagemax= (int) agemax;
2751: /*pp=vector(1,nlstate);*/
2752: prop=matrix(1,nlstate,iagemin,iagemax+3);
2753: /* freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
2754: j1=0;
2755:
2756: /*j=cptcoveff;*/
2757: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2758:
2759: first=1;
2760: for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
2761: /*for(i1=1; i1<=ncodemax[k1];i1++){
2762: j1++;*/
2763:
2764: for (i=1; i<=nlstate; i++)
2765: for(m=iagemin; m <= iagemax+3; m++)
2766: prop[i][m]=0.0;
2767:
2768: for (i=1; i<=imx; i++) { /* Each individual */
2769: bool=1;
2770: if (cptcovn>0) {
2771: for (z1=1; z1<=cptcoveff; z1++)
2772: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
2773: bool=0;
2774: }
2775: if (bool==1) {
2776: for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
2777: y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
2778: if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
2779: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2780: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2781: 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);
2782: if (s[m][i]>0 && s[m][i]<=nlstate) {
2783: /*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]]);*/
2784: prop[s[m][i]][(int)agev[m][i]] += weight[i];
2785: prop[s[m][i]][iagemax+3] += weight[i];
2786: }
2787: }
2788: } /* end selection of waves */
2789: }
2790: }
2791: for(i=iagemin; i <= iagemax+3; i++){
2792: for(jk=1,posprop=0; jk <=nlstate ; jk++) {
2793: posprop += prop[jk][i];
2794: }
2795:
2796: for(jk=1; jk <=nlstate ; jk++){
2797: if( i <= iagemax){
2798: if(posprop>=1.e-5){
2799: probs[i][jk][j1]= prop[jk][i]/posprop;
2800: } else{
2801: if(first==1){
2802: first=0;
2803: 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]);
2804: }
2805: }
2806: }
2807: }/* end jk */
2808: }/* end i */
2809: /*} *//* end i1 */
2810: } /* end j1 */
2811:
2812: /* free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
2813: /*free_vector(pp,1,nlstate);*/
2814: free_matrix(prop,1,nlstate, iagemin,iagemax+3);
2815: } /* End of prevalence */
2816:
2817: /************* Waves Concatenation ***************/
2818:
2819: 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)
2820: {
2821: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
2822: Death is a valid wave (if date is known).
2823: mw[mi][i] is the mi (mi=1 to wav[i]) effective wave of individual i
2824: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
2825: and mw[mi+1][i]. dh depends on stepm.
2826: */
2827:
2828: int i, mi, m;
2829: /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
2830: double sum=0., jmean=0.;*/
2831: int first;
2832: int j, k=0,jk, ju, jl;
2833: double sum=0.;
2834: first=0;
2835: jmin=100000;
2836: jmax=-1;
2837: jmean=0.;
2838: for(i=1; i<=imx; i++){
2839: mi=0;
2840: m=firstpass;
2841: while(s[m][i] <= nlstate){
2842: if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
2843: mw[++mi][i]=m;
2844: if(m >=lastpass)
2845: break;
2846: else
2847: m++;
2848: }/* end while */
2849: if (s[m][i] > nlstate){
2850: mi++; /* Death is another wave */
2851: /* if(mi==0) never been interviewed correctly before death */
2852: /* Only death is a correct wave */
2853: mw[mi][i]=m;
2854: }
2855:
2856: wav[i]=mi;
2857: if(mi==0){
2858: nbwarn++;
2859: if(first==0){
2860: printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
2861: first=1;
2862: }
2863: if(first==1){
2864: fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
2865: }
2866: } /* end mi==0 */
2867: } /* End individuals */
2868:
2869: for(i=1; i<=imx; i++){
2870: for(mi=1; mi<wav[i];mi++){
2871: if (stepm <=0)
2872: dh[mi][i]=1;
2873: else{
2874: if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
2875: if (agedc[i] < 2*AGESUP) {
2876: j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
2877: if(j==0) j=1; /* Survives at least one month after exam */
2878: else if(j<0){
2879: nberr++;
2880: 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]);
2881: j=1; /* Temporary Dangerous patch */
2882: 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);
2883: 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]);
2884: 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);
2885: }
2886: k=k+1;
2887: if (j >= jmax){
2888: jmax=j;
2889: ijmax=i;
2890: }
2891: if (j <= jmin){
2892: jmin=j;
2893: ijmin=i;
2894: }
2895: sum=sum+j;
2896: /*if (j<0) printf("j=%d num=%d \n",j,i);*/
2897: /* printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
2898: }
2899: }
2900: else{
2901: j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
2902: /* 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]); */
2903:
2904: k=k+1;
2905: if (j >= jmax) {
2906: jmax=j;
2907: ijmax=i;
2908: }
2909: else if (j <= jmin){
2910: jmin=j;
2911: ijmin=i;
2912: }
2913: /* if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
2914: /*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]);*/
2915: if(j<0){
2916: nberr++;
2917: 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]);
2918: 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]);
2919: }
2920: sum=sum+j;
2921: }
2922: jk= j/stepm;
2923: jl= j -jk*stepm;
2924: ju= j -(jk+1)*stepm;
2925: if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
2926: if(jl==0){
2927: dh[mi][i]=jk;
2928: bh[mi][i]=0;
2929: }else{ /* We want a negative bias in order to only have interpolation ie
2930: * to avoid the price of an extra matrix product in likelihood */
2931: dh[mi][i]=jk+1;
2932: bh[mi][i]=ju;
2933: }
2934: }else{
2935: if(jl <= -ju){
2936: dh[mi][i]=jk;
2937: bh[mi][i]=jl; /* bias is positive if real duration
2938: * is higher than the multiple of stepm and negative otherwise.
2939: */
2940: }
2941: else{
2942: dh[mi][i]=jk+1;
2943: bh[mi][i]=ju;
2944: }
2945: if(dh[mi][i]==0){
2946: dh[mi][i]=1; /* At least one step */
2947: bh[mi][i]=ju; /* At least one step */
2948: /* 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);*/
2949: }
2950: } /* end if mle */
2951: }
2952: } /* end wave */
2953: }
2954: jmean=sum/k;
2955: 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);
2956: 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);
2957: }
2958:
2959: /*********** Tricode ****************************/
2960: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
2961: {
2962: /**< Uses cptcovn+2*cptcovprod as the number of covariates */
2963: /* Tvar[i]=atoi(stre); find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1
2964: * Boring subroutine which should only output nbcode[Tvar[j]][k]
2965: * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
2966: * nbcode[Tvar[j]][1]=
2967: */
2968:
2969: int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
2970: int modmaxcovj=0; /* Modality max of covariates j */
2971: int cptcode=0; /* Modality max of covariates j */
2972: int modmincovj=0; /* Modality min of covariates j */
2973:
2974:
2975: cptcoveff=0;
2976:
2977: for (k=-1; k < maxncov; k++) Ndum[k]=0;
2978: for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
2979:
2980: /* Loop on covariates without age and products */
2981: for (j=1; j<=(cptcovs); j++) { /* model V1 + V2*age+ V3 + V3*V4 : V1 + V3 = 2 only */
2982: for (i=1; i<=imx; i++) { /* Lopp on individuals: reads the data file to get the maximum value of the
2983: modality of this covariate Vj*/
2984: ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
2985: * If product of Vn*Vm, still boolean *:
2986: * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
2987: * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0 */
2988: /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
2989: modality of the nth covariate of individual i. */
2990: if (ij > modmaxcovj)
2991: modmaxcovj=ij;
2992: else if (ij < modmincovj)
2993: modmincovj=ij;
2994: if ((ij < -1) && (ij > NCOVMAX)){
2995: printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
2996: exit(1);
2997: }else
2998: Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
2999: /* If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
3000: /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
3001: /* getting the maximum value of the modality of the covariate
3002: (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
3003: female is 1, then modmaxcovj=1.*/
3004: }
3005: printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
3006: cptcode=modmaxcovj;
3007: /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
3008: /*for (i=0; i<=cptcode; i++) {*/
3009: for (i=modmincovj; i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
3010: printf("Frequencies of covariates %d V%d %d\n", j, Tvar[j], Ndum[i]);
3011: if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
3012: ncodemax[j]++; /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
3013: }
3014: /* In fact ncodemax[j]=2 (dichotom. variables only) but it could be more for
3015: historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
3016: } /* Ndum[-1] number of undefined modalities */
3017:
3018: /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
3019: /* For covariate j, modalities could be 1, 2, 3, 4. If Ndum[2]=0 ncodemax[j] is not 4 but 3 */
3020: /* If Ndum[3}= 635; Ndum[4]=0; Ndum[5]=0; Ndum[6]=27; Ndum[7]=125;
3021: modmincovj=3; modmaxcovj = 7;
3022: There are only 3 modalities non empty (or 2 if 27 is too few) : ncodemax[j]=3;
3023: which will be coded 0, 1, 2 which in binary on 3-1 digits are 0=00 1=01, 2=10; defining two dummy
3024: variables V1_1 and V1_2.
3025: nbcode[Tvar[j]][ij]=k;
3026: nbcode[Tvar[j]][1]=0;
3027: nbcode[Tvar[j]][2]=1;
3028: nbcode[Tvar[j]][3]=2;
3029: */
3030: ij=1; /* ij is similar to i but can jumps over null modalities */
3031: for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
3032: for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
3033: /*recode from 0 */
3034: if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
3035: nbcode[Tvar[j]][ij]=k; /* stores the modality in an array nbcode.
3036: k is a modality. If we have model=V1+V1*sex
3037: then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
3038: ij++;
3039: }
3040: if (ij > ncodemax[j]) break;
3041: } /* end of loop on */
3042: } /* end of loop on modality */
3043: } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/
3044:
3045: for (k=-1; k< maxncov; k++) Ndum[k]=0;
3046:
3047: for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */
3048: /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
3049: ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
3050: Ndum[ij]++;
3051: }
3052:
3053: ij=1;
3054: for (i=0; i<= maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
3055: /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
3056: if((Ndum[i]!=0) && (i<=ncovcol)){
3057: /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
3058: Tvaraff[ij]=i; /*For printing (unclear) */
3059: ij++;
3060: }else
3061: Tvaraff[ij]=0;
3062: }
3063: ij--;
3064: cptcoveff=ij; /*Number of total covariates*/
3065:
3066: }
3067:
3068:
3069: /*********** Health Expectancies ****************/
3070:
3071: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
3072:
3073: {
3074: /* Health expectancies, no variances */
3075: int i, j, nhstepm, hstepm, h, nstepm;
3076: int nhstepma, nstepma; /* Decreasing with age */
3077: double age, agelim, hf;
3078: double ***p3mat;
3079: double eip;
3080:
3081: pstamp(ficreseij);
3082: fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
3083: fprintf(ficreseij,"# Age");
3084: for(i=1; i<=nlstate;i++){
3085: for(j=1; j<=nlstate;j++){
3086: fprintf(ficreseij," e%1d%1d ",i,j);
3087: }
3088: fprintf(ficreseij," e%1d. ",i);
3089: }
3090: fprintf(ficreseij,"\n");
3091:
3092:
3093: if(estepm < stepm){
3094: printf ("Problem %d lower than %d\n",estepm, stepm);
3095: }
3096: else hstepm=estepm;
3097: /* We compute the life expectancy from trapezoids spaced every estepm months
3098: * This is mainly to measure the difference between two models: for example
3099: * if stepm=24 months pijx are given only every 2 years and by summing them
3100: * we are calculating an estimate of the Life Expectancy assuming a linear
3101: * progression in between and thus overestimating or underestimating according
3102: * to the curvature of the survival function. If, for the same date, we
3103: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3104: * to compare the new estimate of Life expectancy with the same linear
3105: * hypothesis. A more precise result, taking into account a more precise
3106: * curvature will be obtained if estepm is as small as stepm. */
3107:
3108: /* For example we decided to compute the life expectancy with the smallest unit */
3109: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3110: nhstepm is the number of hstepm from age to agelim
3111: nstepm is the number of stepm from age to agelin.
3112: Look at hpijx to understand the reason of that which relies in memory size
3113: and note for a fixed period like estepm months */
3114: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3115: survival function given by stepm (the optimization length). Unfortunately it
3116: means that if the survival funtion is printed only each two years of age and if
3117: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3118: results. So we changed our mind and took the option of the best precision.
3119: */
3120: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3121:
3122: agelim=AGESUP;
3123: /* If stepm=6 months */
3124: /* Computed by stepm unit matrices, product of hstepm matrices, stored
3125: in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
3126:
3127: /* nhstepm age range expressed in number of stepm */
3128: nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3129: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3130: /* if (stepm >= YEARM) hstepm=1;*/
3131: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3132: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3133:
3134: for (age=bage; age<=fage; age ++){
3135: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3136: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3137: /* if (stepm >= YEARM) hstepm=1;*/
3138: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3139:
3140: /* If stepm=6 months */
3141: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3142: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3143:
3144: hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3145:
3146: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3147:
3148: printf("%d|",(int)age);fflush(stdout);
3149: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3150:
3151: /* Computing expectancies */
3152: for(i=1; i<=nlstate;i++)
3153: for(j=1; j<=nlstate;j++)
3154: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3155: eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
3156:
3157: /* 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]);*/
3158:
3159: }
3160:
3161: fprintf(ficreseij,"%3.0f",age );
3162: for(i=1; i<=nlstate;i++){
3163: eip=0;
3164: for(j=1; j<=nlstate;j++){
3165: eip +=eij[i][j][(int)age];
3166: fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
3167: }
3168: fprintf(ficreseij,"%9.4f", eip );
3169: }
3170: fprintf(ficreseij,"\n");
3171:
3172: }
3173: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3174: printf("\n");
3175: fprintf(ficlog,"\n");
3176:
3177: }
3178:
3179: 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[] )
3180:
3181: {
3182: /* Covariances of health expectancies eij and of total life expectancies according
3183: to initial status i, ei. .
3184: */
3185: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
3186: int nhstepma, nstepma; /* Decreasing with age */
3187: double age, agelim, hf;
3188: double ***p3matp, ***p3matm, ***varhe;
3189: double **dnewm,**doldm;
3190: double *xp, *xm;
3191: double **gp, **gm;
3192: double ***gradg, ***trgradg;
3193: int theta;
3194:
3195: double eip, vip;
3196:
3197: varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
3198: xp=vector(1,npar);
3199: xm=vector(1,npar);
3200: dnewm=matrix(1,nlstate*nlstate,1,npar);
3201: doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
3202:
3203: pstamp(ficresstdeij);
3204: fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
3205: fprintf(ficresstdeij,"# Age");
3206: for(i=1; i<=nlstate;i++){
3207: for(j=1; j<=nlstate;j++)
3208: fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
3209: fprintf(ficresstdeij," e%1d. ",i);
3210: }
3211: fprintf(ficresstdeij,"\n");
3212:
3213: pstamp(ficrescveij);
3214: fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
3215: fprintf(ficrescveij,"# Age");
3216: for(i=1; i<=nlstate;i++)
3217: for(j=1; j<=nlstate;j++){
3218: cptj= (j-1)*nlstate+i;
3219: for(i2=1; i2<=nlstate;i2++)
3220: for(j2=1; j2<=nlstate;j2++){
3221: cptj2= (j2-1)*nlstate+i2;
3222: if(cptj2 <= cptj)
3223: fprintf(ficrescveij," %1d%1d,%1d%1d",i,j,i2,j2);
3224: }
3225: }
3226: fprintf(ficrescveij,"\n");
3227:
3228: if(estepm < stepm){
3229: printf ("Problem %d lower than %d\n",estepm, stepm);
3230: }
3231: else hstepm=estepm;
3232: /* We compute the life expectancy from trapezoids spaced every estepm months
3233: * This is mainly to measure the difference between two models: for example
3234: * if stepm=24 months pijx are given only every 2 years and by summing them
3235: * we are calculating an estimate of the Life Expectancy assuming a linear
3236: * progression in between and thus overestimating or underestimating according
3237: * to the curvature of the survival function. If, for the same date, we
3238: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3239: * to compare the new estimate of Life expectancy with the same linear
3240: * hypothesis. A more precise result, taking into account a more precise
3241: * curvature will be obtained if estepm is as small as stepm. */
3242:
3243: /* For example we decided to compute the life expectancy with the smallest unit */
3244: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3245: nhstepm is the number of hstepm from age to agelim
3246: nstepm is the number of stepm from age to agelin.
3247: Look at hpijx to understand the reason of that which relies in memory size
3248: and note for a fixed period like estepm months */
3249: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3250: survival function given by stepm (the optimization length). Unfortunately it
3251: means that if the survival funtion is printed only each two years of age and if
3252: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3253: results. So we changed our mind and took the option of the best precision.
3254: */
3255: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3256:
3257: /* If stepm=6 months */
3258: /* nhstepm age range expressed in number of stepm */
3259: agelim=AGESUP;
3260: nstepm=(int) rint((agelim-bage)*YEARM/stepm);
3261: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3262: /* if (stepm >= YEARM) hstepm=1;*/
3263: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3264:
3265: p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3266: p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3267: gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
3268: trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
3269: gp=matrix(0,nhstepm,1,nlstate*nlstate);
3270: gm=matrix(0,nhstepm,1,nlstate*nlstate);
3271:
3272: for (age=bage; age<=fage; age ++){
3273: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3274: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3275: /* if (stepm >= YEARM) hstepm=1;*/
3276: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3277:
3278: /* If stepm=6 months */
3279: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3280: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3281:
3282: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3283:
3284: /* Computing Variances of health expectancies */
3285: /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
3286: decrease memory allocation */
3287: for(theta=1; theta <=npar; theta++){
3288: for(i=1; i<=npar; i++){
3289: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3290: xm[i] = x[i] - (i==theta ?delti[theta]:0);
3291: }
3292: hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);
3293: hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);
3294:
3295: for(j=1; j<= nlstate; j++){
3296: for(i=1; i<=nlstate; i++){
3297: for(h=0; h<=nhstepm-1; h++){
3298: gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
3299: gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
3300: }
3301: }
3302: }
3303:
3304: for(ij=1; ij<= nlstate*nlstate; ij++)
3305: for(h=0; h<=nhstepm-1; h++){
3306: gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
3307: }
3308: }/* End theta */
3309:
3310:
3311: for(h=0; h<=nhstepm-1; h++)
3312: for(j=1; j<=nlstate*nlstate;j++)
3313: for(theta=1; theta <=npar; theta++)
3314: trgradg[h][j][theta]=gradg[h][theta][j];
3315:
3316:
3317: for(ij=1;ij<=nlstate*nlstate;ij++)
3318: for(ji=1;ji<=nlstate*nlstate;ji++)
3319: varhe[ij][ji][(int)age] =0.;
3320:
3321: printf("%d|",(int)age);fflush(stdout);
3322: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3323: for(h=0;h<=nhstepm-1;h++){
3324: for(k=0;k<=nhstepm-1;k++){
3325: matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
3326: matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
3327: for(ij=1;ij<=nlstate*nlstate;ij++)
3328: for(ji=1;ji<=nlstate*nlstate;ji++)
3329: varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
3330: }
3331: }
3332:
3333: /* Computing expectancies */
3334: hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3335: for(i=1; i<=nlstate;i++)
3336: for(j=1; j<=nlstate;j++)
3337: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3338: eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
3339:
3340: /* 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]);*/
3341:
3342: }
3343:
3344: fprintf(ficresstdeij,"%3.0f",age );
3345: for(i=1; i<=nlstate;i++){
3346: eip=0.;
3347: vip=0.;
3348: for(j=1; j<=nlstate;j++){
3349: eip += eij[i][j][(int)age];
3350: for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
3351: vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
3352: fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
3353: }
3354: fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
3355: }
3356: fprintf(ficresstdeij,"\n");
3357:
3358: fprintf(ficrescveij,"%3.0f",age );
3359: for(i=1; i<=nlstate;i++)
3360: for(j=1; j<=nlstate;j++){
3361: cptj= (j-1)*nlstate+i;
3362: for(i2=1; i2<=nlstate;i2++)
3363: for(j2=1; j2<=nlstate;j2++){
3364: cptj2= (j2-1)*nlstate+i2;
3365: if(cptj2 <= cptj)
3366: fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
3367: }
3368: }
3369: fprintf(ficrescveij,"\n");
3370:
3371: }
3372: free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
3373: free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
3374: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
3375: free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
3376: free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3377: free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3378: printf("\n");
3379: fprintf(ficlog,"\n");
3380:
3381: free_vector(xm,1,npar);
3382: free_vector(xp,1,npar);
3383: free_matrix(dnewm,1,nlstate*nlstate,1,npar);
3384: free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
3385: free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
3386: }
3387:
3388: /************ Variance ******************/
3389: 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[])
3390: {
3391: /* Variance of health expectancies */
3392: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
3393: /* double **newm;*/
3394: /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
3395:
3396: int movingaverage();
3397: double **dnewm,**doldm;
3398: double **dnewmp,**doldmp;
3399: int i, j, nhstepm, hstepm, h, nstepm ;
3400: int k;
3401: double *xp;
3402: double **gp, **gm; /* for var eij */
3403: double ***gradg, ***trgradg; /*for var eij */
3404: double **gradgp, **trgradgp; /* for var p point j */
3405: double *gpp, *gmp; /* for var p point j */
3406: double **varppt; /* for var p point j nlstate to nlstate+ndeath */
3407: double ***p3mat;
3408: double age,agelim, hf;
3409: double ***mobaverage;
3410: int theta;
3411: char digit[4];
3412: char digitp[25];
3413:
3414: char fileresprobmorprev[FILENAMELENGTH];
3415:
3416: if(popbased==1){
3417: if(mobilav!=0)
3418: strcpy(digitp,"-populbased-mobilav-");
3419: else strcpy(digitp,"-populbased-nomobil-");
3420: }
3421: else
3422: strcpy(digitp,"-stablbased-");
3423:
3424: if (mobilav!=0) {
3425: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3426: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
3427: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
3428: printf(" Error in movingaverage mobilav=%d\n",mobilav);
3429: }
3430: }
3431:
3432: strcpy(fileresprobmorprev,"prmorprev");
3433: sprintf(digit,"%-d",ij);
3434: /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
3435: strcat(fileresprobmorprev,digit); /* Tvar to be done */
3436: strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
3437: strcat(fileresprobmorprev,fileres);
3438: if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
3439: printf("Problem with resultfile: %s\n", fileresprobmorprev);
3440: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
3441: }
3442: printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3443:
3444: fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3445: pstamp(ficresprobmorprev);
3446: 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);
3447: fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
3448: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3449: fprintf(ficresprobmorprev," p.%-d SE",j);
3450: for(i=1; i<=nlstate;i++)
3451: fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
3452: }
3453: fprintf(ficresprobmorprev,"\n");
3454: fprintf(ficgp,"\n# Routine varevsij");
3455: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
3456: 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");
3457: fprintf(fichtm,"\n<br>%s <br>\n",digitp);
3458: /* } */
3459: varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3460: pstamp(ficresvij);
3461: fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n# (weighted average of eij where weights are ");
3462: if(popbased==1)
3463: 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);
3464: else
3465: fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
3466: fprintf(ficresvij,"# Age");
3467: for(i=1; i<=nlstate;i++)
3468: for(j=1; j<=nlstate;j++)
3469: fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
3470: fprintf(ficresvij,"\n");
3471:
3472: xp=vector(1,npar);
3473: dnewm=matrix(1,nlstate,1,npar);
3474: doldm=matrix(1,nlstate,1,nlstate);
3475: dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
3476: doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3477:
3478: gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
3479: gpp=vector(nlstate+1,nlstate+ndeath);
3480: gmp=vector(nlstate+1,nlstate+ndeath);
3481: trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
3482:
3483: if(estepm < stepm){
3484: printf ("Problem %d lower than %d\n",estepm, stepm);
3485: }
3486: else hstepm=estepm;
3487: /* For example we decided to compute the life expectancy with the smallest unit */
3488: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3489: nhstepm is the number of hstepm from age to agelim
3490: nstepm is the number of stepm from age to agelin.
3491: Look at function hpijx to understand why (it is linked to memory size questions) */
3492: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3493: survival function given by stepm (the optimization length). Unfortunately it
3494: means that if the survival funtion is printed every two years of age and if
3495: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3496: results. So we changed our mind and took the option of the best precision.
3497: */
3498: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3499: agelim = AGESUP;
3500: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3501: nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3502: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3503: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3504: gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
3505: gp=matrix(0,nhstepm,1,nlstate);
3506: gm=matrix(0,nhstepm,1,nlstate);
3507:
3508:
3509: for(theta=1; theta <=npar; theta++){
3510: for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
3511: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3512: }
3513: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3514: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3515:
3516: if (popbased==1) {
3517: if(mobilav ==0){
3518: for(i=1; i<=nlstate;i++)
3519: prlim[i][i]=probs[(int)age][i][ij];
3520: }else{ /* mobilav */
3521: for(i=1; i<=nlstate;i++)
3522: prlim[i][i]=mobaverage[(int)age][i][ij];
3523: }
3524: }
3525:
3526: for(j=1; j<= nlstate; j++){
3527: for(h=0; h<=nhstepm; h++){
3528: for(i=1, gp[h][j]=0.;i<=nlstate;i++)
3529: gp[h][j] += prlim[i][i]*p3mat[i][j][h];
3530: }
3531: }
3532: /* This for computing probability of death (h=1 means
3533: computed over hstepm matrices product = hstepm*stepm months)
3534: as a weighted average of prlim.
3535: */
3536: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3537: for(i=1,gpp[j]=0.; i<= nlstate; i++)
3538: gpp[j] += prlim[i][i]*p3mat[i][j][1];
3539: }
3540: /* end probability of death */
3541:
3542: for(i=1; i<=npar; i++) /* Computes gradient x - delta */
3543: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3544: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3545: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3546:
3547: if (popbased==1) {
3548: if(mobilav ==0){
3549: for(i=1; i<=nlstate;i++)
3550: prlim[i][i]=probs[(int)age][i][ij];
3551: }else{ /* mobilav */
3552: for(i=1; i<=nlstate;i++)
3553: prlim[i][i]=mobaverage[(int)age][i][ij];
3554: }
3555: }
3556:
3557: for(j=1; j<= nlstate; j++){ /* Sum of wi * eij = e.j */
3558: for(h=0; h<=nhstepm; h++){
3559: for(i=1, gm[h][j]=0.;i<=nlstate;i++)
3560: gm[h][j] += prlim[i][i]*p3mat[i][j][h];
3561: }
3562: }
3563: /* This for computing probability of death (h=1 means
3564: computed over hstepm matrices product = hstepm*stepm months)
3565: as a weighted average of prlim.
3566: */
3567: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3568: for(i=1,gmp[j]=0.; i<= nlstate; i++)
3569: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3570: }
3571: /* end probability of death */
3572:
3573: for(j=1; j<= nlstate; j++) /* vareij */
3574: for(h=0; h<=nhstepm; h++){
3575: gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
3576: }
3577:
3578: for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
3579: gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
3580: }
3581:
3582: } /* End theta */
3583:
3584: trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
3585:
3586: for(h=0; h<=nhstepm; h++) /* veij */
3587: for(j=1; j<=nlstate;j++)
3588: for(theta=1; theta <=npar; theta++)
3589: trgradg[h][j][theta]=gradg[h][theta][j];
3590:
3591: for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
3592: for(theta=1; theta <=npar; theta++)
3593: trgradgp[j][theta]=gradgp[theta][j];
3594:
3595:
3596: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3597: for(i=1;i<=nlstate;i++)
3598: for(j=1;j<=nlstate;j++)
3599: vareij[i][j][(int)age] =0.;
3600:
3601: for(h=0;h<=nhstepm;h++){
3602: for(k=0;k<=nhstepm;k++){
3603: matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
3604: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
3605: for(i=1;i<=nlstate;i++)
3606: for(j=1;j<=nlstate;j++)
3607: vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
3608: }
3609: }
3610:
3611: /* pptj */
3612: matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
3613: matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
3614: for(j=nlstate+1;j<=nlstate+ndeath;j++)
3615: for(i=nlstate+1;i<=nlstate+ndeath;i++)
3616: varppt[j][i]=doldmp[j][i];
3617: /* end ppptj */
3618: /* x centered again */
3619: hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);
3620: prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
3621:
3622: if (popbased==1) {
3623: if(mobilav ==0){
3624: for(i=1; i<=nlstate;i++)
3625: prlim[i][i]=probs[(int)age][i][ij];
3626: }else{ /* mobilav */
3627: for(i=1; i<=nlstate;i++)
3628: prlim[i][i]=mobaverage[(int)age][i][ij];
3629: }
3630: }
3631:
3632: /* This for computing probability of death (h=1 means
3633: computed over hstepm (estepm) matrices product = hstepm*stepm months)
3634: as a weighted average of prlim.
3635: */
3636: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3637: for(i=1,gmp[j]=0.;i<= nlstate; i++)
3638: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3639: }
3640: /* end probability of death */
3641:
3642: fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
3643: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3644: fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
3645: for(i=1; i<=nlstate;i++){
3646: fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
3647: }
3648: }
3649: fprintf(ficresprobmorprev,"\n");
3650:
3651: fprintf(ficresvij,"%.0f ",age );
3652: for(i=1; i<=nlstate;i++)
3653: for(j=1; j<=nlstate;j++){
3654: fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
3655: }
3656: fprintf(ficresvij,"\n");
3657: free_matrix(gp,0,nhstepm,1,nlstate);
3658: free_matrix(gm,0,nhstepm,1,nlstate);
3659: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
3660: free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
3661: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3662: } /* End age */
3663: free_vector(gpp,nlstate+1,nlstate+ndeath);
3664: free_vector(gmp,nlstate+1,nlstate+ndeath);
3665: free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
3666: free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
3667: fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
3668: /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
3669: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
3670: /* fprintf(ficgp,"\n plot \"%s\" u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
3671: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
3672: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
3673: fprintf(ficgp,"\n plot \"%s\" u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
3674: fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
3675: fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
3676: fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
3677: 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);
3678: /* 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);
3679: */
3680: /* fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
3681: fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
3682:
3683: free_vector(xp,1,npar);
3684: free_matrix(doldm,1,nlstate,1,nlstate);
3685: free_matrix(dnewm,1,nlstate,1,npar);
3686: free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3687: free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
3688: free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3689: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3690: fclose(ficresprobmorprev);
3691: fflush(ficgp);
3692: fflush(fichtm);
3693: } /* end varevsij */
3694:
3695: /************ Variance of prevlim ******************/
3696: 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[])
3697: {
3698: /* Variance of prevalence limit */
3699: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
3700:
3701: double **dnewm,**doldm;
3702: int i, j, nhstepm, hstepm;
3703: double *xp;
3704: double *gp, *gm;
3705: double **gradg, **trgradg;
3706: double age,agelim;
3707: int theta;
3708:
3709: pstamp(ficresvpl);
3710: fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
3711: fprintf(ficresvpl,"# Age");
3712: for(i=1; i<=nlstate;i++)
3713: fprintf(ficresvpl," %1d-%1d",i,i);
3714: fprintf(ficresvpl,"\n");
3715:
3716: xp=vector(1,npar);
3717: dnewm=matrix(1,nlstate,1,npar);
3718: doldm=matrix(1,nlstate,1,nlstate);
3719:
3720: hstepm=1*YEARM; /* Every year of age */
3721: hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
3722: agelim = AGESUP;
3723: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3724: nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3725: if (stepm >= YEARM) hstepm=1;
3726: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
3727: gradg=matrix(1,npar,1,nlstate);
3728: gp=vector(1,nlstate);
3729: gm=vector(1,nlstate);
3730:
3731: for(theta=1; theta <=npar; theta++){
3732: for(i=1; i<=npar; i++){ /* Computes gradient */
3733: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3734: }
3735: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3736: for(i=1;i<=nlstate;i++)
3737: gp[i] = prlim[i][i];
3738:
3739: for(i=1; i<=npar; i++) /* Computes gradient */
3740: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3741: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3742: for(i=1;i<=nlstate;i++)
3743: gm[i] = prlim[i][i];
3744:
3745: for(i=1;i<=nlstate;i++)
3746: gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
3747: } /* End theta */
3748:
3749: trgradg =matrix(1,nlstate,1,npar);
3750:
3751: for(j=1; j<=nlstate;j++)
3752: for(theta=1; theta <=npar; theta++)
3753: trgradg[j][theta]=gradg[theta][j];
3754:
3755: for(i=1;i<=nlstate;i++)
3756: varpl[i][(int)age] =0.;
3757: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
3758: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
3759: for(i=1;i<=nlstate;i++)
3760: varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
3761:
3762: fprintf(ficresvpl,"%.0f ",age );
3763: for(i=1; i<=nlstate;i++)
3764: fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
3765: fprintf(ficresvpl,"\n");
3766: free_vector(gp,1,nlstate);
3767: free_vector(gm,1,nlstate);
3768: free_matrix(gradg,1,npar,1,nlstate);
3769: free_matrix(trgradg,1,nlstate,1,npar);
3770: } /* End age */
3771:
3772: free_vector(xp,1,npar);
3773: free_matrix(doldm,1,nlstate,1,npar);
3774: free_matrix(dnewm,1,nlstate,1,nlstate);
3775:
3776: }
3777:
3778: /************ Variance of one-step probabilities ******************/
3779: 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[])
3780: {
3781: int i, j=0, k1, l1, tj;
3782: int k2, l2, j1, z1;
3783: int k=0, l;
3784: int first=1, first1, first2;
3785: double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
3786: double **dnewm,**doldm;
3787: double *xp;
3788: double *gp, *gm;
3789: double **gradg, **trgradg;
3790: double **mu;
3791: double age, cov[NCOVMAX+1];
3792: double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
3793: int theta;
3794: char fileresprob[FILENAMELENGTH];
3795: char fileresprobcov[FILENAMELENGTH];
3796: char fileresprobcor[FILENAMELENGTH];
3797: double ***varpij;
3798:
3799: strcpy(fileresprob,"prob");
3800: strcat(fileresprob,fileres);
3801: if((ficresprob=fopen(fileresprob,"w"))==NULL) {
3802: printf("Problem with resultfile: %s\n", fileresprob);
3803: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
3804: }
3805: strcpy(fileresprobcov,"probcov");
3806: strcat(fileresprobcov,fileres);
3807: if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
3808: printf("Problem with resultfile: %s\n", fileresprobcov);
3809: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
3810: }
3811: strcpy(fileresprobcor,"probcor");
3812: strcat(fileresprobcor,fileres);
3813: if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
3814: printf("Problem with resultfile: %s\n", fileresprobcor);
3815: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
3816: }
3817: printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3818: fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3819: printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3820: fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3821: printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3822: fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3823: pstamp(ficresprob);
3824: fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
3825: fprintf(ficresprob,"# Age");
3826: pstamp(ficresprobcov);
3827: fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
3828: fprintf(ficresprobcov,"# Age");
3829: pstamp(ficresprobcor);
3830: fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
3831: fprintf(ficresprobcor,"# Age");
3832:
3833:
3834: for(i=1; i<=nlstate;i++)
3835: for(j=1; j<=(nlstate+ndeath);j++){
3836: fprintf(ficresprob," p%1d-%1d (SE)",i,j);
3837: fprintf(ficresprobcov," p%1d-%1d ",i,j);
3838: fprintf(ficresprobcor," p%1d-%1d ",i,j);
3839: }
3840: /* fprintf(ficresprob,"\n");
3841: fprintf(ficresprobcov,"\n");
3842: fprintf(ficresprobcor,"\n");
3843: */
3844: xp=vector(1,npar);
3845: dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3846: doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
3847: mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
3848: varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
3849: first=1;
3850: fprintf(ficgp,"\n# Routine varprob");
3851: fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
3852: fprintf(fichtm,"\n");
3853:
3854: fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
3855: fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
3856: file %s<br>\n",optionfilehtmcov);
3857: fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
3858: and drawn. It helps understanding how is the covariance between two incidences.\
3859: They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
3860: 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. \
3861: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
3862: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
3863: standard deviations wide on each axis. <br>\
3864: Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
3865: and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
3866: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
3867:
3868: cov[1]=1;
3869: /* tj=cptcoveff; */
3870: tj = (int) pow(2,cptcoveff);
3871: if (cptcovn<1) {tj=1;ncodemax[1]=1;}
3872: j1=0;
3873: for(j1=1; j1<=tj;j1++){
3874: /*for(i1=1; i1<=ncodemax[t];i1++){ */
3875: /*j1++;*/
3876: if (cptcovn>0) {
3877: fprintf(ficresprob, "\n#********** Variable ");
3878: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3879: fprintf(ficresprob, "**********\n#\n");
3880: fprintf(ficresprobcov, "\n#********** Variable ");
3881: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3882: fprintf(ficresprobcov, "**********\n#\n");
3883:
3884: fprintf(ficgp, "\n#********** Variable ");
3885: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3886: fprintf(ficgp, "**********\n#\n");
3887:
3888:
3889: fprintf(fichtmcov, "\n<hr size=\"2\" color=\"#EC5E5E\">********** Variable ");
3890: for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3891: fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
3892:
3893: fprintf(ficresprobcor, "\n#********** Variable ");
3894: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3895: fprintf(ficresprobcor, "**********\n#");
3896: }
3897:
3898: gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
3899: trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3900: gp=vector(1,(nlstate)*(nlstate+ndeath));
3901: gm=vector(1,(nlstate)*(nlstate+ndeath));
3902: for (age=bage; age<=fage; age ++){
3903: cov[2]=age;
3904: for (k=1; k<=cptcovn;k++) {
3905: cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
3906: * 1 1 1 1 1
3907: * 2 2 1 1 1
3908: * 3 1 2 1 1
3909: */
3910: /* nbcode[1][1]=0 nbcode[1][2]=1;*/
3911: }
3912: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
3913: for (k=1; k<=cptcovprod;k++)
3914: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
3915:
3916:
3917: for(theta=1; theta <=npar; theta++){
3918: for(i=1; i<=npar; i++)
3919: xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
3920:
3921: pmij(pmmij,cov,ncovmodel,xp,nlstate);
3922:
3923: k=0;
3924: for(i=1; i<= (nlstate); i++){
3925: for(j=1; j<=(nlstate+ndeath);j++){
3926: k=k+1;
3927: gp[k]=pmmij[i][j];
3928: }
3929: }
3930:
3931: for(i=1; i<=npar; i++)
3932: xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
3933:
3934: pmij(pmmij,cov,ncovmodel,xp,nlstate);
3935: k=0;
3936: for(i=1; i<=(nlstate); i++){
3937: for(j=1; j<=(nlstate+ndeath);j++){
3938: k=k+1;
3939: gm[k]=pmmij[i][j];
3940: }
3941: }
3942:
3943: for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
3944: gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];
3945: }
3946:
3947: for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
3948: for(theta=1; theta <=npar; theta++)
3949: trgradg[j][theta]=gradg[theta][j];
3950:
3951: matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
3952: matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
3953:
3954: pmij(pmmij,cov,ncovmodel,x,nlstate);
3955:
3956: k=0;
3957: for(i=1; i<=(nlstate); i++){
3958: for(j=1; j<=(nlstate+ndeath);j++){
3959: k=k+1;
3960: mu[k][(int) age]=pmmij[i][j];
3961: }
3962: }
3963: for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
3964: for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
3965: varpij[i][j][(int)age] = doldm[i][j];
3966:
3967: /*printf("\n%d ",(int)age);
3968: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
3969: printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
3970: fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
3971: }*/
3972:
3973: fprintf(ficresprob,"\n%d ",(int)age);
3974: fprintf(ficresprobcov,"\n%d ",(int)age);
3975: fprintf(ficresprobcor,"\n%d ",(int)age);
3976:
3977: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
3978: fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
3979: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
3980: fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
3981: fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
3982: }
3983: i=0;
3984: for (k=1; k<=(nlstate);k++){
3985: for (l=1; l<=(nlstate+ndeath);l++){
3986: i++;
3987: fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
3988: fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
3989: for (j=1; j<=i;j++){
3990: /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
3991: fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
3992: fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
3993: }
3994: }
3995: }/* end of loop for state */
3996: } /* end of loop for age */
3997: free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
3998: free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
3999: free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4000: free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4001:
4002: /* Confidence intervalle of pij */
4003: /*
4004: fprintf(ficgp,"\nunset parametric;unset label");
4005: fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
4006: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
4007: 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);
4008: fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
4009: fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
4010: fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
4011: */
4012:
4013: /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
4014: first1=1;first2=2;
4015: for (k2=1; k2<=(nlstate);k2++){
4016: for (l2=1; l2<=(nlstate+ndeath);l2++){
4017: if(l2==k2) continue;
4018: j=(k2-1)*(nlstate+ndeath)+l2;
4019: for (k1=1; k1<=(nlstate);k1++){
4020: for (l1=1; l1<=(nlstate+ndeath);l1++){
4021: if(l1==k1) continue;
4022: i=(k1-1)*(nlstate+ndeath)+l1;
4023: if(i<=j) continue;
4024: for (age=bage; age<=fage; age ++){
4025: if ((int)age %5==0){
4026: v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
4027: v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
4028: cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
4029: mu1=mu[i][(int) age]/stepm*YEARM ;
4030: mu2=mu[j][(int) age]/stepm*YEARM;
4031: c12=cv12/sqrt(v1*v2);
4032: /* Computing eigen value of matrix of covariance */
4033: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
4034: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
4035: if ((lc2 <0) || (lc1 <0) ){
4036: if(first2==1){
4037: first1=0;
4038: 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);
4039: }
4040: 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);
4041: /* lc1=fabs(lc1); */ /* If we want to have them positive */
4042: /* lc2=fabs(lc2); */
4043: }
4044:
4045: /* Eigen vectors */
4046: v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
4047: /*v21=sqrt(1.-v11*v11); *//* error */
4048: v21=(lc1-v1)/cv12*v11;
4049: v12=-v21;
4050: v22=v11;
4051: tnalp=v21/v11;
4052: if(first1==1){
4053: first1=0;
4054: 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);
4055: }
4056: 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);
4057: /*printf(fignu*/
4058: /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
4059: /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
4060: if(first==1){
4061: first=0;
4062: fprintf(ficgp,"\nset parametric;unset label");
4063: 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);
4064: fprintf(ficgp,"\nset ter png small size 320, 240");
4065: fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
4066: :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
4067: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
4068: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
4069: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4070: fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4071: fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
4072: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4073: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4074: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4075: 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",\
4076: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4077: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4078: }else{
4079: first=0;
4080: fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
4081: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4082: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4083: 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",\
4084: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4085: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4086: }/* if first */
4087: } /* age mod 5 */
4088: } /* end loop age */
4089: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4090: first=1;
4091: } /*l12 */
4092: } /* k12 */
4093: } /*l1 */
4094: }/* k1 */
4095: /* } */ /* loop covariates */
4096: }
4097: free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
4098: free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
4099: free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4100: free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
4101: free_vector(xp,1,npar);
4102: fclose(ficresprob);
4103: fclose(ficresprobcov);
4104: fclose(ficresprobcor);
4105: fflush(ficgp);
4106: fflush(fichtmcov);
4107: }
4108:
4109:
4110: /******************* Printing html file ***********/
4111: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
4112: int lastpass, int stepm, int weightopt, char model[],\
4113: int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
4114: int popforecast, int estepm ,\
4115: double jprev1, double mprev1,double anprev1, \
4116: double jprev2, double mprev2,double anprev2){
4117: int jj1, k1, i1, cpt;
4118:
4119: fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
4120: <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
4121: </ul>");
4122: fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
4123: - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
4124: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
4125: fprintf(fichtm,"\
4126: - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
4127: stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
4128: fprintf(fichtm,"\
4129: - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
4130: subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
4131: fprintf(fichtm,"\
4132: - (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): \
4133: <a href=\"%s\">%s</a> <br>\n",
4134: estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
4135: fprintf(fichtm,"\
4136: - Population projections by age and states: \
4137: <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
4138:
4139: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
4140:
4141: m=pow(2,cptcoveff);
4142: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4143:
4144: jj1=0;
4145: for(k1=1; k1<=m;k1++){
4146: for(i1=1; i1<=ncodemax[k1];i1++){
4147: jj1++;
4148: if (cptcovn > 0) {
4149: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4150: for (cpt=1; cpt<=cptcoveff;cpt++)
4151: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4152: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4153: }
4154: /* Pij */
4155: 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> \
4156: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
4157: /* Quasi-incidences */
4158: fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
4159: 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> \
4160: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
4161: /* Period (stable) prevalence in each health state */
4162: for(cpt=1; cpt<=nlstate;cpt++){
4163: 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> \
4164: <img src=\"%s%d_%d.png\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
4165: }
4166: for(cpt=1; cpt<=nlstate;cpt++) {
4167: 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> \
4168: <img src=\"%s%d%d.png\">",cpt,nlstate,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
4169: }
4170: } /* end i1 */
4171: }/* End k1 */
4172: fprintf(fichtm,"</ul>");
4173:
4174:
4175: fprintf(fichtm,"\
4176: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
4177: - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
4178:
4179: fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4180: subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
4181: fprintf(fichtm,"\
4182: - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4183: subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
4184:
4185: fprintf(fichtm,"\
4186: - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4187: subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
4188: fprintf(fichtm,"\
4189: - 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): \
4190: <a href=\"%s\">%s</a> <br>\n</li>",
4191: estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
4192: fprintf(fichtm,"\
4193: - (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): \
4194: <a href=\"%s\">%s</a> <br>\n</li>",
4195: estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
4196: fprintf(fichtm,"\
4197: - 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",
4198: estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
4199: fprintf(fichtm,"\
4200: - 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",
4201: estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
4202: fprintf(fichtm,"\
4203: - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
4204: subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
4205:
4206: /* if(popforecast==1) fprintf(fichtm,"\n */
4207: /* - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
4208: /* - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
4209: /* <br>",fileres,fileres,fileres,fileres); */
4210: /* else */
4211: /* 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); */
4212: fflush(fichtm);
4213: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
4214:
4215: m=pow(2,cptcoveff);
4216: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4217:
4218: jj1=0;
4219: for(k1=1; k1<=m;k1++){
4220: for(i1=1; i1<=ncodemax[k1];i1++){
4221: jj1++;
4222: if (cptcovn > 0) {
4223: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4224: for (cpt=1; cpt<=cptcoveff;cpt++)
4225: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4226: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4227: }
4228: for(cpt=1; cpt<=nlstate;cpt++) {
4229: fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
4230: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
4231: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);
4232: }
4233: fprintf(fichtm,"\n<br>- Total life expectancy by age and \
4234: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
4235: true period expectancies (those weighted with period prevalences are also\
4236: drawn in addition to the population based expectancies computed using\
4237: observed and cahotic prevalences: %s%d.png<br>\
4238: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
4239: } /* end i1 */
4240: }/* End k1 */
4241: fprintf(fichtm,"</ul>");
4242: fflush(fichtm);
4243: }
4244:
4245: /******************* Gnuplot file **************/
4246: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4247:
4248: char dirfileres[132],optfileres[132];
4249: int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
4250: int ng=0;
4251: /* if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
4252: /* printf("Problem with file %s",optionfilegnuplot); */
4253: /* fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
4254: /* } */
4255:
4256: /*#ifdef windows */
4257: fprintf(ficgp,"cd \"%s\" \n",pathc);
4258: /*#endif */
4259: m=pow(2,cptcoveff);
4260:
4261: strcpy(dirfileres,optionfilefiname);
4262: strcpy(optfileres,"vpl");
4263: /* 1eme*/
4264: fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
4265: for (cpt=1; cpt<= nlstate ; cpt ++) {
4266: for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
4267: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
4268: fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
4269: fprintf(ficgp,"set xlabel \"Age\" \n\
4270: set ylabel \"Probability\" \n\
4271: set ter png small size 320, 240\n\
4272: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
4273:
4274: for (i=1; i<= nlstate ; i ++) {
4275: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4276: else fprintf(ficgp," %%*lf (%%*lf)");
4277: }
4278: 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);
4279: for (i=1; i<= nlstate ; i ++) {
4280: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4281: else fprintf(ficgp," %%*lf (%%*lf)");
4282: }
4283: 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);
4284: for (i=1; i<= nlstate ; i ++) {
4285: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4286: else fprintf(ficgp," %%*lf (%%*lf)");
4287: }
4288: 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));
4289: }
4290: }
4291: /*2 eme*/
4292: fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
4293: for (k1=1; k1<= m ; k1 ++) {
4294: fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
4295: fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
4296:
4297: for (i=1; i<= nlstate+1 ; i ++) {
4298: k=2*i;
4299: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4300: for (j=1; j<= nlstate+1 ; j ++) {
4301: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4302: else fprintf(ficgp," %%*lf (%%*lf)");
4303: }
4304: if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
4305: else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
4306: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4307: for (j=1; j<= nlstate+1 ; j ++) {
4308: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4309: else fprintf(ficgp," %%*lf (%%*lf)");
4310: }
4311: fprintf(ficgp,"\" t\"\" w l lt 0,");
4312: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4313: for (j=1; j<= nlstate+1 ; j ++) {
4314: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4315: else fprintf(ficgp," %%*lf (%%*lf)");
4316: }
4317: if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
4318: else fprintf(ficgp,"\" t\"\" w l lt 0,");
4319: }
4320: }
4321:
4322: /*3eme*/
4323:
4324: for (k1=1; k1<= m ; k1 ++) {
4325: for (cpt=1; cpt<= nlstate ; cpt ++) {
4326: /* k=2+nlstate*(2*cpt-2); */
4327: k=2+(nlstate+1)*(cpt-1);
4328: fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
4329: fprintf(ficgp,"set ter png small size 320, 240\n\
4330: 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);
4331: /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4332: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4333: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4334: fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4335: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4336: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4337:
4338: */
4339: for (i=1; i< nlstate ; i ++) {
4340: 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);
4341: /* 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);*/
4342:
4343: }
4344: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
4345: }
4346: }
4347:
4348: /* CV preval stable (period) */
4349: for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
4350: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
4351: k=3;
4352: fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
4353: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
4354: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
4355: set ter png small size 320, 240\n\
4356: unset log y\n\
4357: plot [%.f:%.f] ", ageminpar, agemaxpar);
4358: for (i=1; i<= nlstate ; i ++){
4359: if(i==1)
4360: fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
4361: else
4362: fprintf(ficgp,", '' ");
4363: l=(nlstate+ndeath)*(i-1)+1;
4364: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
4365: for (j=1; j<= (nlstate-1) ; j ++)
4366: fprintf(ficgp,"+$%d",k+l+j);
4367: fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
4368: } /* nlstate */
4369: fprintf(ficgp,"\n");
4370: } /* end cpt state*/
4371: } /* end covariate */
4372:
4373: /* proba elementaires */
4374: for(i=1,jk=1; i <=nlstate; i++){
4375: for(k=1; k <=(nlstate+ndeath); k++){
4376: if (k != i) {
4377: for(j=1; j <=ncovmodel; j++){
4378: fprintf(ficgp,"p%d=%f ",jk,p[jk]);
4379: jk++;
4380: fprintf(ficgp,"\n");
4381: }
4382: }
4383: }
4384: }
4385: /*goto avoid;*/
4386: for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
4387: for(jk=1; jk <=m; jk++) {
4388: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);
4389: if (ng==2)
4390: fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
4391: else
4392: fprintf(ficgp,"\nset title \"Probability\"\n");
4393: fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot [%.f:%.f] ",ageminpar,agemaxpar);
4394: i=1;
4395: for(k2=1; k2<=nlstate; k2++) {
4396: k3=i;
4397: for(k=1; k<=(nlstate+ndeath); k++) {
4398: if (k != k2){
4399: if(ng==2)
4400: fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
4401: else
4402: fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
4403: ij=1;/* To be checked else nbcode[0][0] wrong */
4404: for(j=3; j <=ncovmodel; j++) {
4405: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /\* Bug valgrind *\/ */
4406: /* /\*fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);*\/ */
4407: /* ij++; */
4408: /* } */
4409: /* else */
4410: fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4411: }
4412: fprintf(ficgp,")/(1");
4413:
4414: for(k1=1; k1 <=nlstate; k1++){
4415: fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
4416: ij=1;
4417: for(j=3; j <=ncovmodel; j++){
4418: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { */
4419: /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]); */
4420: /* ij++; */
4421: /* } */
4422: /* else */
4423: fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4424: }
4425: fprintf(ficgp,")");
4426: }
4427: fprintf(ficgp,") t \"p%d%d\" ", k2,k);
4428: if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
4429: i=i+ncovmodel;
4430: }
4431: } /* end k */
4432: } /* end k2 */
4433: } /* end jk */
4434: } /* end ng */
4435: /* avoid: */
4436: fflush(ficgp);
4437: } /* end gnuplot */
4438:
4439:
4440: /*************** Moving average **************/
4441: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
4442:
4443: int i, cpt, cptcod;
4444: int modcovmax =1;
4445: int mobilavrange, mob;
4446: double age;
4447:
4448: modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
4449: a covariate has 2 modalities */
4450: if (cptcovn<1) modcovmax=1; /* At least 1 pass */
4451:
4452: if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
4453: if(mobilav==1) mobilavrange=5; /* default */
4454: else mobilavrange=mobilav;
4455: for (age=bage; age<=fage; age++)
4456: for (i=1; i<=nlstate;i++)
4457: for (cptcod=1;cptcod<=modcovmax;cptcod++)
4458: mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
4459: /* We keep the original values on the extreme ages bage, fage and for
4460: fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
4461: we use a 5 terms etc. until the borders are no more concerned.
4462: */
4463: for (mob=3;mob <=mobilavrange;mob=mob+2){
4464: for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
4465: for (i=1; i<=nlstate;i++){
4466: for (cptcod=1;cptcod<=modcovmax;cptcod++){
4467: mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
4468: for (cpt=1;cpt<=(mob-1)/2;cpt++){
4469: mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
4470: mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
4471: }
4472: mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
4473: }
4474: }
4475: }/* end age */
4476: }/* end mob */
4477: }else return -1;
4478: return 0;
4479: }/* End movingaverage */
4480:
4481:
4482: /************** Forecasting ******************/
4483: 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){
4484: /* proj1, year, month, day of starting projection
4485: agemin, agemax range of age
4486: dateprev1 dateprev2 range of dates during which prevalence is computed
4487: anproj2 year of en of projection (same day and month as proj1).
4488: */
4489: int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
4490: double agec; /* generic age */
4491: double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
4492: double *popeffectif,*popcount;
4493: double ***p3mat;
4494: double ***mobaverage;
4495: char fileresf[FILENAMELENGTH];
4496:
4497: agelim=AGESUP;
4498: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4499:
4500: strcpy(fileresf,"f");
4501: strcat(fileresf,fileres);
4502: if((ficresf=fopen(fileresf,"w"))==NULL) {
4503: printf("Problem with forecast resultfile: %s\n", fileresf);
4504: fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
4505: }
4506: printf("Computing forecasting: result on file '%s' \n", fileresf);
4507: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
4508:
4509: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4510:
4511: if (mobilav!=0) {
4512: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4513: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4514: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4515: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4516: }
4517: }
4518:
4519: stepsize=(int) (stepm+YEARM-1)/YEARM;
4520: if (stepm<=12) stepsize=1;
4521: if(estepm < stepm){
4522: printf ("Problem %d lower than %d\n",estepm, stepm);
4523: }
4524: else hstepm=estepm;
4525:
4526: hstepm=hstepm/stepm;
4527: yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp and
4528: fractional in yp1 */
4529: anprojmean=yp;
4530: yp2=modf((yp1*12),&yp);
4531: mprojmean=yp;
4532: yp1=modf((yp2*30.5),&yp);
4533: jprojmean=yp;
4534: if(jprojmean==0) jprojmean=1;
4535: if(mprojmean==0) jprojmean=1;
4536:
4537: i1=cptcoveff;
4538: if (cptcovn < 1){i1=1;}
4539:
4540: fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
4541:
4542: fprintf(ficresf,"#****** Routine prevforecast **\n");
4543:
4544: /* if (h==(int)(YEARM*yearp)){ */
4545: for(cptcov=1, k=0;cptcov<=i1;cptcov++){
4546: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4547: k=k+1;
4548: fprintf(ficresf,"\n#******");
4549: for(j=1;j<=cptcoveff;j++) {
4550: 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]]);
4551: }
4552: fprintf(ficresf,"******\n");
4553: fprintf(ficresf,"# Covariate valuofcovar yearproj age");
4554: for(j=1; j<=nlstate+ndeath;j++){
4555: for(i=1; i<=nlstate;i++)
4556: fprintf(ficresf," p%d%d",i,j);
4557: fprintf(ficresf," p.%d",j);
4558: }
4559: for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
4560: fprintf(ficresf,"\n");
4561: fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);
4562:
4563: for (agec=fage; agec>=(ageminpar-1); agec--){
4564: nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
4565: nhstepm = nhstepm/hstepm;
4566: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4567: oldm=oldms;savm=savms;
4568: hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
4569:
4570: for (h=0; h<=nhstepm; h++){
4571: if (h*hstepm/YEARM*stepm ==yearp) {
4572: fprintf(ficresf,"\n");
4573: for(j=1;j<=cptcoveff;j++)
4574: fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4575: fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
4576: }
4577: for(j=1; j<=nlstate+ndeath;j++) {
4578: ppij=0.;
4579: for(i=1; i<=nlstate;i++) {
4580: if (mobilav==1)
4581: ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
4582: else {
4583: ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
4584: }
4585: if (h*hstepm/YEARM*stepm== yearp) {
4586: fprintf(ficresf," %.3f", p3mat[i][j][h]);
4587: }
4588: } /* end i */
4589: if (h*hstepm/YEARM*stepm==yearp) {
4590: fprintf(ficresf," %.3f", ppij);
4591: }
4592: }/* end j */
4593: } /* end h */
4594: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4595: } /* end agec */
4596: } /* end yearp */
4597: } /* end cptcod */
4598: } /* end cptcov */
4599:
4600: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4601:
4602: fclose(ficresf);
4603: }
4604:
4605: /************** Forecasting *****not tested NB*************/
4606: 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){
4607:
4608: int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
4609: int *popage;
4610: double calagedatem, agelim, kk1, kk2;
4611: double *popeffectif,*popcount;
4612: double ***p3mat,***tabpop,***tabpopprev;
4613: double ***mobaverage;
4614: char filerespop[FILENAMELENGTH];
4615:
4616: tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4617: tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4618: agelim=AGESUP;
4619: calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
4620:
4621: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4622:
4623:
4624: strcpy(filerespop,"pop");
4625: strcat(filerespop,fileres);
4626: if((ficrespop=fopen(filerespop,"w"))==NULL) {
4627: printf("Problem with forecast resultfile: %s\n", filerespop);
4628: fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
4629: }
4630: printf("Computing forecasting: result on file '%s' \n", filerespop);
4631: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
4632:
4633: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4634:
4635: if (mobilav!=0) {
4636: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4637: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4638: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4639: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4640: }
4641: }
4642:
4643: stepsize=(int) (stepm+YEARM-1)/YEARM;
4644: if (stepm<=12) stepsize=1;
4645:
4646: agelim=AGESUP;
4647:
4648: hstepm=1;
4649: hstepm=hstepm/stepm;
4650:
4651: if (popforecast==1) {
4652: if((ficpop=fopen(popfile,"r"))==NULL) {
4653: printf("Problem with population file : %s\n",popfile);exit(0);
4654: fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
4655: }
4656: popage=ivector(0,AGESUP);
4657: popeffectif=vector(0,AGESUP);
4658: popcount=vector(0,AGESUP);
4659:
4660: i=1;
4661: while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
4662:
4663: imx=i;
4664: for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
4665: }
4666:
4667: for(cptcov=1,k=0;cptcov<=i2;cptcov++){
4668: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4669: k=k+1;
4670: fprintf(ficrespop,"\n#******");
4671: for(j=1;j<=cptcoveff;j++) {
4672: fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4673: }
4674: fprintf(ficrespop,"******\n");
4675: fprintf(ficrespop,"# Age");
4676: for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
4677: if (popforecast==1) fprintf(ficrespop," [Population]");
4678:
4679: for (cpt=0; cpt<=0;cpt++) {
4680: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4681:
4682: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4683: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4684: nhstepm = nhstepm/hstepm;
4685:
4686: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4687: oldm=oldms;savm=savms;
4688: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4689:
4690: for (h=0; h<=nhstepm; h++){
4691: if (h==(int) (calagedatem+YEARM*cpt)) {
4692: fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4693: }
4694: for(j=1; j<=nlstate+ndeath;j++) {
4695: kk1=0.;kk2=0;
4696: for(i=1; i<=nlstate;i++) {
4697: if (mobilav==1)
4698: kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
4699: else {
4700: kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
4701: }
4702: }
4703: if (h==(int)(calagedatem+12*cpt)){
4704: tabpop[(int)(agedeb)][j][cptcod]=kk1;
4705: /*fprintf(ficrespop," %.3f", kk1);
4706: if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
4707: }
4708: }
4709: for(i=1; i<=nlstate;i++){
4710: kk1=0.;
4711: for(j=1; j<=nlstate;j++){
4712: kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
4713: }
4714: tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
4715: }
4716:
4717: if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
4718: fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
4719: }
4720: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4721: }
4722: }
4723:
4724: /******/
4725:
4726: for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
4727: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4728: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4729: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4730: nhstepm = nhstepm/hstepm;
4731:
4732: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4733: oldm=oldms;savm=savms;
4734: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4735: for (h=0; h<=nhstepm; h++){
4736: if (h==(int) (calagedatem+YEARM*cpt)) {
4737: fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4738: }
4739: for(j=1; j<=nlstate+ndeath;j++) {
4740: kk1=0.;kk2=0;
4741: for(i=1; i<=nlstate;i++) {
4742: kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];
4743: }
4744: if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);
4745: }
4746: }
4747: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4748: }
4749: }
4750: }
4751: }
4752:
4753: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4754:
4755: if (popforecast==1) {
4756: free_ivector(popage,0,AGESUP);
4757: free_vector(popeffectif,0,AGESUP);
4758: free_vector(popcount,0,AGESUP);
4759: }
4760: free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4761: free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4762: fclose(ficrespop);
4763: } /* End of popforecast */
4764:
4765: int fileappend(FILE *fichier, char *optionfich)
4766: {
4767: if((fichier=fopen(optionfich,"a"))==NULL) {
4768: printf("Problem with file: %s\n", optionfich);
4769: fprintf(ficlog,"Problem with file: %s\n", optionfich);
4770: return (0);
4771: }
4772: fflush(fichier);
4773: return (1);
4774: }
4775:
4776:
4777: /**************** function prwizard **********************/
4778: void prwizard(int ncovmodel, int nlstate, int ndeath, char model[], FILE *ficparo)
4779: {
4780:
4781: /* Wizard to print covariance matrix template */
4782:
4783: char ca[32], cb[32];
4784: int i,j, k, li, lj, lk, ll, jj, npar, itimes;
4785: int numlinepar;
4786:
4787: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4788: fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4789: for(i=1; i <=nlstate; i++){
4790: jj=0;
4791: for(j=1; j <=nlstate+ndeath; j++){
4792: if(j==i) continue;
4793: jj++;
4794: /*ca[0]= k+'a'-1;ca[1]='\0';*/
4795: printf("%1d%1d",i,j);
4796: fprintf(ficparo,"%1d%1d",i,j);
4797: for(k=1; k<=ncovmodel;k++){
4798: /* printf(" %lf",param[i][j][k]); */
4799: /* fprintf(ficparo," %lf",param[i][j][k]); */
4800: printf(" 0.");
4801: fprintf(ficparo," 0.");
4802: }
4803: printf("\n");
4804: fprintf(ficparo,"\n");
4805: }
4806: }
4807: printf("# Scales (for hessian or gradient estimation)\n");
4808: fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
4809: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
4810: for(i=1; i <=nlstate; i++){
4811: jj=0;
4812: for(j=1; j <=nlstate+ndeath; j++){
4813: if(j==i) continue;
4814: jj++;
4815: fprintf(ficparo,"%1d%1d",i,j);
4816: printf("%1d%1d",i,j);
4817: fflush(stdout);
4818: for(k=1; k<=ncovmodel;k++){
4819: /* printf(" %le",delti3[i][j][k]); */
4820: /* fprintf(ficparo," %le",delti3[i][j][k]); */
4821: printf(" 0.");
4822: fprintf(ficparo," 0.");
4823: }
4824: numlinepar++;
4825: printf("\n");
4826: fprintf(ficparo,"\n");
4827: }
4828: }
4829: printf("# Covariance matrix\n");
4830: /* # 121 Var(a12)\n\ */
4831: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4832: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
4833: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
4834: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
4835: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
4836: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
4837: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4838: fflush(stdout);
4839: fprintf(ficparo,"# Covariance matrix\n");
4840: /* # 121 Var(a12)\n\ */
4841: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4842: /* # ...\n\ */
4843: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4844:
4845: for(itimes=1;itimes<=2;itimes++){
4846: jj=0;
4847: for(i=1; i <=nlstate; i++){
4848: for(j=1; j <=nlstate+ndeath; j++){
4849: if(j==i) continue;
4850: for(k=1; k<=ncovmodel;k++){
4851: jj++;
4852: ca[0]= k+'a'-1;ca[1]='\0';
4853: if(itimes==1){
4854: printf("#%1d%1d%d",i,j,k);
4855: fprintf(ficparo,"#%1d%1d%d",i,j,k);
4856: }else{
4857: printf("%1d%1d%d",i,j,k);
4858: fprintf(ficparo,"%1d%1d%d",i,j,k);
4859: /* printf(" %.5le",matcov[i][j]); */
4860: }
4861: ll=0;
4862: for(li=1;li <=nlstate; li++){
4863: for(lj=1;lj <=nlstate+ndeath; lj++){
4864: if(lj==li) continue;
4865: for(lk=1;lk<=ncovmodel;lk++){
4866: ll++;
4867: if(ll<=jj){
4868: cb[0]= lk +'a'-1;cb[1]='\0';
4869: if(ll<jj){
4870: if(itimes==1){
4871: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4872: fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4873: }else{
4874: printf(" 0.");
4875: fprintf(ficparo," 0.");
4876: }
4877: }else{
4878: if(itimes==1){
4879: printf(" Var(%s%1d%1d)",ca,i,j);
4880: fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
4881: }else{
4882: printf(" 0.");
4883: fprintf(ficparo," 0.");
4884: }
4885: }
4886: }
4887: } /* end lk */
4888: } /* end lj */
4889: } /* end li */
4890: printf("\n");
4891: fprintf(ficparo,"\n");
4892: numlinepar++;
4893: } /* end k*/
4894: } /*end j */
4895: } /* end i */
4896: } /* end itimes */
4897:
4898: } /* end of prwizard */
4899: /******************* Gompertz Likelihood ******************************/
4900: double gompertz(double x[])
4901: {
4902: double A,B,L=0.0,sump=0.,num=0.;
4903: int i,n=0; /* n is the size of the sample */
4904:
4905: for (i=0;i<=imx-1 ; i++) {
4906: sump=sump+weight[i];
4907: /* sump=sump+1;*/
4908: num=num+1;
4909: }
4910:
4911:
4912: /* for (i=0; i<=imx; i++)
4913: 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]);*/
4914:
4915: for (i=1;i<=imx ; i++)
4916: {
4917: if (cens[i] == 1 && wav[i]>1)
4918: A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
4919:
4920: if (cens[i] == 0 && wav[i]>1)
4921: A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
4922: +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);
4923:
4924: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
4925: if (wav[i] > 1 ) { /* ??? */
4926: L=L+A*weight[i];
4927: /* 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]);*/
4928: }
4929: }
4930:
4931: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
4932:
4933: return -2*L*num/sump;
4934: }
4935:
4936: #ifdef GSL
4937: /******************* Gompertz_f Likelihood ******************************/
4938: double gompertz_f(const gsl_vector *v, void *params)
4939: {
4940: double A,B,LL=0.0,sump=0.,num=0.;
4941: double *x= (double *) v->data;
4942: int i,n=0; /* n is the size of the sample */
4943:
4944: for (i=0;i<=imx-1 ; i++) {
4945: sump=sump+weight[i];
4946: /* sump=sump+1;*/
4947: num=num+1;
4948: }
4949:
4950:
4951: /* for (i=0; i<=imx; i++)
4952: 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]);*/
4953: printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
4954: for (i=1;i<=imx ; i++)
4955: {
4956: if (cens[i] == 1 && wav[i]>1)
4957: A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
4958:
4959: if (cens[i] == 0 && wav[i]>1)
4960: A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
4961: +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);
4962:
4963: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
4964: if (wav[i] > 1 ) { /* ??? */
4965: LL=LL+A*weight[i];
4966: /* 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]);*/
4967: }
4968: }
4969:
4970: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
4971: printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
4972:
4973: return -2*LL*num/sump;
4974: }
4975: #endif
4976:
4977: /******************* Printing html file ***********/
4978: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
4979: int lastpass, int stepm, int weightopt, char model[],\
4980: int imx, double p[],double **matcov,double agemortsup){
4981: int i,k;
4982:
4983: fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
4984: fprintf(fichtm," mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
4985: for (i=1;i<=2;i++)
4986: 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]));
4987: fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
4988: fprintf(fichtm,"</ul>");
4989:
4990: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
4991:
4992: 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>");
4993:
4994: for (k=agegomp;k<(agemortsup-2);k++)
4995: 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]);
4996:
4997:
4998: fflush(fichtm);
4999: }
5000:
5001: /******************* Gnuplot file **************/
5002: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
5003:
5004: char dirfileres[132],optfileres[132];
5005:
5006: int ng;
5007:
5008:
5009: /*#ifdef windows */
5010: fprintf(ficgp,"cd \"%s\" \n",pathc);
5011: /*#endif */
5012:
5013:
5014: strcpy(dirfileres,optionfilefiname);
5015: strcpy(optfileres,"vpl");
5016: fprintf(ficgp,"set out \"graphmort.png\"\n ");
5017: fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
5018: fprintf(ficgp, "set ter png small size 320, 240\n set log y\n");
5019: /* fprintf(ficgp, "set size 0.65,0.65\n"); */
5020: fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
5021:
5022: }
5023:
5024: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
5025: {
5026:
5027: /*-------- data file ----------*/
5028: FILE *fic;
5029: char dummy[]=" ";
5030: int i=0, j=0, n=0;
5031: int linei, month, year,iout;
5032: char line[MAXLINE], linetmp[MAXLINE];
5033: char stra[MAXLINE], strb[MAXLINE];
5034: char *stratrunc;
5035: int lstra;
5036:
5037:
5038: if((fic=fopen(datafile,"r"))==NULL) {
5039: printf("Problem while opening datafile: %s\n", datafile);return 1;
5040: fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
5041: }
5042:
5043: i=1;
5044: linei=0;
5045: while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
5046: linei=linei+1;
5047: for(j=strlen(line); j>=0;j--){ /* Untabifies line */
5048: if(line[j] == '\t')
5049: line[j] = ' ';
5050: }
5051: for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
5052: ;
5053: };
5054: line[j+1]=0; /* Trims blanks at end of line */
5055: if(line[0]=='#'){
5056: fprintf(ficlog,"Comment line\n%s\n",line);
5057: printf("Comment line\n%s\n",line);
5058: continue;
5059: }
5060: trimbb(linetmp,line); /* Trims multiple blanks in line */
5061: strcpy(line, linetmp);
5062:
5063:
5064: for (j=maxwav;j>=1;j--){
5065: cutv(stra, strb, line, ' ');
5066: if(strb[0]=='.') { /* Missing status */
5067: lval=-1;
5068: }else{
5069: errno=0;
5070: lval=strtol(strb,&endptr,10);
5071: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
5072: if( strb[0]=='\0' || (*endptr != '\0')){
5073: 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);
5074: 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);
5075: return 1;
5076: }
5077: }
5078: s[j][i]=lval;
5079:
5080: strcpy(line,stra);
5081: cutv(stra, strb,line,' ');
5082: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
5083: }
5084: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
5085: month=99;
5086: year=9999;
5087: }else{
5088: 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);
5089: 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);
5090: return 1;
5091: }
5092: anint[j][i]= (double) year;
5093: mint[j][i]= (double)month;
5094: strcpy(line,stra);
5095: } /* ENd Waves */
5096:
5097: cutv(stra, strb,line,' ');
5098: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
5099: }
5100: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
5101: month=99;
5102: year=9999;
5103: }else{
5104: 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);
5105: 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);
5106: return 1;
5107: }
5108: andc[i]=(double) year;
5109: moisdc[i]=(double) month;
5110: strcpy(line,stra);
5111:
5112: cutv(stra, strb,line,' ');
5113: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
5114: }
5115: else if( (iout=sscanf(strb,"%s.", dummy)) != 0){
5116: month=99;
5117: year=9999;
5118: }else{
5119: 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);
5120: 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);
5121: return 1;
5122: }
5123: if (year==9999) {
5124: 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);
5125: 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);
5126: return 1;
5127:
5128: }
5129: annais[i]=(double)(year);
5130: moisnais[i]=(double)(month);
5131: strcpy(line,stra);
5132:
5133: cutv(stra, strb,line,' ');
5134: errno=0;
5135: dval=strtod(strb,&endptr);
5136: if( strb[0]=='\0' || (*endptr != '\0')){
5137: printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight. Exiting.\n",dval, i,line,linei);
5138: 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);
5139: fflush(ficlog);
5140: return 1;
5141: }
5142: weight[i]=dval;
5143: strcpy(line,stra);
5144:
5145: for (j=ncovcol;j>=1;j--){
5146: cutv(stra, strb,line,' ');
5147: if(strb[0]=='.') { /* Missing status */
5148: lval=-1;
5149: }else{
5150: errno=0;
5151: lval=strtol(strb,&endptr,10);
5152: if( strb[0]=='\0' || (*endptr != '\0')){
5153: 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);
5154: 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);
5155: return 1;
5156: }
5157: }
5158: if(lval <-1 || lval >1){
5159: printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
5160: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5161: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5162: For example, for multinomial values like 1, 2 and 3,\n \
5163: build V1=0 V2=0 for the reference value (1),\n \
5164: V1=1 V2=0 for (2) \n \
5165: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5166: output of IMaCh is often meaningless.\n \
5167: Exiting.\n",lval,linei, i,line,j);
5168: fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
5169: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5170: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5171: For example, for multinomial values like 1, 2 and 3,\n \
5172: build V1=0 V2=0 for the reference value (1),\n \
5173: V1=1 V2=0 for (2) \n \
5174: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5175: output of IMaCh is often meaningless.\n \
5176: Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
5177: return 1;
5178: }
5179: covar[j][i]=(double)(lval);
5180: strcpy(line,stra);
5181: }
5182: lstra=strlen(stra);
5183:
5184: if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
5185: stratrunc = &(stra[lstra-9]);
5186: num[i]=atol(stratrunc);
5187: }
5188: else
5189: num[i]=atol(stra);
5190: /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
5191: 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;}*/
5192:
5193: i=i+1;
5194: } /* End loop reading data */
5195:
5196: *imax=i-1; /* Number of individuals */
5197: fclose(fic);
5198:
5199: return (0);
5200: /* endread: */
5201: printf("Exiting readdata: ");
5202: fclose(fic);
5203: return (1);
5204:
5205:
5206:
5207: }
5208: void removespace(char *str) {
5209: char *p1 = str, *p2 = str;
5210: do
5211: while (*p2 == ' ')
5212: p2++;
5213: while (*p1++ == *p2++);
5214: }
5215:
5216: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
5217: * Model V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age
5218: * - cptcovt total number of covariates of the model nbocc(+)+1 = 8
5219: * - cptcovn or number of covariates k of the models excluding age*products =6
5220: * - cptcovage number of covariates with age*products =2
5221: * - cptcovs number of simple covariates
5222: * - 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
5223: * which is a new column after the 9 (ncovcol) variables.
5224: * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
5225: * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
5226: * Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
5227: * - Tvard[k] p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
5228: */
5229: {
5230: int i, j, k, ks;
5231: int j1, k1, k2;
5232: char modelsav[80];
5233: char stra[80], strb[80], strc[80], strd[80],stre[80];
5234:
5235: /*removespace(model);*/
5236: if (strlen(model) >1){ /* If there is at least 1 covariate */
5237: j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
5238: j=nbocc(model,'+'); /**< j=Number of '+' */
5239: j1=nbocc(model,'*'); /**< j1=Number of '*' */
5240: cptcovs=j+1-j1; /**< Number of simple covariates V1+V2*age+V3 +V3*V4=> V1 + V3 =2 */
5241: cptcovt= j+1; /* Number of total covariates in the model V1 + V2*age+ V3 + V3*V4=> 4*/
5242: /* including age products which are counted in cptcovage.
5243: * but the covariates which are products must be treated separately: ncovn=4- 2=2 (V1+V3). */
5244: cptcovprod=j1; /**< Number of products V1*V2 +v3*age = 2 */
5245: cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1 */
5246: strcpy(modelsav,model);
5247: if (strstr(model,"AGE") !=0){
5248: printf("Error. AGE must be in lower case 'age' model=%s ",model);
5249: fprintf(ficlog,"Error. AGE must be in lower case model=%s ",model);fflush(ficlog);
5250: return 1;
5251: }
5252: if (strstr(model,"v") !=0){
5253: printf("Error. 'v' must be in upper case 'V' model=%s ",model);
5254: fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
5255: return 1;
5256: }
5257:
5258: /* Design
5259: * V1 V2 V3 V4 V5 V6 V7 V8 V9 Weight
5260: * < ncovcol=8 >
5261: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
5262: * k= 1 2 3 4 5 6 7 8
5263: * cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
5264: * covar[k,i], value of kth covariate if not including age for individual i:
5265: * covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
5266: * Tvar[k] # of the kth covariate: Tvar[1]=2 Tvar[4]=3 Tvar[8]=8
5267: * if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and
5268: * Tage[++cptcovage]=k
5269: * if products, new covar are created after ncovcol with k1
5270: * Tvar[k]=ncovcol+k1; # of the kth covariate product: Tvar[5]=ncovcol+1=10 Tvar[6]=ncovcol+1=11
5271: * Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
5272: * 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
5273: * Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
5274: * Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
5275: * V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
5276: * < ncovcol=8 >
5277: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 d1 d1 d2 d2
5278: * k= 1 2 3 4 5 6 7 8 9 10 11 12
5279: * Tvar[k]= 2 1 3 3 10 11 8 8 5 6 7 8
5280: * p Tvar[1]@12={2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5281: * p Tprod[1]@2={ 6, 5}
5282: *p Tvard[1][1]@4= {7, 8, 5, 6}
5283: * covar[k][i]= V2 V1 ? V3 V5*V6? V7*V8? ? V8
5284: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
5285: *How to reorganize?
5286: * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
5287: * Tvars {2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5288: * {2, 1, 4, 8, 5, 6, 3, 7}
5289: * Struct []
5290: */
5291:
5292: /* This loop fills the array Tvar from the string 'model'.*/
5293: /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
5294: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 */
5295: /* k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
5296: /* k=3 V4 Tvar[k=3]= 4 (from V4) */
5297: /* k=2 V1 Tvar[k=2]= 1 (from V1) */
5298: /* k=1 Tvar[1]=2 (from V2) */
5299: /* k=5 Tvar[5] */
5300: /* for (k=1; k<=cptcovn;k++) { */
5301: /* cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
5302: /* } */
5303: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
5304: /*
5305: * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
5306: for(k=cptcovt; k>=1;k--) /**< Number of covariates */
5307: Tvar[k]=0;
5308: cptcovage=0;
5309: for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
5310: cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+'
5311: modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */
5312: if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
5313: /* printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
5314: /*scanf("%d",i);*/
5315: if (strchr(strb,'*')) { /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
5316: cutl(strc,strd,strb,'*'); /**< strd*strc Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
5317: if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
5318: /* covar is not filled and then is empty */
5319: cptcovprod--;
5320: cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
5321: Tvar[k]=atoi(stre); /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2 */
5322: cptcovage++; /* Sums the number of covariates which include age as a product */
5323: Tage[cptcovage]=k; /* Tage[1] = 4 */
5324: /*printf("stre=%s ", stre);*/
5325: } else if (strcmp(strd,"age")==0) { /* or age*Vn */
5326: cptcovprod--;
5327: cutl(stre,strb,strc,'V');
5328: Tvar[k]=atoi(stre);
5329: cptcovage++;
5330: Tage[cptcovage]=k;
5331: } else { /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2 strb=V3*V2*/
5332: /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
5333: cptcovn++;
5334: cptcovprodnoage++;k1++;
5335: cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
5336: Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
5337: because this model-covariate is a construction we invent a new column
5338: ncovcol + k1
5339: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
5340: Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
5341: cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
5342: Tprod[k1]=k; /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 */
5343: Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
5344: Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
5345: k2=k2+2;
5346: Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
5347: Tvar[cptcovt+k2+1]=Tvard[k1][2]; /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
5348: for (i=1; i<=lastobs;i++){
5349: /* Computes the new covariate which is a product of
5350: covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
5351: covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
5352: }
5353: } /* End age is not in the model */
5354: } /* End if model includes a product */
5355: else { /* no more sum */
5356: /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
5357: /* scanf("%d",i);*/
5358: cutl(strd,strc,strb,'V');
5359: ks++; /**< Number of simple covariates */
5360: cptcovn++;
5361: Tvar[k]=atoi(strd);
5362: }
5363: strcpy(modelsav,stra); /* modelsav=V2+V1+V4 stra=V2+V1+V4 */
5364: /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
5365: scanf("%d",i);*/
5366: } /* end of loop + */
5367: } /* end model */
5368:
5369: /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
5370: If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
5371:
5372: /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
5373: printf("cptcovprod=%d ", cptcovprod);
5374: fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
5375:
5376: scanf("%d ",i);*/
5377:
5378:
5379: return (0); /* with covar[new additional covariate if product] and Tage if age */
5380: /*endread:*/
5381: printf("Exiting decodemodel: ");
5382: return (1);
5383: }
5384:
5385: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
5386: {
5387: int i, m;
5388:
5389: for (i=1; i<=imx; i++) {
5390: for(m=2; (m<= maxwav); m++) {
5391: if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
5392: anint[m][i]=9999;
5393: s[m][i]=-1;
5394: }
5395: if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
5396: *nberr = *nberr + 1;
5397: 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);
5398: 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);
5399: s[m][i]=-1;
5400: }
5401: if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
5402: (*nberr)++;
5403: 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]);
5404: 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]);
5405: s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
5406: }
5407: }
5408: }
5409:
5410: for (i=1; i<=imx; i++) {
5411: agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
5412: for(m=firstpass; (m<= lastpass); m++){
5413: if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
5414: if (s[m][i] >= nlstate+1) {
5415: if(agedc[i]>0){
5416: if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
5417: agev[m][i]=agedc[i];
5418: /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
5419: }else {
5420: if ((int)andc[i]!=9999){
5421: nbwarn++;
5422: printf("Warning negative age at death: %ld line:%d\n",num[i],i);
5423: fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
5424: agev[m][i]=-1;
5425: }
5426: }
5427: } /* agedc > 0 */
5428: }
5429: else if(s[m][i] !=9){ /* Standard case, age in fractional
5430: years but with the precision of a month */
5431: agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
5432: if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
5433: agev[m][i]=1;
5434: else if(agev[m][i] < *agemin){
5435: *agemin=agev[m][i];
5436: printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
5437: }
5438: else if(agev[m][i] >*agemax){
5439: *agemax=agev[m][i];
5440: /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
5441: }
5442: /*agev[m][i]=anint[m][i]-annais[i];*/
5443: /* agev[m][i] = age[i]+2*m;*/
5444: }
5445: else { /* =9 */
5446: agev[m][i]=1;
5447: s[m][i]=-1;
5448: }
5449: }
5450: else /*= 0 Unknown */
5451: agev[m][i]=1;
5452: }
5453:
5454: }
5455: for (i=1; i<=imx; i++) {
5456: for(m=firstpass; (m<=lastpass); m++){
5457: if (s[m][i] > (nlstate+ndeath)) {
5458: (*nberr)++;
5459: 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);
5460: 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);
5461: return 1;
5462: }
5463: }
5464: }
5465:
5466: /*for (i=1; i<=imx; i++){
5467: for (m=firstpass; (m<lastpass); m++){
5468: printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
5469: }
5470:
5471: }*/
5472:
5473:
5474: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
5475: fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
5476:
5477: return (0);
5478: /* endread:*/
5479: printf("Exiting calandcheckages: ");
5480: return (1);
5481: }
5482:
5483: #if defined(_MSC_VER)
5484: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
5485: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
5486: //#include "stdafx.h"
5487: //#include <stdio.h>
5488: //#include <tchar.h>
5489: //#include <windows.h>
5490: //#include <iostream>
5491: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
5492:
5493: LPFN_ISWOW64PROCESS fnIsWow64Process;
5494:
5495: BOOL IsWow64()
5496: {
5497: BOOL bIsWow64 = FALSE;
5498:
5499: //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
5500: // (HANDLE, PBOOL);
5501:
5502: //LPFN_ISWOW64PROCESS fnIsWow64Process;
5503:
5504: HMODULE module = GetModuleHandle(_T("kernel32"));
5505: const char funcName[] = "IsWow64Process";
5506: fnIsWow64Process = (LPFN_ISWOW64PROCESS)
5507: GetProcAddress(module, funcName);
5508:
5509: if (NULL != fnIsWow64Process)
5510: {
5511: if (!fnIsWow64Process(GetCurrentProcess(),
5512: &bIsWow64))
5513: //throw std::exception("Unknown error");
5514: printf("Unknown error\n");
5515: }
5516: return bIsWow64 != FALSE;
5517: }
5518: #endif
5519:
5520: void syscompilerinfo()
5521: {
5522: /* #include "syscompilerinfo.h"*/
5523:
5524: #if defined __INTEL_COMPILER
5525: #if defined(__GNUC__)
5526: struct utsname sysInfo; /* For Intel on Linux and OS/X */
5527: #endif
5528: #elif defined(__GNUC__)
5529: #ifndef __APPLE__
5530: #include <gnu/libc-version.h> /* Only on gnu */
5531: #endif
5532: struct utsname sysInfo;
5533: int cross = CROSS;
5534: if (cross){
5535: printf("Cross-");
5536: fprintf(ficlog, "Cross-");
5537: }
5538: #endif
5539:
5540: #include <stdint.h>
5541:
5542: printf("Compiled with:");fprintf(ficlog,"Compiled with:");
5543: #if defined(__clang__)
5544: printf(" Clang/LLVM");fprintf(ficlog," Clang/LLVM"); /* Clang/LLVM. ---------------------------------------------- */
5545: #endif
5546: #if defined(__ICC) || defined(__INTEL_COMPILER)
5547: printf(" Intel ICC/ICPC");fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
5548: #endif
5549: #if defined(__GNUC__) || defined(__GNUG__)
5550: printf(" GNU GCC/G++");fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
5551: #endif
5552: #if defined(__HP_cc) || defined(__HP_aCC)
5553: printf(" Hewlett-Packard C/aC++");fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
5554: #endif
5555: #if defined(__IBMC__) || defined(__IBMCPP__)
5556: printf(" IBM XL C/C++"); fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
5557: #endif
5558: #if defined(_MSC_VER)
5559: printf(" Microsoft Visual Studio");fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
5560: #endif
5561: #if defined(__PGI)
5562: printf(" Portland Group PGCC/PGCPP");fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
5563: #endif
5564: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
5565: printf(" Oracle Solaris Studio");fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
5566: #endif
5567: printf(" for ");fprintf(ficlog," for ");
5568:
5569: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
5570: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
5571: // Windows (x64 and x86)
5572: printf("Windows (x64 and x86) ");fprintf(ficlog,"Windows (x64 and x86) ");
5573: #elif __unix__ // all unices, not all compilers
5574: // Unix
5575: printf("Unix ");fprintf(ficlog,"Unix ");
5576: #elif __linux__
5577: // linux
5578: printf("linux ");fprintf(ficlog,"linux ");
5579: #elif __APPLE__
5580: // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
5581: printf("Mac OS ");fprintf(ficlog,"Mac OS ");
5582: #endif
5583:
5584: /* __MINGW32__ */
5585: /* __CYGWIN__ */
5586: /* __MINGW64__ */
5587: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
5588: /* _MSC_VER //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /? */
5589: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
5590: /* _WIN64 // Defined for applications for Win64. */
5591: /* _M_X64 // Defined for compilations that target x64 processors. */
5592: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
5593:
5594: #if UINTPTR_MAX == 0xffffffff
5595: printf(" 32-bit"); fprintf(ficlog," 32-bit");/* 32-bit */
5596: #elif UINTPTR_MAX == 0xffffffffffffffff
5597: printf(" 64-bit"); fprintf(ficlog," 64-bit");/* 64-bit */
5598: #else
5599: printf(" wtf-bit"); fprintf(ficlog," wtf-bit");/* wtf */
5600: #endif
5601:
5602: #if defined(__GNUC__)
5603: # if defined(__GNUC_PATCHLEVEL__)
5604: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
5605: + __GNUC_MINOR__ * 100 \
5606: + __GNUC_PATCHLEVEL__)
5607: # else
5608: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
5609: + __GNUC_MINOR__ * 100)
5610: # endif
5611: printf(" using GNU C version %d.\n", __GNUC_VERSION__);
5612: fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
5613:
5614: if (uname(&sysInfo) != -1) {
5615: printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
5616: fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
5617: }
5618: else
5619: perror("uname() error");
5620: //#ifndef __INTEL_COMPILER
5621: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
5622: printf("GNU libc version: %s\n", gnu_get_libc_version());
5623: fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
5624: #endif
5625: #endif
5626:
5627: // void main()
5628: // {
5629: #if defined(_MSC_VER)
5630: if (IsWow64()){
5631: printf("The program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
5632: fprintf(ficlog, "The program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
5633: }
5634: else{
5635: printf("The process is not running under WOW64 (i.e probably on a 64bit Windows).\n");
5636: fprintf(ficlog,"The programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
5637: }
5638: // printf("\nPress Enter to continue...");
5639: // getchar();
5640: // }
5641:
5642: #endif
5643:
5644:
5645: }
5646:
5647: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar){
5648: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
5649: int i, j, k, i1 ;
5650: double ftolpl = 1.e-10;
5651: double age, agebase, agelim;
5652:
5653: strcpy(filerespl,"pl");
5654: strcat(filerespl,fileres);
5655: if((ficrespl=fopen(filerespl,"w"))==NULL) {
5656: printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
5657: fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
5658: }
5659: printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
5660: fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
5661: pstamp(ficrespl);
5662: fprintf(ficrespl,"# Period (stable) prevalence \n");
5663: fprintf(ficrespl,"#Age ");
5664: for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
5665: fprintf(ficrespl,"\n");
5666:
5667: /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
5668:
5669: agebase=ageminpar;
5670: agelim=agemaxpar;
5671:
5672: i1=pow(2,cptcoveff);
5673: if (cptcovn < 1){i1=1;}
5674:
5675: for(cptcov=1,k=0;cptcov<=i1;cptcov++){
5676: /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
5677: //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
5678: k=k+1;
5679: /* to clean */
5680: //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtab[cptcod][cptcov]);
5681: fprintf(ficrespl,"\n#******");
5682: printf("\n#******");
5683: fprintf(ficlog,"\n#******");
5684: for(j=1;j<=cptcoveff;j++) {
5685: fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5686: printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5687: fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5688: }
5689: fprintf(ficrespl,"******\n");
5690: printf("******\n");
5691: fprintf(ficlog,"******\n");
5692:
5693: fprintf(ficrespl,"#Age ");
5694: for(j=1;j<=cptcoveff;j++) {
5695: fprintf(ficrespl,"V%d %d",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5696: }
5697: for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
5698: fprintf(ficrespl,"\n");
5699:
5700: for (age=agebase; age<=agelim; age++){
5701: /* for (age=agebase; age<=agebase; age++){ */
5702: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
5703: fprintf(ficrespl,"%.0f ",age );
5704: for(j=1;j<=cptcoveff;j++)
5705: fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5706: for(i=1; i<=nlstate;i++)
5707: fprintf(ficrespl," %.5f", prlim[i][i]);
5708: fprintf(ficrespl,"\n");
5709: } /* Age */
5710: /* was end of cptcod */
5711: } /* cptcov */
5712: }
5713:
5714: int hPijx(double *p, int bage, int fage){
5715: /*------------- h Pij x at various ages ------------*/
5716:
5717: int stepsize;
5718: int agelim;
5719: int hstepm;
5720: int nhstepm;
5721: int h, i, i1, j, k;
5722:
5723: double agedeb;
5724: double ***p3mat;
5725:
5726: strcpy(filerespij,"pij"); strcat(filerespij,fileres);
5727: if((ficrespij=fopen(filerespij,"w"))==NULL) {
5728: printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
5729: fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
5730: }
5731: printf("Computing pij: result on file '%s' \n", filerespij);
5732: fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
5733:
5734: stepsize=(int) (stepm+YEARM-1)/YEARM;
5735: /*if (stepm<=24) stepsize=2;*/
5736:
5737: agelim=AGESUP;
5738: hstepm=stepsize*YEARM; /* Every year of age */
5739: hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
5740:
5741: /* hstepm=1; aff par mois*/
5742: pstamp(ficrespij);
5743: fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
5744: i1= pow(2,cptcoveff);
5745: for(cptcov=1,k=0;cptcov<=i1;cptcov++){
5746: /*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
5747: k=k+1;
5748: /* for (k=1; k <= (int) pow(2,cptcoveff); k++){*/
5749: fprintf(ficrespij,"\n#****** ");
5750: for(j=1;j<=cptcoveff;j++)
5751: fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5752: fprintf(ficrespij,"******\n");
5753:
5754: for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
5755: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
5756: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
5757:
5758: /* nhstepm=nhstepm*YEARM; aff par mois*/
5759:
5760: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5761: oldm=oldms;savm=savms;
5762: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
5763: fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
5764: for(i=1; i<=nlstate;i++)
5765: for(j=1; j<=nlstate+ndeath;j++)
5766: fprintf(ficrespij," %1d-%1d",i,j);
5767: fprintf(ficrespij,"\n");
5768: for (h=0; h<=nhstepm; h++){
5769: /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
5770: fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
5771: for(i=1; i<=nlstate;i++)
5772: for(j=1; j<=nlstate+ndeath;j++)
5773: fprintf(ficrespij," %.5f", p3mat[i][j][h]);
5774: fprintf(ficrespij,"\n");
5775: }
5776: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5777: fprintf(ficrespij,"\n");
5778: }
5779: /*}*/
5780: }
5781: }
5782:
5783:
5784: /***********************************************/
5785: /**************** Main Program *****************/
5786: /***********************************************/
5787:
5788: int main(int argc, char *argv[])
5789: {
5790: #ifdef GSL
5791: const gsl_multimin_fminimizer_type *T;
5792: size_t iteri = 0, it;
5793: int rval = GSL_CONTINUE;
5794: int status = GSL_SUCCESS;
5795: double ssval;
5796: #endif
5797: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
5798: int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
5799:
5800: int jj, ll, li, lj, lk;
5801: int numlinepar=0; /* Current linenumber of parameter file */
5802: int itimes;
5803: int NDIM=2;
5804: int vpopbased=0;
5805:
5806: char ca[32], cb[32];
5807: /* FILE *fichtm; *//* Html File */
5808: /* FILE *ficgp;*/ /*Gnuplot File */
5809: struct stat info;
5810: double agedeb;
5811: double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
5812:
5813: double fret;
5814: double dum; /* Dummy variable */
5815: double ***p3mat;
5816: double ***mobaverage;
5817:
5818: char line[MAXLINE];
5819: char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
5820: char pathr[MAXLINE], pathimach[MAXLINE];
5821: char *tok, *val; /* pathtot */
5822: int firstobs=1, lastobs=10;
5823: int c, h , cpt;
5824: int jl;
5825: int i1, j1, jk, stepsize;
5826: int *tab;
5827: int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
5828: int mobilav=0,popforecast=0;
5829: int hstepm, nhstepm;
5830: int agemortsup;
5831: float sumlpop=0.;
5832: double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
5833: double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
5834:
5835: double bage=0, fage=110, age, agelim, agebase;
5836: double ftolpl=FTOL;
5837: double **prlim;
5838: double ***param; /* Matrix of parameters */
5839: double *p;
5840: double **matcov; /* Matrix of covariance */
5841: double ***delti3; /* Scale */
5842: double *delti; /* Scale */
5843: double ***eij, ***vareij;
5844: double **varpl; /* Variances of prevalence limits by age */
5845: double *epj, vepp;
5846:
5847: double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
5848: double **ximort;
5849: char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
5850: int *dcwave;
5851:
5852: char z[1]="c";
5853:
5854: /*char *strt;*/
5855: char strtend[80];
5856:
5857:
5858: /* setlocale (LC_ALL, ""); */
5859: /* bindtextdomain (PACKAGE, LOCALEDIR); */
5860: /* textdomain (PACKAGE); */
5861: /* setlocale (LC_CTYPE, ""); */
5862: /* setlocale (LC_MESSAGES, ""); */
5863:
5864: /* gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
5865: rstart_time = time(NULL);
5866: /* (void) gettimeofday(&start_time,&tzp);*/
5867: start_time = *localtime(&rstart_time);
5868: curr_time=start_time;
5869: /*tml = *localtime(&start_time.tm_sec);*/
5870: /* strcpy(strstart,asctime(&tml)); */
5871: strcpy(strstart,asctime(&start_time));
5872:
5873: /* printf("Localtime (at start)=%s",strstart); */
5874: /* tp.tm_sec = tp.tm_sec +86400; */
5875: /* tm = *localtime(&start_time.tm_sec); */
5876: /* tmg.tm_year=tmg.tm_year +dsign*dyear; */
5877: /* tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
5878: /* tmg.tm_hour=tmg.tm_hour + 1; */
5879: /* tp.tm_sec = mktime(&tmg); */
5880: /* strt=asctime(&tmg); */
5881: /* printf("Time(after) =%s",strstart); */
5882: /* (void) time (&time_value);
5883: * printf("time=%d,t-=%d\n",time_value,time_value-86400);
5884: * tm = *localtime(&time_value);
5885: * strstart=asctime(&tm);
5886: * printf("tim_value=%d,asctime=%s\n",time_value,strstart);
5887: */
5888:
5889: nberr=0; /* Number of errors and warnings */
5890: nbwarn=0;
5891: getcwd(pathcd, size);
5892:
5893: printf("\n%s\n%s",version,fullversion);
5894: if(argc <=1){
5895: printf("\nEnter the parameter file name: ");
5896: fgets(pathr,FILENAMELENGTH,stdin);
5897: i=strlen(pathr);
5898: if(pathr[i-1]=='\n')
5899: pathr[i-1]='\0';
5900: i=strlen(pathr);
5901: if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
5902: pathr[i-1]='\0';
5903: for (tok = pathr; tok != NULL; ){
5904: printf("Pathr |%s|\n",pathr);
5905: while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
5906: printf("val= |%s| pathr=%s\n",val,pathr);
5907: strcpy (pathtot, val);
5908: if(pathr[0] == '\0') break; /* Dirty */
5909: }
5910: }
5911: else{
5912: strcpy(pathtot,argv[1]);
5913: }
5914: /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
5915: /*cygwin_split_path(pathtot,path,optionfile);
5916: printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
5917: /* cutv(path,optionfile,pathtot,'\\');*/
5918:
5919: /* Split argv[0], imach program to get pathimach */
5920: printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
5921: split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
5922: printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
5923: /* strcpy(pathimach,argv[0]); */
5924: /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
5925: split(pathtot,path,optionfile,optionfilext,optionfilefiname);
5926: printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
5927: chdir(path); /* Can be a relative path */
5928: if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
5929: printf("Current directory %s!\n",pathcd);
5930: strcpy(command,"mkdir ");
5931: strcat(command,optionfilefiname);
5932: if((outcmd=system(command)) != 0){
5933: printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
5934: /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
5935: /* fclose(ficlog); */
5936: /* exit(1); */
5937: }
5938: /* if((imk=mkdir(optionfilefiname))<0){ */
5939: /* perror("mkdir"); */
5940: /* } */
5941:
5942: /*-------- arguments in the command line --------*/
5943:
5944: /* Log file */
5945: strcat(filelog, optionfilefiname);
5946: strcat(filelog,".log"); /* */
5947: if((ficlog=fopen(filelog,"w"))==NULL) {
5948: printf("Problem with logfile %s\n",filelog);
5949: goto end;
5950: }
5951: fprintf(ficlog,"Log filename:%s\n",filelog);
5952: fprintf(ficlog,"\n%s\n%s",version,fullversion);
5953: fprintf(ficlog,"\nEnter the parameter file name: \n");
5954: fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
5955: path=%s \n\
5956: optionfile=%s\n\
5957: optionfilext=%s\n\
5958: optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
5959:
5960: syscompilerinfo();
5961:
5962: printf("Local time (at start):%s",strstart);
5963: fprintf(ficlog,"Local time (at start): %s",strstart);
5964: fflush(ficlog);
5965: /* (void) gettimeofday(&curr_time,&tzp); */
5966: /* printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
5967:
5968: /* */
5969: strcpy(fileres,"r");
5970: strcat(fileres, optionfilefiname);
5971: strcat(fileres,".txt"); /* Other files have txt extension */
5972:
5973: /*---------arguments file --------*/
5974:
5975: if((ficpar=fopen(optionfile,"r"))==NULL) {
5976: printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
5977: fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
5978: fflush(ficlog);
5979: /* goto end; */
5980: exit(70);
5981: }
5982:
5983:
5984:
5985: strcpy(filereso,"o");
5986: strcat(filereso,fileres);
5987: if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
5988: printf("Problem with Output resultfile: %s\n", filereso);
5989: fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
5990: fflush(ficlog);
5991: goto end;
5992: }
5993:
5994: /* Reads comments: lines beginning with '#' */
5995: numlinepar=0;
5996: while((c=getc(ficpar))=='#' && c!= EOF){
5997: ungetc(c,ficpar);
5998: fgets(line, MAXLINE, ficpar);
5999: numlinepar++;
6000: fputs(line,stdout);
6001: fputs(line,ficparo);
6002: fputs(line,ficlog);
6003: }
6004: ungetc(c,ficpar);
6005:
6006: 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);
6007: numlinepar++;
6008: 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);
6009: 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);
6010: 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);
6011: fflush(ficlog);
6012: while((c=getc(ficpar))=='#' && c!= EOF){
6013: ungetc(c,ficpar);
6014: fgets(line, MAXLINE, ficpar);
6015: numlinepar++;
6016: fputs(line, stdout);
6017: //puts(line);
6018: fputs(line,ficparo);
6019: fputs(line,ficlog);
6020: }
6021: ungetc(c,ficpar);
6022:
6023:
6024: covar=matrix(0,NCOVMAX,1,n); /**< used in readdata */
6025: cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
6026: /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
6027: v1+v2*age+v2*v3 makes cptcovn = 3
6028: */
6029: if (strlen(model)>1)
6030: 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*/
6031: else
6032: ncovmodel=2;
6033: nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
6034: nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
6035: npar= nforce*ncovmodel; /* Number of parameters like aij*/
6036: if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
6037: 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);
6038: 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);
6039: fflush(stdout);
6040: fclose (ficlog);
6041: goto end;
6042: }
6043: delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6044: delti=delti3[1][1];
6045: /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
6046: if(mle==-1){ /* Print a wizard for help writing covariance matrix */
6047: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
6048: printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
6049: fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
6050: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
6051: fclose (ficparo);
6052: fclose (ficlog);
6053: goto end;
6054: exit(0);
6055: }
6056: else if(mle==-3) {
6057: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
6058: printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
6059: fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
6060: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6061: matcov=matrix(1,npar,1,npar);
6062: }
6063: else{
6064: /* Read guessed parameters */
6065: /* Reads comments: lines beginning with '#' */
6066: while((c=getc(ficpar))=='#' && c!= EOF){
6067: ungetc(c,ficpar);
6068: fgets(line, MAXLINE, ficpar);
6069: numlinepar++;
6070: fputs(line,stdout);
6071: fputs(line,ficparo);
6072: fputs(line,ficlog);
6073: }
6074: ungetc(c,ficpar);
6075:
6076: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6077: for(i=1; i <=nlstate; i++){
6078: j=0;
6079: for(jj=1; jj <=nlstate+ndeath; jj++){
6080: if(jj==i) continue;
6081: j++;
6082: fscanf(ficpar,"%1d%1d",&i1,&j1);
6083: if ((i1 != i) && (j1 != j)){
6084: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
6085: It might be a problem of design; if ncovcol and the model are correct\n \
6086: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
6087: exit(1);
6088: }
6089: fprintf(ficparo,"%1d%1d",i1,j1);
6090: if(mle==1)
6091: printf("%1d%1d",i,j);
6092: fprintf(ficlog,"%1d%1d",i,j);
6093: for(k=1; k<=ncovmodel;k++){
6094: fscanf(ficpar," %lf",¶m[i][j][k]);
6095: if(mle==1){
6096: printf(" %lf",param[i][j][k]);
6097: fprintf(ficlog," %lf",param[i][j][k]);
6098: }
6099: else
6100: fprintf(ficlog," %lf",param[i][j][k]);
6101: fprintf(ficparo," %lf",param[i][j][k]);
6102: }
6103: fscanf(ficpar,"\n");
6104: numlinepar++;
6105: if(mle==1)
6106: printf("\n");
6107: fprintf(ficlog,"\n");
6108: fprintf(ficparo,"\n");
6109: }
6110: }
6111: fflush(ficlog);
6112:
6113: /* Reads scales values */
6114: p=param[1][1];
6115:
6116: /* Reads comments: lines beginning with '#' */
6117: while((c=getc(ficpar))=='#' && c!= EOF){
6118: ungetc(c,ficpar);
6119: fgets(line, MAXLINE, ficpar);
6120: numlinepar++;
6121: fputs(line,stdout);
6122: fputs(line,ficparo);
6123: fputs(line,ficlog);
6124: }
6125: ungetc(c,ficpar);
6126:
6127: for(i=1; i <=nlstate; i++){
6128: for(j=1; j <=nlstate+ndeath-1; j++){
6129: fscanf(ficpar,"%1d%1d",&i1,&j1);
6130: if ( (i1-i) * (j1-j) != 0){
6131: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
6132: exit(1);
6133: }
6134: printf("%1d%1d",i,j);
6135: fprintf(ficparo,"%1d%1d",i1,j1);
6136: fprintf(ficlog,"%1d%1d",i1,j1);
6137: for(k=1; k<=ncovmodel;k++){
6138: fscanf(ficpar,"%le",&delti3[i][j][k]);
6139: printf(" %le",delti3[i][j][k]);
6140: fprintf(ficparo," %le",delti3[i][j][k]);
6141: fprintf(ficlog," %le",delti3[i][j][k]);
6142: }
6143: fscanf(ficpar,"\n");
6144: numlinepar++;
6145: printf("\n");
6146: fprintf(ficparo,"\n");
6147: fprintf(ficlog,"\n");
6148: }
6149: }
6150: fflush(ficlog);
6151:
6152: /* Reads covariance matrix */
6153: delti=delti3[1][1];
6154:
6155:
6156: /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
6157:
6158: /* Reads comments: lines beginning with '#' */
6159: while((c=getc(ficpar))=='#' && c!= EOF){
6160: ungetc(c,ficpar);
6161: fgets(line, MAXLINE, ficpar);
6162: numlinepar++;
6163: fputs(line,stdout);
6164: fputs(line,ficparo);
6165: fputs(line,ficlog);
6166: }
6167: ungetc(c,ficpar);
6168:
6169: matcov=matrix(1,npar,1,npar);
6170: for(i=1; i <=npar; i++)
6171: for(j=1; j <=npar; j++) matcov[i][j]=0.;
6172:
6173: for(i=1; i <=npar; i++){
6174: fscanf(ficpar,"%s",str);
6175: if(mle==1)
6176: printf("%s",str);
6177: fprintf(ficlog,"%s",str);
6178: fprintf(ficparo,"%s",str);
6179: for(j=1; j <=i; j++){
6180: fscanf(ficpar," %le",&matcov[i][j]);
6181: if(mle==1){
6182: printf(" %.5le",matcov[i][j]);
6183: }
6184: fprintf(ficlog," %.5le",matcov[i][j]);
6185: fprintf(ficparo," %.5le",matcov[i][j]);
6186: }
6187: fscanf(ficpar,"\n");
6188: numlinepar++;
6189: if(mle==1)
6190: printf("\n");
6191: fprintf(ficlog,"\n");
6192: fprintf(ficparo,"\n");
6193: }
6194: for(i=1; i <=npar; i++)
6195: for(j=i+1;j<=npar;j++)
6196: matcov[i][j]=matcov[j][i];
6197:
6198: if(mle==1)
6199: printf("\n");
6200: fprintf(ficlog,"\n");
6201:
6202: fflush(ficlog);
6203:
6204: /*-------- Rewriting parameter file ----------*/
6205: strcpy(rfileres,"r"); /* "Rparameterfile */
6206: strcat(rfileres,optionfilefiname); /* Parameter file first name*/
6207: strcat(rfileres,"."); /* */
6208: strcat(rfileres,optionfilext); /* Other files have txt extension */
6209: if((ficres =fopen(rfileres,"w"))==NULL) {
6210: printf("Problem writing new parameter file: %s\n", fileres);goto end;
6211: fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
6212: }
6213: fprintf(ficres,"#%s\n",version);
6214: } /* End of mle != -3 */
6215:
6216:
6217: n= lastobs;
6218: num=lvector(1,n);
6219: moisnais=vector(1,n);
6220: annais=vector(1,n);
6221: moisdc=vector(1,n);
6222: andc=vector(1,n);
6223: agedc=vector(1,n);
6224: cod=ivector(1,n);
6225: weight=vector(1,n);
6226: for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
6227: mint=matrix(1,maxwav,1,n);
6228: anint=matrix(1,maxwav,1,n);
6229: s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */
6230: tab=ivector(1,NCOVMAX);
6231: ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
6232:
6233: /* Reads data from file datafile */
6234: if (readdata(datafile, firstobs, lastobs, &imx)==1)
6235: goto end;
6236:
6237: /* Calculation of the number of parameters from char model */
6238: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4
6239: k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
6240: k=3 V4 Tvar[k=3]= 4 (from V4)
6241: k=2 V1 Tvar[k=2]= 1 (from V1)
6242: k=1 Tvar[1]=2 (from V2)
6243: */
6244: Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
6245: /* V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs).
6246: For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4,
6247: Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
6248: */
6249: /* For model-covariate k tells which data-covariate to use but
6250: because this model-covariate is a construction we invent a new column
6251: ncovcol + k1
6252: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
6253: Tvar[3=V1*V4]=4+1 etc */
6254: Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
6255: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
6256: if V2+V1+V1*V4+age*V3+V3*V2 TProd[k1=2]=5 (V3*V2)
6257: */
6258: Tvaraff=ivector(1,NCOVMAX); /* Unclear */
6259: 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
6260: * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd.
6261: * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
6262: Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
6263: 4 covariates (3 plus signs)
6264: Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
6265: */
6266:
6267: if(decodemodel(model, lastobs) == 1)
6268: goto end;
6269:
6270: if((double)(lastobs-imx)/(double)imx > 1.10){
6271: nbwarn++;
6272: 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);
6273: 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);
6274: }
6275: /* if(mle==1){*/
6276: if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
6277: for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
6278: }
6279:
6280: /*-calculation of age at interview from date of interview and age at death -*/
6281: agev=matrix(1,maxwav,1,imx);
6282:
6283: if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
6284: goto end;
6285:
6286:
6287: agegomp=(int)agemin;
6288: free_vector(moisnais,1,n);
6289: free_vector(annais,1,n);
6290: /* free_matrix(mint,1,maxwav,1,n);
6291: free_matrix(anint,1,maxwav,1,n);*/
6292: free_vector(moisdc,1,n);
6293: free_vector(andc,1,n);
6294: /* */
6295:
6296: wav=ivector(1,imx);
6297: dh=imatrix(1,lastpass-firstpass+1,1,imx);
6298: bh=imatrix(1,lastpass-firstpass+1,1,imx);
6299: mw=imatrix(1,lastpass-firstpass+1,1,imx);
6300:
6301: /* Concatenates waves */
6302: concatwav(wav, dh, bh, mw, s, agedc, agev, firstpass, lastpass, imx, nlstate, stepm);
6303: /* */
6304:
6305: /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
6306:
6307: nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
6308: ncodemax[1]=1;
6309: Ndum =ivector(-1,NCOVMAX);
6310: if (ncovmodel > 2)
6311: tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
6312:
6313: codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
6314: /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
6315: h=0;
6316:
6317:
6318: /*if (cptcovn > 0) */
6319:
6320:
6321: m=pow(2,cptcoveff);
6322:
6323: for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
6324: 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 */
6325: for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
6326: for(cpt=1; cpt <=pow(2,k-1); cpt++){ /* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 */
6327: h++;
6328: if (h>m)
6329: h=1;
6330: /**< codtab(h,k) k = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
6331: * h 1 2 3 4
6332: *______________________________
6333: * 1 i=1 1 i=1 1 i=1 1 i=1 1
6334: * 2 2 1 1 1
6335: * 3 i=2 1 2 1 1
6336: * 4 2 2 1 1
6337: * 5 i=3 1 i=2 1 2 1
6338: * 6 2 1 2 1
6339: * 7 i=4 1 2 2 1
6340: * 8 2 2 2 1
6341: * 9 i=5 1 i=3 1 i=2 1 1
6342: * 10 2 1 1 1
6343: * 11 i=6 1 2 1 1
6344: * 12 2 2 1 1
6345: * 13 i=7 1 i=4 1 2 1
6346: * 14 2 1 2 1
6347: * 15 i=8 1 2 2 1
6348: * 16 2 2 2 1
6349: */
6350: codtab[h][k]=j;
6351: /*codtab[h][Tvar[k]]=j;*/
6352: 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]]);
6353: }
6354: }
6355: }
6356: }
6357: /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
6358: codtab[1][2]=1;codtab[2][2]=2; */
6359: /* for(i=1; i <=m ;i++){
6360: for(k=1; k <=cptcovn; k++){
6361: printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
6362: }
6363: printf("\n");
6364: }
6365: scanf("%d",i);*/
6366:
6367: free_ivector(Ndum,-1,NCOVMAX);
6368:
6369:
6370:
6371: /*------------ gnuplot -------------*/
6372: strcpy(optionfilegnuplot,optionfilefiname);
6373: if(mle==-3)
6374: strcat(optionfilegnuplot,"-mort");
6375: strcat(optionfilegnuplot,".gp");
6376:
6377: if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
6378: printf("Problem with file %s",optionfilegnuplot);
6379: }
6380: else{
6381: fprintf(ficgp,"\n# %s\n", version);
6382: fprintf(ficgp,"# %s\n", optionfilegnuplot);
6383: //fprintf(ficgp,"set missing 'NaNq'\n");
6384: fprintf(ficgp,"set datafile missing 'NaNq'\n");
6385: }
6386: /* fclose(ficgp);*/
6387: /*--------- index.htm --------*/
6388:
6389: strcpy(optionfilehtm,optionfilefiname); /* Main html file */
6390: if(mle==-3)
6391: strcat(optionfilehtm,"-mort");
6392: strcat(optionfilehtm,".htm");
6393: if((fichtm=fopen(optionfilehtm,"w"))==NULL) {
6394: printf("Problem with %s \n",optionfilehtm);
6395: exit(0);
6396: }
6397:
6398: strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
6399: strcat(optionfilehtmcov,"-cov.htm");
6400: if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL) {
6401: printf("Problem with %s \n",optionfilehtmcov), exit(0);
6402: }
6403: else{
6404: fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6405: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6406: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
6407: optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
6408: }
6409:
6410: fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6411: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6412: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
6413: \n\
6414: <hr size=\"2\" color=\"#EC5E5E\">\
6415: <ul><li><h4>Parameter files</h4>\n\
6416: - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
6417: - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
6418: - Log file of the run: <a href=\"%s\">%s</a><br>\n\
6419: - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
6420: - Date and time at start: %s</ul>\n",\
6421: optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
6422: optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
6423: fileres,fileres,\
6424: filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
6425: fflush(fichtm);
6426:
6427: strcpy(pathr,path);
6428: strcat(pathr,optionfilefiname);
6429: chdir(optionfilefiname); /* Move to directory named optionfile */
6430:
6431: /* Calculates basic frequencies. Computes observed prevalence at single age
6432: and prints on file fileres'p'. */
6433: freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
6434:
6435: fprintf(fichtm,"\n");
6436: fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
6437: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
6438: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
6439: imx,agemin,agemax,jmin,jmax,jmean);
6440: pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6441: oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6442: newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6443: savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6444: oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
6445:
6446:
6447: /* For Powell, parameters are in a vector p[] starting at p[1]
6448: so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
6449: p=param[1][1]; /* *(*(*(param +1)+1)+0) */
6450:
6451: globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
6452:
6453: if (mle==-3){
6454: ximort=matrix(1,NDIM,1,NDIM);
6455: /* ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
6456: cens=ivector(1,n);
6457: ageexmed=vector(1,n);
6458: agecens=vector(1,n);
6459: dcwave=ivector(1,n);
6460:
6461: for (i=1; i<=imx; i++){
6462: dcwave[i]=-1;
6463: for (m=firstpass; m<=lastpass; m++)
6464: if (s[m][i]>nlstate) {
6465: dcwave[i]=m;
6466: /* printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
6467: break;
6468: }
6469: }
6470:
6471: for (i=1; i<=imx; i++) {
6472: if (wav[i]>0){
6473: ageexmed[i]=agev[mw[1][i]][i];
6474: j=wav[i];
6475: agecens[i]=1.;
6476:
6477: if (ageexmed[i]> 1 && wav[i] > 0){
6478: agecens[i]=agev[mw[j][i]][i];
6479: cens[i]= 1;
6480: }else if (ageexmed[i]< 1)
6481: cens[i]= -1;
6482: if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
6483: cens[i]=0 ;
6484: }
6485: else cens[i]=-1;
6486: }
6487:
6488: for (i=1;i<=NDIM;i++) {
6489: for (j=1;j<=NDIM;j++)
6490: ximort[i][j]=(i == j ? 1.0 : 0.0);
6491: }
6492:
6493: /*p[1]=0.0268; p[NDIM]=0.083;*/
6494: /*printf("%lf %lf", p[1], p[2]);*/
6495:
6496:
6497: #ifdef GSL
6498: printf("GSL optimization\n"); fprintf(ficlog,"Powell\n");
6499: #else
6500: printf("Powell\n"); fprintf(ficlog,"Powell\n");
6501: #endif
6502: strcpy(filerespow,"pow-mort");
6503: strcat(filerespow,fileres);
6504: if((ficrespow=fopen(filerespow,"w"))==NULL) {
6505: printf("Problem with resultfile: %s\n", filerespow);
6506: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
6507: }
6508: #ifdef GSL
6509: fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
6510: #else
6511: fprintf(ficrespow,"# Powell\n# iter -2*LL");
6512: #endif
6513: /* for (i=1;i<=nlstate;i++)
6514: for(j=1;j<=nlstate+ndeath;j++)
6515: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
6516: */
6517: fprintf(ficrespow,"\n");
6518: #ifdef GSL
6519: /* gsl starts here */
6520: T = gsl_multimin_fminimizer_nmsimplex;
6521: gsl_multimin_fminimizer *sfm = NULL;
6522: gsl_vector *ss, *x;
6523: gsl_multimin_function minex_func;
6524:
6525: /* Initial vertex size vector */
6526: ss = gsl_vector_alloc (NDIM);
6527:
6528: if (ss == NULL){
6529: GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
6530: }
6531: /* Set all step sizes to 1 */
6532: gsl_vector_set_all (ss, 0.001);
6533:
6534: /* Starting point */
6535:
6536: x = gsl_vector_alloc (NDIM);
6537:
6538: if (x == NULL){
6539: gsl_vector_free(ss);
6540: GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
6541: }
6542:
6543: /* Initialize method and iterate */
6544: /* p[1]=0.0268; p[NDIM]=0.083; */
6545: /* gsl_vector_set(x, 0, 0.0268); */
6546: /* gsl_vector_set(x, 1, 0.083); */
6547: gsl_vector_set(x, 0, p[1]);
6548: gsl_vector_set(x, 1, p[2]);
6549:
6550: minex_func.f = &gompertz_f;
6551: minex_func.n = NDIM;
6552: minex_func.params = (void *)&p; /* ??? */
6553:
6554: sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
6555: gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
6556:
6557: printf("Iterations beginning .....\n\n");
6558: printf("Iter. # Intercept Slope -Log Likelihood Simplex size\n");
6559:
6560: iteri=0;
6561: while (rval == GSL_CONTINUE){
6562: iteri++;
6563: status = gsl_multimin_fminimizer_iterate(sfm);
6564:
6565: if (status) printf("error: %s\n", gsl_strerror (status));
6566: fflush(0);
6567:
6568: if (status)
6569: break;
6570:
6571: rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
6572: ssval = gsl_multimin_fminimizer_size (sfm);
6573:
6574: if (rval == GSL_SUCCESS)
6575: printf ("converged to a local maximum at\n");
6576:
6577: printf("%5d ", iteri);
6578: for (it = 0; it < NDIM; it++){
6579: printf ("%10.5f ", gsl_vector_get (sfm->x, it));
6580: }
6581: printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
6582: }
6583:
6584: printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
6585:
6586: gsl_vector_free(x); /* initial values */
6587: gsl_vector_free(ss); /* inital step size */
6588: for (it=0; it<NDIM; it++){
6589: p[it+1]=gsl_vector_get(sfm->x,it);
6590: fprintf(ficrespow," %.12lf", p[it]);
6591: }
6592: gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1) */
6593: #endif
6594: #ifdef POWELL
6595: powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
6596: #endif
6597: fclose(ficrespow);
6598:
6599: hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);
6600:
6601: for(i=1; i <=NDIM; i++)
6602: for(j=i+1;j<=NDIM;j++)
6603: matcov[i][j]=matcov[j][i];
6604:
6605: printf("\nCovariance matrix\n ");
6606: for(i=1; i <=NDIM; i++) {
6607: for(j=1;j<=NDIM;j++){
6608: printf("%f ",matcov[i][j]);
6609: }
6610: printf("\n ");
6611: }
6612:
6613: printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
6614: for (i=1;i<=NDIM;i++)
6615: printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
6616:
6617: lsurv=vector(1,AGESUP);
6618: lpop=vector(1,AGESUP);
6619: tpop=vector(1,AGESUP);
6620: lsurv[agegomp]=100000;
6621:
6622: for (k=agegomp;k<=AGESUP;k++) {
6623: agemortsup=k;
6624: if (p[1]*exp(p[2]*(k-agegomp))>1) break;
6625: }
6626:
6627: for (k=agegomp;k<agemortsup;k++)
6628: lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
6629:
6630: for (k=agegomp;k<agemortsup;k++){
6631: lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
6632: sumlpop=sumlpop+lpop[k];
6633: }
6634:
6635: tpop[agegomp]=sumlpop;
6636: for (k=agegomp;k<(agemortsup-3);k++){
6637: /* tpop[k+1]=2;*/
6638: tpop[k+1]=tpop[k]-lpop[k];
6639: }
6640:
6641:
6642: printf("\nAge lx qx dx Lx Tx e(x)\n");
6643: for (k=agegomp;k<(agemortsup-2);k++)
6644: 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]);
6645:
6646:
6647: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6648: printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6649:
6650: printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
6651: stepm, weightopt,\
6652: model,imx,p,matcov,agemortsup);
6653:
6654: free_vector(lsurv,1,AGESUP);
6655: free_vector(lpop,1,AGESUP);
6656: free_vector(tpop,1,AGESUP);
6657: #ifdef GSL
6658: free_ivector(cens,1,n);
6659: free_vector(agecens,1,n);
6660: free_ivector(dcwave,1,n);
6661: free_matrix(ximort,1,NDIM,1,NDIM);
6662: #endif
6663: } /* Endof if mle==-3 */
6664:
6665: else{ /* For mle >=1 */
6666: globpr=0;/* debug */
6667: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
6668: printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6669: for (k=1; k<=npar;k++)
6670: printf(" %d %8.5f",k,p[k]);
6671: printf("\n");
6672: globpr=1; /* to print the contributions */
6673: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
6674: printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6675: for (k=1; k<=npar;k++)
6676: printf(" %d %8.5f",k,p[k]);
6677: printf("\n");
6678: if(mle>=1){ /* Could be 1 or 2 */
6679: mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
6680: }
6681:
6682: /*--------- results files --------------*/
6683: 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);
6684:
6685:
6686: fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6687: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6688: fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6689: for(i=1,jk=1; i <=nlstate; i++){
6690: for(k=1; k <=(nlstate+ndeath); k++){
6691: if (k != i) {
6692: printf("%d%d ",i,k);
6693: fprintf(ficlog,"%d%d ",i,k);
6694: fprintf(ficres,"%1d%1d ",i,k);
6695: for(j=1; j <=ncovmodel; j++){
6696: printf("%lf ",p[jk]);
6697: fprintf(ficlog,"%lf ",p[jk]);
6698: fprintf(ficres,"%lf ",p[jk]);
6699: jk++;
6700: }
6701: printf("\n");
6702: fprintf(ficlog,"\n");
6703: fprintf(ficres,"\n");
6704: }
6705: }
6706: }
6707: if(mle!=0){
6708: /* Computing hessian and covariance matrix */
6709: ftolhess=ftol; /* Usually correct */
6710: hesscov(matcov, p, npar, delti, ftolhess, func);
6711: }
6712: fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
6713: printf("# Scales (for hessian or gradient estimation)\n");
6714: fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
6715: for(i=1,jk=1; i <=nlstate; i++){
6716: for(j=1; j <=nlstate+ndeath; j++){
6717: if (j!=i) {
6718: fprintf(ficres,"%1d%1d",i,j);
6719: printf("%1d%1d",i,j);
6720: fprintf(ficlog,"%1d%1d",i,j);
6721: for(k=1; k<=ncovmodel;k++){
6722: printf(" %.5e",delti[jk]);
6723: fprintf(ficlog," %.5e",delti[jk]);
6724: fprintf(ficres," %.5e",delti[jk]);
6725: jk++;
6726: }
6727: printf("\n");
6728: fprintf(ficlog,"\n");
6729: fprintf(ficres,"\n");
6730: }
6731: }
6732: }
6733:
6734: 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");
6735: if(mle>=1)
6736: 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");
6737: 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");
6738: /* # 121 Var(a12)\n\ */
6739: /* # 122 Cov(b12,a12) Var(b12)\n\ */
6740: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
6741: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
6742: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
6743: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
6744: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
6745: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
6746:
6747:
6748: /* Just to have a covariance matrix which will be more understandable
6749: even is we still don't want to manage dictionary of variables
6750: */
6751: for(itimes=1;itimes<=2;itimes++){
6752: jj=0;
6753: for(i=1; i <=nlstate; i++){
6754: for(j=1; j <=nlstate+ndeath; j++){
6755: if(j==i) continue;
6756: for(k=1; k<=ncovmodel;k++){
6757: jj++;
6758: ca[0]= k+'a'-1;ca[1]='\0';
6759: if(itimes==1){
6760: if(mle>=1)
6761: printf("#%1d%1d%d",i,j,k);
6762: fprintf(ficlog,"#%1d%1d%d",i,j,k);
6763: fprintf(ficres,"#%1d%1d%d",i,j,k);
6764: }else{
6765: if(mle>=1)
6766: printf("%1d%1d%d",i,j,k);
6767: fprintf(ficlog,"%1d%1d%d",i,j,k);
6768: fprintf(ficres,"%1d%1d%d",i,j,k);
6769: }
6770: ll=0;
6771: for(li=1;li <=nlstate; li++){
6772: for(lj=1;lj <=nlstate+ndeath; lj++){
6773: if(lj==li) continue;
6774: for(lk=1;lk<=ncovmodel;lk++){
6775: ll++;
6776: if(ll<=jj){
6777: cb[0]= lk +'a'-1;cb[1]='\0';
6778: if(ll<jj){
6779: if(itimes==1){
6780: if(mle>=1)
6781: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6782: fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6783: fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6784: }else{
6785: if(mle>=1)
6786: printf(" %.5e",matcov[jj][ll]);
6787: fprintf(ficlog," %.5e",matcov[jj][ll]);
6788: fprintf(ficres," %.5e",matcov[jj][ll]);
6789: }
6790: }else{
6791: if(itimes==1){
6792: if(mle>=1)
6793: printf(" Var(%s%1d%1d)",ca,i,j);
6794: fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
6795: fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
6796: }else{
6797: if(mle>=1)
6798: printf(" %.5e",matcov[jj][ll]);
6799: fprintf(ficlog," %.5e",matcov[jj][ll]);
6800: fprintf(ficres," %.5e",matcov[jj][ll]);
6801: }
6802: }
6803: }
6804: } /* end lk */
6805: } /* end lj */
6806: } /* end li */
6807: if(mle>=1)
6808: printf("\n");
6809: fprintf(ficlog,"\n");
6810: fprintf(ficres,"\n");
6811: numlinepar++;
6812: } /* end k*/
6813: } /*end j */
6814: } /* end i */
6815: } /* end itimes */
6816:
6817: fflush(ficlog);
6818: fflush(ficres);
6819:
6820: while((c=getc(ficpar))=='#' && c!= EOF){
6821: ungetc(c,ficpar);
6822: fgets(line, MAXLINE, ficpar);
6823: fputs(line,stdout);
6824: fputs(line,ficparo);
6825: }
6826: ungetc(c,ficpar);
6827:
6828: estepm=0;
6829: fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
6830: if (estepm==0 || estepm < stepm) estepm=stepm;
6831: if (fage <= 2) {
6832: bage = ageminpar;
6833: fage = agemaxpar;
6834: }
6835:
6836: fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
6837: fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6838: fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6839:
6840: while((c=getc(ficpar))=='#' && c!= EOF){
6841: ungetc(c,ficpar);
6842: fgets(line, MAXLINE, ficpar);
6843: fputs(line,stdout);
6844: fputs(line,ficparo);
6845: }
6846: ungetc(c,ficpar);
6847:
6848: 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);
6849: 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);
6850: 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);
6851: printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
6852: 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);
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:
6863: dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
6864: dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
6865:
6866: fscanf(ficpar,"pop_based=%d\n",&popbased);
6867: fprintf(ficparo,"pop_based=%d\n",popbased);
6868: fprintf(ficres,"pop_based=%d\n",popbased);
6869:
6870: while((c=getc(ficpar))=='#' && c!= EOF){
6871: ungetc(c,ficpar);
6872: fgets(line, MAXLINE, ficpar);
6873: fputs(line,stdout);
6874: fputs(line,ficparo);
6875: }
6876: ungetc(c,ficpar);
6877:
6878: 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);
6879: 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);
6880: 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);
6881: 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);
6882: 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);
6883: /* day and month of proj2 are not used but only year anproj2.*/
6884:
6885:
6886:
6887: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
6888: /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
6889:
6890: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6891: printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6892:
6893: printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
6894: model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
6895: jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
6896:
6897: /*------------ free_vector -------------*/
6898: /* chdir(path); */
6899:
6900: free_ivector(wav,1,imx);
6901: free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
6902: free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
6903: free_imatrix(mw,1,lastpass-firstpass+1,1,imx);
6904: free_lvector(num,1,n);
6905: free_vector(agedc,1,n);
6906: /*free_matrix(covar,0,NCOVMAX,1,n);*/
6907: /*free_matrix(covar,1,NCOVMAX,1,n);*/
6908: fclose(ficparo);
6909: fclose(ficres);
6910:
6911:
6912: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
6913: /*#include "prevlim.h"*/ /* Use ficrespl, ficlog */
6914: prlim=matrix(1,nlstate,1,nlstate);
6915: prevalence_limit(p, prlim, ageminpar, agemaxpar);
6916: fclose(ficrespl);
6917:
6918: #ifdef FREEEXIT2
6919: #include "freeexit2.h"
6920: #endif
6921:
6922: /*------------- h Pij x at various ages ------------*/
6923: /*#include "hpijx.h"*/
6924: hPijx(p, bage, fage);
6925: fclose(ficrespij);
6926:
6927: /*-------------- Variance of one-step probabilities---*/
6928: k=1;
6929: varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
6930:
6931:
6932: probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
6933: for(i=1;i<=AGESUP;i++)
6934: for(j=1;j<=NCOVMAX;j++)
6935: for(k=1;k<=NCOVMAX;k++)
6936: probs[i][j][k]=0.;
6937:
6938: /*---------- Forecasting ------------------*/
6939: /*if((stepm == 1) && (strcmp(model,".")==0)){*/
6940: if(prevfcast==1){
6941: /* if(stepm ==1){*/
6942: prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
6943: /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
6944: /* } */
6945: /* else{ */
6946: /* erreur=108; */
6947: /* 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); */
6948: /* 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); */
6949: /* } */
6950: }
6951:
6952:
6953: /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
6954:
6955: prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
6956: /* 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",\
6957: ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
6958: */
6959:
6960: if (mobilav!=0) {
6961: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
6962: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
6963: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
6964: printf(" Error in movingaverage mobilav=%d\n",mobilav);
6965: }
6966: }
6967:
6968:
6969: /*---------- Health expectancies, no variances ------------*/
6970:
6971: strcpy(filerese,"e");
6972: strcat(filerese,fileres);
6973: if((ficreseij=fopen(filerese,"w"))==NULL) {
6974: printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
6975: fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
6976: }
6977: printf("Computing Health Expectancies: result on file '%s' \n", filerese);
6978: fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
6979: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
6980: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
6981:
6982: for (k=1; k <= (int) pow(2,cptcoveff); k++){
6983: fprintf(ficreseij,"\n#****** ");
6984: for(j=1;j<=cptcoveff;j++) {
6985: fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
6986: }
6987: fprintf(ficreseij,"******\n");
6988:
6989: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
6990: oldm=oldms;savm=savms;
6991: evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);
6992:
6993: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
6994: /*}*/
6995: }
6996: fclose(ficreseij);
6997:
6998:
6999: /*---------- Health expectancies and variances ------------*/
7000:
7001:
7002: strcpy(filerest,"t");
7003: strcat(filerest,fileres);
7004: if((ficrest=fopen(filerest,"w"))==NULL) {
7005: printf("Problem with total LE resultfile: %s\n", filerest);goto end;
7006: fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
7007: }
7008: printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
7009: fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
7010:
7011:
7012: strcpy(fileresstde,"stde");
7013: strcat(fileresstde,fileres);
7014: if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
7015: printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
7016: fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
7017: }
7018: printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
7019: fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
7020:
7021: strcpy(filerescve,"cve");
7022: strcat(filerescve,fileres);
7023: if((ficrescveij=fopen(filerescve,"w"))==NULL) {
7024: printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
7025: fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
7026: }
7027: printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
7028: fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
7029:
7030: strcpy(fileresv,"v");
7031: strcat(fileresv,fileres);
7032: if((ficresvij=fopen(fileresv,"w"))==NULL) {
7033: printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
7034: fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
7035: }
7036: printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
7037: fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
7038:
7039: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
7040: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
7041:
7042: for (k=1; k <= (int) pow(2,cptcoveff); k++){
7043: fprintf(ficrest,"\n#****** ");
7044: for(j=1;j<=cptcoveff;j++)
7045: fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7046: fprintf(ficrest,"******\n");
7047:
7048: fprintf(ficresstdeij,"\n#****** ");
7049: fprintf(ficrescveij,"\n#****** ");
7050: for(j=1;j<=cptcoveff;j++) {
7051: fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7052: fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7053: }
7054: fprintf(ficresstdeij,"******\n");
7055: fprintf(ficrescveij,"******\n");
7056:
7057: fprintf(ficresvij,"\n#****** ");
7058: for(j=1;j<=cptcoveff;j++)
7059: fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7060: fprintf(ficresvij,"******\n");
7061:
7062: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
7063: oldm=oldms;savm=savms;
7064: cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
7065: /*
7066: */
7067: /* goto endfree; */
7068:
7069: vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
7070: pstamp(ficrest);
7071:
7072:
7073: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
7074: oldm=oldms;savm=savms; /* Segmentation fault */
7075: cptcod= 0; /* To be deleted */
7076: 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 */
7077: 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 ");
7078: if(vpopbased==1)
7079: 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);
7080: else
7081: fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
7082: fprintf(ficrest,"# Age e.. (std) ");
7083: for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
7084: fprintf(ficrest,"\n");
7085:
7086: epj=vector(1,nlstate+1);
7087: for(age=bage; age <=fage ;age++){
7088: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
7089: if (vpopbased==1) {
7090: if(mobilav ==0){
7091: for(i=1; i<=nlstate;i++)
7092: prlim[i][i]=probs[(int)age][i][k];
7093: }else{ /* mobilav */
7094: for(i=1; i<=nlstate;i++)
7095: prlim[i][i]=mobaverage[(int)age][i][k];
7096: }
7097: }
7098:
7099: fprintf(ficrest," %4.0f",age);
7100: for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
7101: for(i=1, epj[j]=0.;i <=nlstate;i++) {
7102: epj[j] += prlim[i][i]*eij[i][j][(int)age];
7103: /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
7104: }
7105: epj[nlstate+1] +=epj[j];
7106: }
7107:
7108: for(i=1, vepp=0.;i <=nlstate;i++)
7109: for(j=1;j <=nlstate;j++)
7110: vepp += vareij[i][j][(int)age];
7111: fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
7112: for(j=1;j <=nlstate;j++){
7113: fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
7114: }
7115: fprintf(ficrest,"\n");
7116: }
7117: }
7118: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
7119: free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
7120: free_vector(epj,1,nlstate+1);
7121: /*}*/
7122: }
7123: free_vector(weight,1,n);
7124: free_imatrix(Tvard,1,NCOVMAX,1,2);
7125: free_imatrix(s,1,maxwav+1,1,n);
7126: free_matrix(anint,1,maxwav,1,n);
7127: free_matrix(mint,1,maxwav,1,n);
7128: free_ivector(cod,1,n);
7129: free_ivector(tab,1,NCOVMAX);
7130: fclose(ficresstdeij);
7131: fclose(ficrescveij);
7132: fclose(ficresvij);
7133: fclose(ficrest);
7134: fclose(ficpar);
7135:
7136: /*------- Variance of period (stable) prevalence------*/
7137:
7138: strcpy(fileresvpl,"vpl");
7139: strcat(fileresvpl,fileres);
7140: if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
7141: printf("Problem with variance of period (stable) prevalence resultfile: %s\n", fileresvpl);
7142: exit(0);
7143: }
7144: printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
7145:
7146: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
7147: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
7148:
7149: for (k=1; k <= (int) pow(2,cptcoveff); k++){
7150: fprintf(ficresvpl,"\n#****** ");
7151: for(j=1;j<=cptcoveff;j++)
7152: fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7153: fprintf(ficresvpl,"******\n");
7154:
7155: varpl=matrix(1,nlstate,(int) bage, (int) fage);
7156: oldm=oldms;savm=savms;
7157: varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
7158: free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
7159: /*}*/
7160: }
7161:
7162: fclose(ficresvpl);
7163:
7164: /*---------- End : free ----------------*/
7165: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
7166: free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
7167: } /* mle==-3 arrives here for freeing */
7168: /* endfree:*/
7169: free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
7170: free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
7171: free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
7172: free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
7173: free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
7174: free_matrix(covar,0,NCOVMAX,1,n);
7175: free_matrix(matcov,1,npar,1,npar);
7176: /*free_vector(delti,1,npar);*/
7177: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
7178: free_matrix(agev,1,maxwav,1,imx);
7179: free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
7180:
7181: free_ivector(ncodemax,1,NCOVMAX);
7182: free_ivector(Tvar,1,NCOVMAX);
7183: free_ivector(Tprod,1,NCOVMAX);
7184: free_ivector(Tvaraff,1,NCOVMAX);
7185: free_ivector(Tage,1,NCOVMAX);
7186:
7187: free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
7188: free_imatrix(codtab,1,100,1,10);
7189: fflush(fichtm);
7190: fflush(ficgp);
7191:
7192:
7193: if((nberr >0) || (nbwarn>0)){
7194: printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
7195: fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
7196: }else{
7197: printf("End of Imach\n");
7198: fprintf(ficlog,"End of Imach\n");
7199: }
7200: printf("See log file on %s\n",filelog);
7201: /* gettimeofday(&end_time, (struct timezone*)0);*/ /* after time */
7202: /*(void) gettimeofday(&end_time,&tzp);*/
7203: rend_time = time(NULL);
7204: end_time = *localtime(&rend_time);
7205: /* tml = *localtime(&end_time.tm_sec); */
7206: strcpy(strtend,asctime(&end_time));
7207: printf("Local time at start %s\nLocal time at end %s",strstart, strtend);
7208: fprintf(ficlog,"Local time at start %s\nLocal time at end %s\n",strstart, strtend);
7209: printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
7210:
7211: printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
7212: fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
7213: fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
7214: /* printf("Total time was %d uSec.\n", total_usecs);*/
7215: /* if(fileappend(fichtm,optionfilehtm)){ */
7216: fprintf(fichtm,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
7217: fclose(fichtm);
7218: fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
7219: fclose(fichtmcov);
7220: fclose(ficgp);
7221: fclose(ficlog);
7222: /*------ End -----------*/
7223:
7224:
7225: printf("Before Current directory %s!\n",pathcd);
7226: if(chdir(pathcd) != 0)
7227: printf("Can't move to directory %s!\n",path);
7228: if(getcwd(pathcd,MAXLINE) > 0)
7229: printf("Current directory %s!\n",pathcd);
7230: /*strcat(plotcmd,CHARSEPARATOR);*/
7231: sprintf(plotcmd,"gnuplot");
7232: #ifdef _WIN32
7233: sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
7234: #endif
7235: if(!stat(plotcmd,&info)){
7236: printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
7237: if(!stat(getenv("GNUPLOTBIN"),&info)){
7238: printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
7239: }else
7240: strcpy(pplotcmd,plotcmd);
7241: #ifdef __unix
7242: strcpy(plotcmd,GNUPLOTPROGRAM);
7243: if(!stat(plotcmd,&info)){
7244: printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
7245: }else
7246: strcpy(pplotcmd,plotcmd);
7247: #endif
7248: }else
7249: strcpy(pplotcmd,plotcmd);
7250:
7251: sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
7252: printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
7253:
7254: if((outcmd=system(plotcmd)) != 0){
7255: printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
7256: printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
7257: sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
7258: if((outcmd=system(plotcmd)) != 0)
7259: printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
7260: }
7261: printf(" Successful, please wait...");
7262: while (z[0] != 'q') {
7263: /* chdir(path); */
7264: printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
7265: scanf("%s",z);
7266: /* if (z[0] == 'c') system("./imach"); */
7267: if (z[0] == 'e') {
7268: #ifdef __APPLE__
7269: sprintf(pplotcmd, "open %s", optionfilehtm);
7270: #elif __linux
7271: sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
7272: #else
7273: sprintf(pplotcmd, "%s", optionfilehtm);
7274: #endif
7275: printf("Starting browser with: %s",pplotcmd);fflush(stdout);
7276: system(pplotcmd);
7277: }
7278: else if (z[0] == 'g') system(plotcmd);
7279: else if (z[0] == 'q') exit(0);
7280: }
7281: end:
7282: while (z[0] != 'q') {
7283: printf("\nType q for exiting: ");
7284: scanf("%s",z);
7285: }
7286: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>