1: /* $Id: imach.c,v 1.182 2015/02/12 08:19:57 brouard Exp $
2: $State: Exp $
3: $Log: imach.c,v $
4: Revision 1.182 2015/02/12 08:19:57 brouard
5: Summary: Trying to keep directest which seems simpler and more general
6: Author: Nicolas Brouard
7:
8: Revision 1.181 2015/02/11 23:22:24 brouard
9: Summary: Comments on Powell added
10:
11: Author:
12:
13: Revision 1.180 2015/02/11 17:33:45 brouard
14: Summary: Finishing move from main to function (hpijx and prevalence_limit)
15:
16: Revision 1.179 2015/01/04 09:57:06 brouard
17: Summary: back to OS/X
18:
19: Revision 1.178 2015/01/04 09:35:48 brouard
20: *** empty log message ***
21:
22: Revision 1.177 2015/01/03 18:40:56 brouard
23: Summary: Still testing ilc32 on OSX
24:
25: Revision 1.176 2015/01/03 16:45:04 brouard
26: *** empty log message ***
27:
28: Revision 1.175 2015/01/03 16:33:42 brouard
29: *** empty log message ***
30:
31: Revision 1.174 2015/01/03 16:15:49 brouard
32: Summary: Still in cross-compilation
33:
34: Revision 1.173 2015/01/03 12:06:26 brouard
35: Summary: trying to detect cross-compilation
36:
37: Revision 1.172 2014/12/27 12:07:47 brouard
38: Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
39:
40: Revision 1.171 2014/12/23 13:26:59 brouard
41: Summary: Back from Visual C
42:
43: Still problem with utsname.h on Windows
44:
45: Revision 1.170 2014/12/23 11:17:12 brouard
46: Summary: Cleaning some \%% back to %%
47:
48: The escape was mandatory for a specific compiler (which one?), but too many warnings.
49:
50: Revision 1.169 2014/12/22 23:08:31 brouard
51: Summary: 0.98p
52:
53: Outputs some informations on compiler used, OS etc. Testing on different platforms.
54:
55: Revision 1.168 2014/12/22 15:17:42 brouard
56: Summary: update
57:
58: Revision 1.167 2014/12/22 13:50:56 brouard
59: Summary: Testing uname and compiler version and if compiled 32 or 64
60:
61: Testing on Linux 64
62:
63: Revision 1.166 2014/12/22 11:40:47 brouard
64: *** empty log message ***
65:
66: Revision 1.165 2014/12/16 11:20:36 brouard
67: Summary: After compiling on Visual C
68:
69: * imach.c (Module): Merging 1.61 to 1.162
70:
71: Revision 1.164 2014/12/16 10:52:11 brouard
72: Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
73:
74: * imach.c (Module): Merging 1.61 to 1.162
75:
76: Revision 1.163 2014/12/16 10:30:11 brouard
77: * imach.c (Module): Merging 1.61 to 1.162
78:
79: Revision 1.162 2014/09/25 11:43:39 brouard
80: Summary: temporary backup 0.99!
81:
82: Revision 1.1 2014/09/16 11:06:58 brouard
83: Summary: With some code (wrong) for nlopt
84:
85: Author:
86:
87: Revision 1.161 2014/09/15 20:41:41 brouard
88: Summary: Problem with macro SQR on Intel compiler
89:
90: Revision 1.160 2014/09/02 09:24:05 brouard
91: *** empty log message ***
92:
93: Revision 1.159 2014/09/01 10:34:10 brouard
94: Summary: WIN32
95: Author: Brouard
96:
97: Revision 1.158 2014/08/27 17:11:51 brouard
98: *** empty log message ***
99:
100: Revision 1.157 2014/08/27 16:26:55 brouard
101: Summary: Preparing windows Visual studio version
102: Author: Brouard
103:
104: In order to compile on Visual studio, time.h is now correct and time_t
105: and tm struct should be used. difftime should be used but sometimes I
106: just make the differences in raw time format (time(&now).
107: Trying to suppress #ifdef LINUX
108: Add xdg-open for __linux in order to open default browser.
109:
110: Revision 1.156 2014/08/25 20:10:10 brouard
111: *** empty log message ***
112:
113: Revision 1.155 2014/08/25 18:32:34 brouard
114: Summary: New compile, minor changes
115: Author: Brouard
116:
117: Revision 1.154 2014/06/20 17:32:08 brouard
118: Summary: Outputs now all graphs of convergence to period prevalence
119:
120: Revision 1.153 2014/06/20 16:45:46 brouard
121: Summary: If 3 live state, convergence to period prevalence on same graph
122: Author: Brouard
123:
124: Revision 1.152 2014/06/18 17:54:09 brouard
125: Summary: open browser, use gnuplot on same dir than imach if not found in the path
126:
127: Revision 1.151 2014/06/18 16:43:30 brouard
128: *** empty log message ***
129:
130: Revision 1.150 2014/06/18 16:42:35 brouard
131: Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
132: Author: brouard
133:
134: Revision 1.149 2014/06/18 15:51:14 brouard
135: Summary: Some fixes in parameter files errors
136: Author: Nicolas Brouard
137:
138: Revision 1.148 2014/06/17 17:38:48 brouard
139: Summary: Nothing new
140: Author: Brouard
141:
142: Just a new packaging for OS/X version 0.98nS
143:
144: Revision 1.147 2014/06/16 10:33:11 brouard
145: *** empty log message ***
146:
147: Revision 1.146 2014/06/16 10:20:28 brouard
148: Summary: Merge
149: Author: Brouard
150:
151: Merge, before building revised version.
152:
153: Revision 1.145 2014/06/10 21:23:15 brouard
154: Summary: Debugging with valgrind
155: Author: Nicolas Brouard
156:
157: Lot of changes in order to output the results with some covariates
158: After the Edimburgh REVES conference 2014, it seems mandatory to
159: improve the code.
160: No more memory valgrind error but a lot has to be done in order to
161: continue the work of splitting the code into subroutines.
162: Also, decodemodel has been improved. Tricode is still not
163: optimal. nbcode should be improved. Documentation has been added in
164: the source code.
165:
166: Revision 1.143 2014/01/26 09:45:38 brouard
167: Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
168:
169: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
170: (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
171:
172: Revision 1.142 2014/01/26 03:57:36 brouard
173: Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
174:
175: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
176:
177: Revision 1.141 2014/01/26 02:42:01 brouard
178: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
179:
180: Revision 1.140 2011/09/02 10:37:54 brouard
181: Summary: times.h is ok with mingw32 now.
182:
183: Revision 1.139 2010/06/14 07:50:17 brouard
184: After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
185: I remember having already fixed agemin agemax which are pointers now but not cvs saved.
186:
187: Revision 1.138 2010/04/30 18:19:40 brouard
188: *** empty log message ***
189:
190: Revision 1.137 2010/04/29 18:11:38 brouard
191: (Module): Checking covariates for more complex models
192: than V1+V2. A lot of change to be done. Unstable.
193:
194: Revision 1.136 2010/04/26 20:30:53 brouard
195: (Module): merging some libgsl code. Fixing computation
196: of likelione (using inter/intrapolation if mle = 0) in order to
197: get same likelihood as if mle=1.
198: Some cleaning of code and comments added.
199:
200: Revision 1.135 2009/10/29 15:33:14 brouard
201: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
202:
203: Revision 1.134 2009/10/29 13:18:53 brouard
204: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
205:
206: Revision 1.133 2009/07/06 10:21:25 brouard
207: just nforces
208:
209: Revision 1.132 2009/07/06 08:22:05 brouard
210: Many tings
211:
212: Revision 1.131 2009/06/20 16:22:47 brouard
213: Some dimensions resccaled
214:
215: Revision 1.130 2009/05/26 06:44:34 brouard
216: (Module): Max Covariate is now set to 20 instead of 8. A
217: lot of cleaning with variables initialized to 0. Trying to make
218: V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
219:
220: Revision 1.129 2007/08/31 13:49:27 lievre
221: Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
222:
223: Revision 1.128 2006/06/30 13:02:05 brouard
224: (Module): Clarifications on computing e.j
225:
226: Revision 1.127 2006/04/28 18:11:50 brouard
227: (Module): Yes the sum of survivors was wrong since
228: imach-114 because nhstepm was no more computed in the age
229: loop. Now we define nhstepma in the age loop.
230: (Module): In order to speed up (in case of numerous covariates) we
231: compute health expectancies (without variances) in a first step
232: and then all the health expectancies with variances or standard
233: deviation (needs data from the Hessian matrices) which slows the
234: computation.
235: In the future we should be able to stop the program is only health
236: expectancies and graph are needed without standard deviations.
237:
238: Revision 1.126 2006/04/28 17:23:28 brouard
239: (Module): Yes the sum of survivors was wrong since
240: imach-114 because nhstepm was no more computed in the age
241: loop. Now we define nhstepma in the age loop.
242: Version 0.98h
243:
244: Revision 1.125 2006/04/04 15:20:31 lievre
245: Errors in calculation of health expectancies. Age was not initialized.
246: Forecasting file added.
247:
248: Revision 1.124 2006/03/22 17:13:53 lievre
249: Parameters are printed with %lf instead of %f (more numbers after the comma).
250: The log-likelihood is printed in the log file
251:
252: Revision 1.123 2006/03/20 10:52:43 brouard
253: * imach.c (Module): <title> changed, corresponds to .htm file
254: name. <head> headers where missing.
255:
256: * imach.c (Module): Weights can have a decimal point as for
257: English (a comma might work with a correct LC_NUMERIC environment,
258: otherwise the weight is truncated).
259: Modification of warning when the covariates values are not 0 or
260: 1.
261: Version 0.98g
262:
263: Revision 1.122 2006/03/20 09:45:41 brouard
264: (Module): Weights can have a decimal point as for
265: English (a comma might work with a correct LC_NUMERIC environment,
266: otherwise the weight is truncated).
267: Modification of warning when the covariates values are not 0 or
268: 1.
269: Version 0.98g
270:
271: Revision 1.121 2006/03/16 17:45:01 lievre
272: * imach.c (Module): Comments concerning covariates added
273:
274: * imach.c (Module): refinements in the computation of lli if
275: status=-2 in order to have more reliable computation if stepm is
276: not 1 month. Version 0.98f
277:
278: Revision 1.120 2006/03/16 15:10:38 lievre
279: (Module): refinements in the computation of lli if
280: status=-2 in order to have more reliable computation if stepm is
281: not 1 month. Version 0.98f
282:
283: Revision 1.119 2006/03/15 17:42:26 brouard
284: (Module): Bug if status = -2, the loglikelihood was
285: computed as likelihood omitting the logarithm. Version O.98e
286:
287: Revision 1.118 2006/03/14 18:20:07 brouard
288: (Module): varevsij Comments added explaining the second
289: table of variances if popbased=1 .
290: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
291: (Module): Function pstamp added
292: (Module): Version 0.98d
293:
294: Revision 1.117 2006/03/14 17:16:22 brouard
295: (Module): varevsij Comments added explaining the second
296: table of variances if popbased=1 .
297: (Module): Covariances of eij, ekl added, graphs fixed, new html link.
298: (Module): Function pstamp added
299: (Module): Version 0.98d
300:
301: Revision 1.116 2006/03/06 10:29:27 brouard
302: (Module): Variance-covariance wrong links and
303: varian-covariance of ej. is needed (Saito).
304:
305: Revision 1.115 2006/02/27 12:17:45 brouard
306: (Module): One freematrix added in mlikeli! 0.98c
307:
308: Revision 1.114 2006/02/26 12:57:58 brouard
309: (Module): Some improvements in processing parameter
310: filename with strsep.
311:
312: Revision 1.113 2006/02/24 14:20:24 brouard
313: (Module): Memory leaks checks with valgrind and:
314: datafile was not closed, some imatrix were not freed and on matrix
315: allocation too.
316:
317: Revision 1.112 2006/01/30 09:55:26 brouard
318: (Module): Back to gnuplot.exe instead of wgnuplot.exe
319:
320: Revision 1.111 2006/01/25 20:38:18 brouard
321: (Module): Lots of cleaning and bugs added (Gompertz)
322: (Module): Comments can be added in data file. Missing date values
323: can be a simple dot '.'.
324:
325: Revision 1.110 2006/01/25 00:51:50 brouard
326: (Module): Lots of cleaning and bugs added (Gompertz)
327:
328: Revision 1.109 2006/01/24 19:37:15 brouard
329: (Module): Comments (lines starting with a #) are allowed in data.
330:
331: Revision 1.108 2006/01/19 18:05:42 lievre
332: Gnuplot problem appeared...
333: To be fixed
334:
335: Revision 1.107 2006/01/19 16:20:37 brouard
336: Test existence of gnuplot in imach path
337:
338: Revision 1.106 2006/01/19 13:24:36 brouard
339: Some cleaning and links added in html output
340:
341: Revision 1.105 2006/01/05 20:23:19 lievre
342: *** empty log message ***
343:
344: Revision 1.104 2005/09/30 16:11:43 lievre
345: (Module): sump fixed, loop imx fixed, and simplifications.
346: (Module): If the status is missing at the last wave but we know
347: that the person is alive, then we can code his/her status as -2
348: (instead of missing=-1 in earlier versions) and his/her
349: contributions to the likelihood is 1 - Prob of dying from last
350: health status (= 1-p13= p11+p12 in the easiest case of somebody in
351: the healthy state at last known wave). Version is 0.98
352:
353: Revision 1.103 2005/09/30 15:54:49 lievre
354: (Module): sump fixed, loop imx fixed, and simplifications.
355:
356: Revision 1.102 2004/09/15 17:31:30 brouard
357: Add the possibility to read data file including tab characters.
358:
359: Revision 1.101 2004/09/15 10:38:38 brouard
360: Fix on curr_time
361:
362: Revision 1.100 2004/07/12 18:29:06 brouard
363: Add version for Mac OS X. Just define UNIX in Makefile
364:
365: Revision 1.99 2004/06/05 08:57:40 brouard
366: *** empty log message ***
367:
368: Revision 1.98 2004/05/16 15:05:56 brouard
369: New version 0.97 . First attempt to estimate force of mortality
370: directly from the data i.e. without the need of knowing the health
371: state at each age, but using a Gompertz model: log u =a + b*age .
372: This is the basic analysis of mortality and should be done before any
373: other analysis, in order to test if the mortality estimated from the
374: cross-longitudinal survey is different from the mortality estimated
375: from other sources like vital statistic data.
376:
377: The same imach parameter file can be used but the option for mle should be -3.
378:
379: Agnès, who wrote this part of the code, tried to keep most of the
380: former routines in order to include the new code within the former code.
381:
382: The output is very simple: only an estimate of the intercept and of
383: the slope with 95% confident intervals.
384:
385: Current limitations:
386: A) Even if you enter covariates, i.e. with the
387: model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
388: B) There is no computation of Life Expectancy nor Life Table.
389:
390: Revision 1.97 2004/02/20 13:25:42 lievre
391: Version 0.96d. Population forecasting command line is (temporarily)
392: suppressed.
393:
394: Revision 1.96 2003/07/15 15:38:55 brouard
395: * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
396: rewritten within the same printf. Workaround: many printfs.
397:
398: Revision 1.95 2003/07/08 07:54:34 brouard
399: * imach.c (Repository):
400: (Repository): Using imachwizard code to output a more meaningful covariance
401: matrix (cov(a12,c31) instead of numbers.
402:
403: Revision 1.94 2003/06/27 13:00:02 brouard
404: Just cleaning
405:
406: Revision 1.93 2003/06/25 16:33:55 brouard
407: (Module): On windows (cygwin) function asctime_r doesn't
408: exist so I changed back to asctime which exists.
409: (Module): Version 0.96b
410:
411: Revision 1.92 2003/06/25 16:30:45 brouard
412: (Module): On windows (cygwin) function asctime_r doesn't
413: exist so I changed back to asctime which exists.
414:
415: Revision 1.91 2003/06/25 15:30:29 brouard
416: * imach.c (Repository): Duplicated warning errors corrected.
417: (Repository): Elapsed time after each iteration is now output. It
418: helps to forecast when convergence will be reached. Elapsed time
419: is stamped in powell. We created a new html file for the graphs
420: concerning matrix of covariance. It has extension -cov.htm.
421:
422: Revision 1.90 2003/06/24 12:34:15 brouard
423: (Module): Some bugs corrected for windows. Also, when
424: mle=-1 a template is output in file "or"mypar.txt with the design
425: of the covariance matrix to be input.
426:
427: Revision 1.89 2003/06/24 12:30:52 brouard
428: (Module): Some bugs corrected for windows. Also, when
429: mle=-1 a template is output in file "or"mypar.txt with the design
430: of the covariance matrix to be input.
431:
432: Revision 1.88 2003/06/23 17:54:56 brouard
433: * 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.
434:
435: Revision 1.87 2003/06/18 12:26:01 brouard
436: Version 0.96
437:
438: Revision 1.86 2003/06/17 20:04:08 brouard
439: (Module): Change position of html and gnuplot routines and added
440: routine fileappend.
441:
442: Revision 1.85 2003/06/17 13:12:43 brouard
443: * imach.c (Repository): Check when date of death was earlier that
444: current date of interview. It may happen when the death was just
445: prior to the death. In this case, dh was negative and likelihood
446: was wrong (infinity). We still send an "Error" but patch by
447: assuming that the date of death was just one stepm after the
448: interview.
449: (Repository): Because some people have very long ID (first column)
450: we changed int to long in num[] and we added a new lvector for
451: memory allocation. But we also truncated to 8 characters (left
452: truncation)
453: (Repository): No more line truncation errors.
454:
455: Revision 1.84 2003/06/13 21:44:43 brouard
456: * imach.c (Repository): Replace "freqsummary" at a correct
457: place. It differs from routine "prevalence" which may be called
458: many times. Probs is memory consuming and must be used with
459: parcimony.
460: Version 0.95a3 (should output exactly the same maximization than 0.8a2)
461:
462: Revision 1.83 2003/06/10 13:39:11 lievre
463: *** empty log message ***
464:
465: Revision 1.82 2003/06/05 15:57:20 brouard
466: Add log in imach.c and fullversion number is now printed.
467:
468: */
469: /*
470: Interpolated Markov Chain
471:
472: Short summary of the programme:
473:
474: This program computes Healthy Life Expectancies from
475: cross-longitudinal data. Cross-longitudinal data consist in: -1- a
476: first survey ("cross") where individuals from different ages are
477: interviewed on their health status or degree of disability (in the
478: case of a health survey which is our main interest) -2- at least a
479: second wave of interviews ("longitudinal") which measure each change
480: (if any) in individual health status. Health expectancies are
481: computed from the time spent in each health state according to a
482: model. More health states you consider, more time is necessary to reach the
483: Maximum Likelihood of the parameters involved in the model. The
484: simplest model is the multinomial logistic model where pij is the
485: probability to be observed in state j at the second wave
486: conditional to be observed in state i at the first wave. Therefore
487: the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
488: 'age' is age and 'sex' is a covariate. If you want to have a more
489: complex model than "constant and age", you should modify the program
490: where the markup *Covariates have to be included here again* invites
491: you to do it. More covariates you add, slower the
492: convergence.
493:
494: The advantage of this computer programme, compared to a simple
495: multinomial logistic model, is clear when the delay between waves is not
496: identical for each individual. Also, if a individual missed an
497: intermediate interview, the information is lost, but taken into
498: account using an interpolation or extrapolation.
499:
500: hPijx is the probability to be observed in state i at age x+h
501: conditional to the observed state i at age x. The delay 'h' can be
502: split into an exact number (nh*stepm) of unobserved intermediate
503: states. This elementary transition (by month, quarter,
504: semester or year) is modelled as a multinomial logistic. The hPx
505: matrix is simply the matrix product of nh*stepm elementary matrices
506: and the contribution of each individual to the likelihood is simply
507: hPijx.
508:
509: Also this programme outputs the covariance matrix of the parameters but also
510: of the life expectancies. It also computes the period (stable) prevalence.
511:
512: Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
513: Institut national d'études démographiques, Paris.
514: This software have been partly granted by Euro-REVES, a concerted action
515: from the European Union.
516: It is copyrighted identically to a GNU software product, ie programme and
517: software can be distributed freely for non commercial use. Latest version
518: can be accessed at http://euroreves.ined.fr/imach .
519:
520: Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
521: or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
522:
523: **********************************************************************/
524: /*
525: main
526: read parameterfile
527: read datafile
528: concatwav
529: freqsummary
530: if (mle >= 1)
531: mlikeli
532: print results files
533: if mle==1
534: computes hessian
535: read end of parameter file: agemin, agemax, bage, fage, estepm
536: begin-prev-date,...
537: open gnuplot file
538: open html file
539: period (stable) prevalence | pl_nom 1-1 2-2 etc by covariate
540: for age prevalim() | #****** V1=0 V2=1 V3=1 V4=0 ******
541: | 65 1 0 2 1 3 1 4 0 0.96326 0.03674
542: freexexit2 possible for memory heap.
543:
544: h Pij x | pij_nom ficrestpij
545: # Cov Agex agex+h hpijx with i,j= 1-1 1-2 1-3 2-1 2-2 2-3
546: 1 85 85 1.00000 0.00000 0.00000 0.00000 1.00000 0.00000
547: 1 85 86 0.68299 0.22291 0.09410 0.71093 0.00000 0.28907
548:
549: 1 65 99 0.00364 0.00322 0.99314 0.00350 0.00310 0.99340
550: 1 65 100 0.00214 0.00204 0.99581 0.00206 0.00196 0.99597
551: variance of p one-step probabilities varprob | prob_nom ficresprob #One-step probabilities and stand. devi in ()
552: Standard deviation of one-step probabilities | probcor_nom ficresprobcor #One-step probabilities and correlation matrix
553: Matrix of variance covariance of one-step probabilities | probcov_nom ficresprobcov #One-step probabilities and covariance matrix
554:
555: forecasting if prevfcast==1 prevforecast call prevalence()
556: health expectancies
557: Variance-covariance of DFLE
558: prevalence()
559: movingaverage()
560: varevsij()
561: if popbased==1 varevsij(,popbased)
562: total life expectancies
563: Variance of period (stable) prevalence
564: end
565: */
566:
567: #define POWELL /* Instead of NLOPT */
568: #define POWELLDIRECT /* Directest to decide new direction instead of Powell test */
569:
570: #include <math.h>
571: #include <stdio.h>
572: #include <stdlib.h>
573: #include <string.h>
574:
575: #ifdef _WIN32
576: #include <io.h>
577: #include <windows.h>
578: #include <tchar.h>
579: #else
580: #include <unistd.h>
581: #endif
582:
583: #include <limits.h>
584: #include <sys/types.h>
585:
586: #if defined(__GNUC__)
587: #include <sys/utsname.h> /* Doesn't work on Windows */
588: #endif
589:
590: #include <sys/stat.h>
591: #include <errno.h>
592: /* extern int errno; */
593:
594: /* #ifdef LINUX */
595: /* #include <time.h> */
596: /* #include "timeval.h" */
597: /* #else */
598: /* #include <sys/time.h> */
599: /* #endif */
600:
601: #include <time.h>
602:
603: #ifdef GSL
604: #include <gsl/gsl_errno.h>
605: #include <gsl/gsl_multimin.h>
606: #endif
607:
608:
609: #ifdef NLOPT
610: #include <nlopt.h>
611: typedef struct {
612: double (* function)(double [] );
613: } myfunc_data ;
614: #endif
615:
616: /* #include <libintl.h> */
617: /* #define _(String) gettext (String) */
618:
619: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
620:
621: #define GNUPLOTPROGRAM "gnuplot"
622: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
623: #define FILENAMELENGTH 132
624:
625: #define GLOCK_ERROR_NOPATH -1 /* empty path */
626: #define GLOCK_ERROR_GETCWD -2 /* cannot get cwd */
627:
628: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
629: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
630:
631: #define NINTERVMAX 8
632: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
633: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
634: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
635: #define codtabm(h,k) 1 & (h-1) >> (k-1) ;
636: #define MAXN 20000
637: #define YEARM 12. /**< Number of months per year */
638: #define AGESUP 130
639: #define AGEBASE 40
640: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
641: #ifdef _WIN32
642: #define DIRSEPARATOR '\\'
643: #define CHARSEPARATOR "\\"
644: #define ODIRSEPARATOR '/'
645: #else
646: #define DIRSEPARATOR '/'
647: #define CHARSEPARATOR "/"
648: #define ODIRSEPARATOR '\\'
649: #endif
650:
651: /* $Id: imach.c,v 1.182 2015/02/12 08:19:57 brouard Exp $ */
652: /* $State: Exp $ */
653:
654: 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";
655: char fullversion[]="$Revision: 1.182 $ $Date: 2015/02/12 08:19:57 $";
656: char strstart[80];
657: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
658: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings */
659: int nvar=0, nforce=0; /* Number of variables, number of forces */
660: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
661: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
662: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
663: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
664: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
665: int cptcovprodnoage=0; /**< Number of covariate products without age */
666: int cptcoveff=0; /* Total number of covariates to vary for printing results */
667: int cptcov=0; /* Working variable */
668: int npar=NPARMAX;
669: int nlstate=2; /* Number of live states */
670: int ndeath=1; /* Number of dead states */
671: int ncovmodel=0, ncovcol=0; /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
672: int popbased=0;
673:
674: int *wav; /* Number of waves for this individuual 0 is possible */
675: int maxwav=0; /* Maxim number of waves */
676: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
677: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */
678: int gipmx=0, gsw=0; /* Global variables on the number of contributions
679: to the likelihood and the sum of weights (done by funcone)*/
680: int mle=1, weightopt=0;
681: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
682: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
683: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
684: * wave mi and wave mi+1 is not an exact multiple of stepm. */
685: int countcallfunc=0; /* Count the number of calls to func */
686: double jmean=1; /* Mean space between 2 waves */
687: double **matprod2(); /* test */
688: double **oldm, **newm, **savm; /* Working pointers to matrices */
689: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
690: /*FILE *fic ; */ /* Used in readdata only */
691: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
692: FILE *ficlog, *ficrespow;
693: int globpr=0; /* Global variable for printing or not */
694: double fretone; /* Only one call to likelihood */
695: long ipmx=0; /* Number of contributions */
696: double sw; /* Sum of weights */
697: char filerespow[FILENAMELENGTH];
698: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
699: FILE *ficresilk;
700: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
701: FILE *ficresprobmorprev;
702: FILE *fichtm, *fichtmcov; /* Html File */
703: FILE *ficreseij;
704: char filerese[FILENAMELENGTH];
705: FILE *ficresstdeij;
706: char fileresstde[FILENAMELENGTH];
707: FILE *ficrescveij;
708: char filerescve[FILENAMELENGTH];
709: FILE *ficresvij;
710: char fileresv[FILENAMELENGTH];
711: FILE *ficresvpl;
712: char fileresvpl[FILENAMELENGTH];
713: char title[MAXLINE];
714: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH], filerespl[FILENAMELENGTH];
715: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
716: char tmpout[FILENAMELENGTH], tmpout2[FILENAMELENGTH];
717: char command[FILENAMELENGTH];
718: int outcmd=0;
719:
720: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
721:
722: char filelog[FILENAMELENGTH]; /* Log file */
723: char filerest[FILENAMELENGTH];
724: char fileregp[FILENAMELENGTH];
725: char popfile[FILENAMELENGTH];
726:
727: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
728:
729: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
730: /* struct timezone tzp; */
731: /* extern int gettimeofday(); */
732: struct tm tml, *gmtime(), *localtime();
733:
734: extern time_t time();
735:
736: struct tm start_time, end_time, curr_time, last_time, forecast_time;
737: time_t rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
738: struct tm tm;
739:
740: char strcurr[80], strfor[80];
741:
742: char *endptr;
743: long lval;
744: double dval;
745:
746: #define NR_END 1
747: #define FREE_ARG char*
748: #define FTOL 1.0e-10
749:
750: #define NRANSI
751: #define ITMAX 200
752:
753: #define TOL 2.0e-4
754:
755: #define CGOLD 0.3819660
756: #define ZEPS 1.0e-10
757: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
758:
759: #define GOLD 1.618034
760: #define GLIMIT 100.0
761: #define TINY 1.0e-20
762:
763: static double maxarg1,maxarg2;
764: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
765: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
766:
767: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
768: #define rint(a) floor(a+0.5)
769: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
770: /* #define mytinydouble 1.0e-16 */
771: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
772: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
773: /* static double dsqrarg; */
774: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
775: static double sqrarg;
776: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
777: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;}
778: int agegomp= AGEGOMP;
779:
780: int imx;
781: int stepm=1;
782: /* Stepm, step in month: minimum step interpolation*/
783:
784: int estepm;
785: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
786:
787: int m,nb;
788: long *num;
789: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
790: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
791: double **pmmij, ***probs;
792: double *ageexmed,*agecens;
793: double dateintmean=0;
794:
795: double *weight;
796: int **s; /* Status */
797: double *agedc;
798: double **covar; /**< covar[j,i], value of jth covariate for individual i,
799: * covar=matrix(0,NCOVMAX,1,n);
800: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; */
801: double idx;
802: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
803: int *Ndum; /** Freq of modality (tricode */
804: int **codtab; /**< codtab=imatrix(1,100,1,10); */
805: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
806: double *lsurv, *lpop, *tpop;
807:
808: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
809: double ftolhess; /**< Tolerance for computing hessian */
810:
811: /**************** split *************************/
812: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
813: {
814: /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
815: the name of the file (name), its extension only (ext) and its first part of the name (finame)
816: */
817: char *ss; /* pointer */
818: int l1, l2; /* length counters */
819:
820: l1 = strlen(path ); /* length of path */
821: if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
822: ss= strrchr( path, DIRSEPARATOR ); /* find last / */
823: if ( ss == NULL ) { /* no directory, so determine current directory */
824: strcpy( name, path ); /* we got the fullname name because no directory */
825: /*if(strrchr(path, ODIRSEPARATOR )==NULL)
826: printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
827: /* get current working directory */
828: /* extern char* getcwd ( char *buf , int len);*/
829: if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
830: return( GLOCK_ERROR_GETCWD );
831: }
832: /* got dirc from getcwd*/
833: printf(" DIRC = %s \n",dirc);
834: } else { /* strip direcotry from path */
835: ss++; /* after this, the filename */
836: l2 = strlen( ss ); /* length of filename */
837: if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
838: strcpy( name, ss ); /* save file name */
839: strncpy( dirc, path, l1 - l2 ); /* now the directory */
840: dirc[l1-l2] = 0; /* add zero */
841: printf(" DIRC2 = %s \n",dirc);
842: }
843: /* We add a separator at the end of dirc if not exists */
844: l1 = strlen( dirc ); /* length of directory */
845: if( dirc[l1-1] != DIRSEPARATOR ){
846: dirc[l1] = DIRSEPARATOR;
847: dirc[l1+1] = 0;
848: printf(" DIRC3 = %s \n",dirc);
849: }
850: ss = strrchr( name, '.' ); /* find last / */
851: if (ss >0){
852: ss++;
853: strcpy(ext,ss); /* save extension */
854: l1= strlen( name);
855: l2= strlen(ss)+1;
856: strncpy( finame, name, l1-l2);
857: finame[l1-l2]= 0;
858: }
859:
860: return( 0 ); /* we're done */
861: }
862:
863:
864: /******************************************/
865:
866: void replace_back_to_slash(char *s, char*t)
867: {
868: int i;
869: int lg=0;
870: i=0;
871: lg=strlen(t);
872: for(i=0; i<= lg; i++) {
873: (s[i] = t[i]);
874: if (t[i]== '\\') s[i]='/';
875: }
876: }
877:
878: char *trimbb(char *out, char *in)
879: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
880: char *s;
881: s=out;
882: while (*in != '\0'){
883: while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
884: in++;
885: }
886: *out++ = *in++;
887: }
888: *out='\0';
889: return s;
890: }
891:
892: char *cutl(char *blocc, char *alocc, char *in, char occ)
893: {
894: /* cuts string in into blocc and alocc where blocc ends before first occurence of char 'occ'
895: and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
896: gives blocc="abcdef2ghi" and alocc="j".
897: If occ is not found blocc is null and alocc is equal to in. Returns blocc
898: */
899: char *s, *t;
900: t=in;s=in;
901: while ((*in != occ) && (*in != '\0')){
902: *alocc++ = *in++;
903: }
904: if( *in == occ){
905: *(alocc)='\0';
906: s=++in;
907: }
908:
909: if (s == t) {/* occ not found */
910: *(alocc-(in-s))='\0';
911: in=s;
912: }
913: while ( *in != '\0'){
914: *blocc++ = *in++;
915: }
916:
917: *blocc='\0';
918: return t;
919: }
920: char *cutv(char *blocc, char *alocc, char *in, char occ)
921: {
922: /* cuts string in into blocc and alocc where blocc ends before last occurence of char 'occ'
923: and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
924: gives blocc="abcdef2ghi" and alocc="j".
925: If occ is not found blocc is null and alocc is equal to in. Returns alocc
926: */
927: char *s, *t;
928: t=in;s=in;
929: while (*in != '\0'){
930: while( *in == occ){
931: *blocc++ = *in++;
932: s=in;
933: }
934: *blocc++ = *in++;
935: }
936: if (s == t) /* occ not found */
937: *(blocc-(in-s))='\0';
938: else
939: *(blocc-(in-s)-1)='\0';
940: in=s;
941: while ( *in != '\0'){
942: *alocc++ = *in++;
943: }
944:
945: *alocc='\0';
946: return s;
947: }
948:
949: int nbocc(char *s, char occ)
950: {
951: int i,j=0;
952: int lg=20;
953: i=0;
954: lg=strlen(s);
955: for(i=0; i<= lg; i++) {
956: if (s[i] == occ ) j++;
957: }
958: return j;
959: }
960:
961: /* void cutv(char *u,char *v, char*t, char occ) */
962: /* { */
963: /* /\* cuts string t into u and v where u ends before last occurence of char 'occ' */
964: /* and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
965: /* gives u="abcdef2ghi" and v="j" *\/ */
966: /* int i,lg,j,p=0; */
967: /* i=0; */
968: /* lg=strlen(t); */
969: /* for(j=0; j<=lg-1; j++) { */
970: /* if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
971: /* } */
972:
973: /* for(j=0; j<p; j++) { */
974: /* (u[j] = t[j]); */
975: /* } */
976: /* u[p]='\0'; */
977:
978: /* for(j=0; j<= lg; j++) { */
979: /* if (j>=(p+1))(v[j-p-1] = t[j]); */
980: /* } */
981: /* } */
982:
983: #ifdef _WIN32
984: char * strsep(char **pp, const char *delim)
985: {
986: char *p, *q;
987:
988: if ((p = *pp) == NULL)
989: return 0;
990: if ((q = strpbrk (p, delim)) != NULL)
991: {
992: *pp = q + 1;
993: *q = '\0';
994: }
995: else
996: *pp = 0;
997: return p;
998: }
999: #endif
1000:
1001: /********************** nrerror ********************/
1002:
1003: void nrerror(char error_text[])
1004: {
1005: fprintf(stderr,"ERREUR ...\n");
1006: fprintf(stderr,"%s\n",error_text);
1007: exit(EXIT_FAILURE);
1008: }
1009: /*********************** vector *******************/
1010: double *vector(int nl, int nh)
1011: {
1012: double *v;
1013: v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
1014: if (!v) nrerror("allocation failure in vector");
1015: return v-nl+NR_END;
1016: }
1017:
1018: /************************ free vector ******************/
1019: void free_vector(double*v, int nl, int nh)
1020: {
1021: free((FREE_ARG)(v+nl-NR_END));
1022: }
1023:
1024: /************************ivector *******************************/
1025: int *ivector(long nl,long nh)
1026: {
1027: int *v;
1028: v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
1029: if (!v) nrerror("allocation failure in ivector");
1030: return v-nl+NR_END;
1031: }
1032:
1033: /******************free ivector **************************/
1034: void free_ivector(int *v, long nl, long nh)
1035: {
1036: free((FREE_ARG)(v+nl-NR_END));
1037: }
1038:
1039: /************************lvector *******************************/
1040: long *lvector(long nl,long nh)
1041: {
1042: long *v;
1043: v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
1044: if (!v) nrerror("allocation failure in ivector");
1045: return v-nl+NR_END;
1046: }
1047:
1048: /******************free lvector **************************/
1049: void free_lvector(long *v, long nl, long nh)
1050: {
1051: free((FREE_ARG)(v+nl-NR_END));
1052: }
1053:
1054: /******************* imatrix *******************************/
1055: int **imatrix(long nrl, long nrh, long ncl, long nch)
1056: /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */
1057: {
1058: long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
1059: int **m;
1060:
1061: /* allocate pointers to rows */
1062: m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*)));
1063: if (!m) nrerror("allocation failure 1 in matrix()");
1064: m += NR_END;
1065: m -= nrl;
1066:
1067:
1068: /* allocate rows and set pointers to them */
1069: m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int)));
1070: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1071: m[nrl] += NR_END;
1072: m[nrl] -= ncl;
1073:
1074: for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;
1075:
1076: /* return pointer to array of pointers to rows */
1077: return m;
1078: }
1079:
1080: /****************** free_imatrix *************************/
1081: void free_imatrix(m,nrl,nrh,ncl,nch)
1082: int **m;
1083: long nch,ncl,nrh,nrl;
1084: /* free an int matrix allocated by imatrix() */
1085: {
1086: free((FREE_ARG) (m[nrl]+ncl-NR_END));
1087: free((FREE_ARG) (m+nrl-NR_END));
1088: }
1089:
1090: /******************* matrix *******************************/
1091: double **matrix(long nrl, long nrh, long ncl, long nch)
1092: {
1093: long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
1094: double **m;
1095:
1096: m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1097: if (!m) nrerror("allocation failure 1 in matrix()");
1098: m += NR_END;
1099: m -= nrl;
1100:
1101: m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1102: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1103: m[nrl] += NR_END;
1104: m[nrl] -= ncl;
1105:
1106: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1107: return m;
1108: /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
1109: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
1110: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1111: */
1112: }
1113:
1114: /*************************free matrix ************************/
1115: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
1116: {
1117: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1118: free((FREE_ARG)(m+nrl-NR_END));
1119: }
1120:
1121: /******************* ma3x *******************************/
1122: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
1123: {
1124: long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
1125: double ***m;
1126:
1127: m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
1128: if (!m) nrerror("allocation failure 1 in matrix()");
1129: m += NR_END;
1130: m -= nrl;
1131:
1132: m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
1133: if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
1134: m[nrl] += NR_END;
1135: m[nrl] -= ncl;
1136:
1137: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
1138:
1139: m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
1140: if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
1141: m[nrl][ncl] += NR_END;
1142: m[nrl][ncl] -= nll;
1143: for (j=ncl+1; j<=nch; j++)
1144: m[nrl][j]=m[nrl][j-1]+nlay;
1145:
1146: for (i=nrl+1; i<=nrh; i++) {
1147: m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
1148: for (j=ncl+1; j<=nch; j++)
1149: m[i][j]=m[i][j-1]+nlay;
1150: }
1151: return m;
1152: /* gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
1153: &(m[i][j][k]) <=> *((*(m+i) + j)+k)
1154: */
1155: }
1156:
1157: /*************************free ma3x ************************/
1158: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
1159: {
1160: free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
1161: free((FREE_ARG)(m[nrl]+ncl-NR_END));
1162: free((FREE_ARG)(m+nrl-NR_END));
1163: }
1164:
1165: /*************** function subdirf ***********/
1166: char *subdirf(char fileres[])
1167: {
1168: /* Caution optionfilefiname is hidden */
1169: strcpy(tmpout,optionfilefiname);
1170: strcat(tmpout,"/"); /* Add to the right */
1171: strcat(tmpout,fileres);
1172: return tmpout;
1173: }
1174:
1175: /*************** function subdirf2 ***********/
1176: char *subdirf2(char fileres[], char *preop)
1177: {
1178:
1179: /* Caution optionfilefiname is hidden */
1180: strcpy(tmpout,optionfilefiname);
1181: strcat(tmpout,"/");
1182: strcat(tmpout,preop);
1183: strcat(tmpout,fileres);
1184: return tmpout;
1185: }
1186:
1187: /*************** function subdirf3 ***********/
1188: char *subdirf3(char fileres[], char *preop, char *preop2)
1189: {
1190:
1191: /* Caution optionfilefiname is hidden */
1192: strcpy(tmpout,optionfilefiname);
1193: strcat(tmpout,"/");
1194: strcat(tmpout,preop);
1195: strcat(tmpout,preop2);
1196: strcat(tmpout,fileres);
1197: return tmpout;
1198: }
1199:
1200: char *asc_diff_time(long time_sec, char ascdiff[])
1201: {
1202: long sec_left, days, hours, minutes;
1203: days = (time_sec) / (60*60*24);
1204: sec_left = (time_sec) % (60*60*24);
1205: hours = (sec_left) / (60*60) ;
1206: sec_left = (sec_left) %(60*60);
1207: minutes = (sec_left) /60;
1208: sec_left = (sec_left) % (60);
1209: sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);
1210: return ascdiff;
1211: }
1212:
1213: /***************** f1dim *************************/
1214: extern int ncom;
1215: extern double *pcom,*xicom;
1216: extern double (*nrfunc)(double []);
1217:
1218: double f1dim(double x)
1219: {
1220: int j;
1221: double f;
1222: double *xt;
1223:
1224: xt=vector(1,ncom);
1225: for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j];
1226: f=(*nrfunc)(xt);
1227: free_vector(xt,1,ncom);
1228: return f;
1229: }
1230:
1231: /*****************brent *************************/
1232: double brent(double ax, double bx, double cx, double (*f)(double), double tol, double *xmin)
1233: {
1234: int iter;
1235: double a,b,d,etemp;
1236: double fu=0,fv,fw,fx;
1237: double ftemp=0.;
1238: double p,q,r,tol1,tol2,u,v,w,x,xm;
1239: double e=0.0;
1240:
1241: a=(ax < cx ? ax : cx);
1242: b=(ax > cx ? ax : cx);
1243: x=w=v=bx;
1244: fw=fv=fx=(*f)(x);
1245: for (iter=1;iter<=ITMAX;iter++) {
1246: xm=0.5*(a+b);
1247: tol2=2.0*(tol1=tol*fabs(x)+ZEPS);
1248: /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
1249: printf(".");fflush(stdout);
1250: fprintf(ficlog,".");fflush(ficlog);
1251: #ifdef DEBUGBRENT
1252: 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);
1253: 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);
1254: /* if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
1255: #endif
1256: if (fabs(x-xm) <= (tol2-0.5*(b-a))){
1257: *xmin=x;
1258: return fx;
1259: }
1260: ftemp=fu;
1261: if (fabs(e) > tol1) {
1262: r=(x-w)*(fx-fv);
1263: q=(x-v)*(fx-fw);
1264: p=(x-v)*q-(x-w)*r;
1265: q=2.0*(q-r);
1266: if (q > 0.0) p = -p;
1267: q=fabs(q);
1268: etemp=e;
1269: e=d;
1270: if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
1271: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1272: else {
1273: d=p/q;
1274: u=x+d;
1275: if (u-a < tol2 || b-u < tol2)
1276: d=SIGN(tol1,xm-x);
1277: }
1278: } else {
1279: d=CGOLD*(e=(x >= xm ? a-x : b-x));
1280: }
1281: u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
1282: fu=(*f)(u);
1283: if (fu <= fx) {
1284: if (u >= x) a=x; else b=x;
1285: SHFT(v,w,x,u)
1286: SHFT(fv,fw,fx,fu)
1287: } else {
1288: if (u < x) a=u; else b=u;
1289: if (fu <= fw || w == x) {
1290: v=w;
1291: w=u;
1292: fv=fw;
1293: fw=fu;
1294: } else if (fu <= fv || v == x || v == w) {
1295: v=u;
1296: fv=fu;
1297: }
1298: }
1299: }
1300: nrerror("Too many iterations in brent");
1301: *xmin=x;
1302: return fx;
1303: }
1304:
1305: /****************** mnbrak ***********************/
1306:
1307: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc,
1308: double (*func)(double))
1309: {
1310: double ulim,u,r,q, dum;
1311: double fu;
1312:
1313: *fa=(*func)(*ax);
1314: *fb=(*func)(*bx);
1315: if (*fb > *fa) {
1316: SHFT(dum,*ax,*bx,dum)
1317: SHFT(dum,*fb,*fa,dum)
1318: }
1319: *cx=(*bx)+GOLD*(*bx-*ax);
1320: *fc=(*func)(*cx);
1321: while (*fb > *fc) { /* Declining fa, fb, fc */
1322: r=(*bx-*ax)*(*fb-*fc);
1323: q=(*bx-*cx)*(*fb-*fa);
1324: u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/
1325: (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscisse of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
1326: ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscisse where function can be evaluated */
1327: if ((*bx-u)*(u-*cx) > 0.0) { /* if u between b and c */
1328: fu=(*func)(u);
1329: #ifdef DEBUG
1330: /* f(x)=A(x-u)**2+f(u) */
1331: double A, fparabu;
1332: A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
1333: fparabu= *fa - A*(*ax-u)*(*ax-u);
1334: 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);
1335: 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);
1336: #endif
1337: } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1338: fu=(*func)(u);
1339: if (fu < *fc) {
1340: SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))
1341: SHFT(*fb,*fc,fu,(*func)(u))
1342: }
1343: } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1344: u=ulim;
1345: fu=(*func)(u);
1346: } else {
1347: u=(*cx)+GOLD*(*cx-*bx);
1348: fu=(*func)(u);
1349: }
1350: SHFT(*ax,*bx,*cx,u)
1351: SHFT(*fa,*fb,*fc,fu)
1352: }
1353: }
1354:
1355: /*************** linmin ************************/
1356: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
1357: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
1358: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
1359: the value of func at the returned location p . This is actually all accomplished by calling the
1360: routines mnbrak and brent .*/
1361: int ncom;
1362: double *pcom,*xicom;
1363: double (*nrfunc)(double []);
1364:
1365: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []))
1366: {
1367: double brent(double ax, double bx, double cx,
1368: double (*f)(double), double tol, double *xmin);
1369: double f1dim(double x);
1370: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb,
1371: double *fc, double (*func)(double));
1372: int j;
1373: double xx,xmin,bx,ax;
1374: double fx,fb,fa;
1375:
1376: ncom=n;
1377: pcom=vector(1,n);
1378: xicom=vector(1,n);
1379: nrfunc=func;
1380: for (j=1;j<=n;j++) {
1381: pcom[j]=p[j];
1382: xicom[j]=xi[j];
1383: }
1384: ax=0.0;
1385: xx=1.0;
1386: mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Find a bracket a,x,b in direction n=xi ie xicom */
1387: *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Find a minimum P+lambda n in that direction (lambdamin), with TOL between abscisses */
1388: #ifdef DEBUG
1389: printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1390: fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
1391: #endif
1392: for (j=1;j<=n;j++) {
1393: xi[j] *= xmin;
1394: p[j] += xi[j];
1395: }
1396: free_vector(xicom,1,n);
1397: free_vector(pcom,1,n);
1398: }
1399:
1400:
1401: /*************** powell ************************/
1402: /*
1403: Minimization of a function func of n variables. Input consists of an initial starting point
1404: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
1405: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
1406: such that failure to decrease by more than this amount on one iteration signals doneness. On
1407: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
1408: function value at p , and iter is the number of iterations taken. The routine linmin is used.
1409: */
1410: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret,
1411: double (*func)(double []))
1412: {
1413: void linmin(double p[], double xi[], int n, double *fret,
1414: double (*func)(double []));
1415: int i,ibig,j;
1416: double del,t,*pt,*ptt,*xit;
1417: double directest;
1418: double fp,fptt;
1419: double *xits;
1420: int niterf, itmp;
1421:
1422: pt=vector(1,n);
1423: ptt=vector(1,n);
1424: xit=vector(1,n);
1425: xits=vector(1,n);
1426: *fret=(*func)(p);
1427: for (j=1;j<=n;j++) pt[j]=p[j];
1428: rcurr_time = time(NULL);
1429: for (*iter=1;;++(*iter)) {
1430: fp=(*fret);
1431: ibig=0;
1432: del=0.0;
1433: rlast_time=rcurr_time;
1434: /* (void) gettimeofday(&curr_time,&tzp); */
1435: rcurr_time = time(NULL);
1436: curr_time = *localtime(&rcurr_time);
1437: printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
1438: fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1439: /* fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1440: for (i=1;i<=n;i++) {
1441: printf(" %d %.12f",i, p[i]);
1442: fprintf(ficlog," %d %.12lf",i, p[i]);
1443: fprintf(ficrespow," %.12lf", p[i]);
1444: }
1445: printf("\n");
1446: fprintf(ficlog,"\n");
1447: fprintf(ficrespow,"\n");fflush(ficrespow);
1448: if(*iter <=3){
1449: tml = *localtime(&rcurr_time);
1450: strcpy(strcurr,asctime(&tml));
1451: rforecast_time=rcurr_time;
1452: itmp = strlen(strcurr);
1453: if(strcurr[itmp-1]=='\n') /* Windows outputs with a new line */
1454: strcurr[itmp-1]='\0';
1455: printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1456: fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1457: for(niterf=10;niterf<=30;niterf+=10){
1458: rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
1459: forecast_time = *localtime(&rforecast_time);
1460: strcpy(strfor,asctime(&forecast_time));
1461: itmp = strlen(strfor);
1462: if(strfor[itmp-1]=='\n')
1463: strfor[itmp-1]='\0';
1464: 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);
1465: 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);
1466: }
1467: }
1468: for (i=1;i<=n;i++) {
1469: for (j=1;j<=n;j++) xit[j]=xi[j][i];
1470: fptt=(*fret);
1471: #ifdef DEBUG
1472: printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1473: fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1474: #endif
1475: printf("%d",i);fflush(stdout);
1476: fprintf(ficlog,"%d",i);fflush(ficlog);
1477: linmin(p,xit,n,fret,func);
1478: if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions
1479: because that direction will be replaced unless the gain del is small
1480: in comparison with the 'probable' gain, mu^2, with the last average direction.
1481: Unless the n directions are conjugate some gain in the determinant may be obtained
1482: with the new direction.
1483: */
1484: del=fabs(fptt-(*fret));
1485: ibig=i;
1486: }
1487: #ifdef DEBUG
1488: printf("%d %.12e",i,(*fret));
1489: fprintf(ficlog,"%d %.12e",i,(*fret));
1490: for (j=1;j<=n;j++) {
1491: xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
1492: printf(" x(%d)=%.12e",j,xit[j]);
1493: fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1494: }
1495: for(j=1;j<=n;j++) {
1496: printf(" p(%d)=%.12e",j,p[j]);
1497: fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1498: }
1499: printf("\n");
1500: fprintf(ficlog,"\n");
1501: #endif
1502: } /* end i */
1503: if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1504: #ifdef DEBUG
1505: int k[2],l;
1506: k[0]=1;
1507: k[1]=-1;
1508: printf("Max: %.12e",(*func)(p));
1509: fprintf(ficlog,"Max: %.12e",(*func)(p));
1510: for (j=1;j<=n;j++) {
1511: printf(" %.12e",p[j]);
1512: fprintf(ficlog," %.12e",p[j]);
1513: }
1514: printf("\n");
1515: fprintf(ficlog,"\n");
1516: for(l=0;l<=1;l++) {
1517: for (j=1;j<=n;j++) {
1518: ptt[j]=p[j]+(p[j]-pt[j])*k[l];
1519: printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1520: fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
1521: }
1522: printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1523: fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
1524: }
1525: #endif
1526:
1527:
1528: free_vector(xit,1,n);
1529: free_vector(xits,1,n);
1530: free_vector(ptt,1,n);
1531: free_vector(pt,1,n);
1532: return;
1533: }
1534: if (*iter == ITMAX) nrerror("powell exceeding maximum iterations.");
1535: for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1536: ptt[j]=2.0*p[j]-pt[j];
1537: xit[j]=p[j]-pt[j];
1538: pt[j]=p[j];
1539: }
1540: fptt=(*func)(ptt); /* f_3 */
1541: if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1542: /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1543: /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1544: /* Let f"(x2) be the 2nd derivative equal everywhere. */
1545: /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
1546: /* will reach at f3 = fm + h^2/2 f"m ; f" = (f1 -2f2 +f3 ) / h**2 */
1547: /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1548: /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1549:
1550: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del); /* Intel compiler doesn't work on one line */
1551: t= t- del*SQR(fp-fptt);
1552: directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If del was big enough we change it for a new direction */
1553: #ifdef DEBUG
1554: printf("t1= %.12lf, t2= %.12lf, t=%.12lf directest=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t,directest);
1555: fprintf(ficlog,"t1= %.12lf, t2= %.12lf, t=%.12lf directest=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t,directest);
1556: printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1557: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1558: fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
1559: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
1560: 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);
1561: 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);
1562: #endif
1563: #ifdef POWELLDIRECT
1564: if (directest*t < 0.0) { /* Contradiction between both tests */
1565: printf("directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt);
1566: printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1567: fprintf(ficlog,"directest= %.12lf, t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt);
1568: fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1569: }
1570: if (directest < 0.0) { /* Then we use it for new direction */
1571: #else
1572: if (t < 0.0) { /* Then we use it for new direction */
1573: #endif
1574: linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction.*/
1575: for (j=1;j<=n;j++) {
1576: xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
1577: xi[j][n]=xit[j]; /* and this nth direction by the by the average p_0 p_n */
1578: }
1579: printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1580: fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1581:
1582: #ifdef DEBUG
1583: printf("Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1584: fprintf(ficlog,"Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1585: for(j=1;j<=n;j++){
1586: printf(" %.12e",xit[j]);
1587: fprintf(ficlog," %.12e",xit[j]);
1588: }
1589: printf("\n");
1590: fprintf(ficlog,"\n");
1591: #endif
1592: } /* end of t negative */
1593: } /* end if (fptt < fp) */
1594: }
1595: }
1596:
1597: /**** Prevalence limit (stable or period prevalence) ****************/
1598:
1599: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
1600: {
1601: /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1602: matrix by transitions matrix until convergence is reached */
1603:
1604: int i, ii,j,k;
1605: double min, max, maxmin, maxmax,sumnew=0.;
1606: /* double **matprod2(); */ /* test */
1607: double **out, cov[NCOVMAX+1], **pmij();
1608: double **newm;
1609: double agefin, delaymax=50 ; /* Max number of years to converge */
1610:
1611: for (ii=1;ii<=nlstate+ndeath;ii++)
1612: for (j=1;j<=nlstate+ndeath;j++){
1613: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1614: }
1615:
1616: cov[1]=1.;
1617:
1618: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1619: for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1620: newm=savm;
1621: /* Covariates have to be included here again */
1622: cov[2]=agefin;
1623:
1624: for (k=1; k<=cptcovn;k++) {
1625: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1626: /*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]]);*/
1627: }
1628: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1629: /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
1630: /* cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]] * nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]]; */
1631:
1632: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
1633: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
1634: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1635: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1636: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1637: out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1638:
1639: savm=oldm;
1640: oldm=newm;
1641: maxmax=0.;
1642: for(j=1;j<=nlstate;j++){
1643: min=1.;
1644: max=0.;
1645: for(i=1; i<=nlstate; i++) {
1646: sumnew=0;
1647: for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
1648: prlim[i][j]= newm[i][j]/(1-sumnew);
1649: /*printf(" prevalim i=%d, j=%d, prmlim[%d][%d]=%f, agefin=%d \n", i, j, i, j, prlim[i][j],(int)agefin);*/
1650: max=FMAX(max,prlim[i][j]);
1651: min=FMIN(min,prlim[i][j]);
1652: }
1653: maxmin=max-min;
1654: maxmax=FMAX(maxmax,maxmin);
1655: } /* j loop */
1656: if(maxmax < ftolpl){
1657: return prlim;
1658: }
1659: } /* age loop */
1660: return prlim; /* should not reach here */
1661: }
1662:
1663: /*************** transition probabilities ***************/
1664:
1665: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1666: {
1667: /* According to parameters values stored in x and the covariate's values stored in cov,
1668: computes the probability to be observed in state j being in state i by appying the
1669: model to the ncovmodel covariates (including constant and age).
1670: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
1671: and, according on how parameters are entered, the position of the coefficient xij(nc) of the
1672: ncth covariate in the global vector x is given by the formula:
1673: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
1674: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
1675: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
1676: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1677: Outputs ps[i][j] the probability to be observed in j being in j according to
1678: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1679: */
1680: double s1, lnpijopii;
1681: /*double t34;*/
1682: int i,j, nc, ii, jj;
1683:
1684: for(i=1; i<= nlstate; i++){
1685: for(j=1; j<i;j++){
1686: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1687: /*lnpijopii += param[i][j][nc]*cov[nc];*/
1688: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
1689: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1690: }
1691: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1692: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1693: }
1694: for(j=i+1; j<=nlstate+ndeath;j++){
1695: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
1696: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
1697: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
1698: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1699: }
1700: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1701: }
1702: }
1703:
1704: for(i=1; i<= nlstate; i++){
1705: s1=0;
1706: for(j=1; j<i; j++){
1707: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1708: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1709: }
1710: for(j=i+1; j<=nlstate+ndeath; j++){
1711: s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1712: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
1713: }
1714: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1715: ps[i][i]=1./(s1+1.);
1716: /* Computing other pijs */
1717: for(j=1; j<i; j++)
1718: ps[i][j]= exp(ps[i][j])*ps[i][i];
1719: for(j=i+1; j<=nlstate+ndeath; j++)
1720: ps[i][j]= exp(ps[i][j])*ps[i][i];
1721: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
1722: } /* end i */
1723:
1724: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
1725: for(jj=1; jj<= nlstate+ndeath; jj++){
1726: ps[ii][jj]=0;
1727: ps[ii][ii]=1;
1728: }
1729: }
1730:
1731:
1732: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
1733: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */
1734: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
1735: /* } */
1736: /* printf("\n "); */
1737: /* } */
1738: /* printf("\n ");printf("%lf ",cov[2]);*/
1739: /*
1740: for(i=1; i<= npar; i++) printf("%f ",x[i]);
1741: goto end;*/
1742: return ps;
1743: }
1744:
1745: /**************** Product of 2 matrices ******************/
1746:
1747: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1748: {
1749: /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
1750: b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
1751: /* in, b, out are matrice of pointers which should have been initialized
1752: before: only the contents of out is modified. The function returns
1753: a pointer to pointers identical to out */
1754: int i, j, k;
1755: for(i=nrl; i<= nrh; i++)
1756: for(k=ncolol; k<=ncoloh; k++){
1757: out[i][k]=0.;
1758: for(j=ncl; j<=nch; j++)
1759: out[i][k] +=in[i][j]*b[j][k];
1760: }
1761: return out;
1762: }
1763:
1764:
1765: /************* Higher Matrix Product ***************/
1766:
1767: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
1768: {
1769: /* Computes the transition matrix starting at age 'age' over
1770: 'nhstepm*hstepm*stepm' months (i.e. until
1771: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying
1772: nhstepm*hstepm matrices.
1773: Output is stored in matrix po[i][j][h] for h every 'hstepm' step
1774: (typically every 2 years instead of every month which is too big
1775: for the memory).
1776: Model is determined by parameters x and covariates have to be
1777: included manually here.
1778:
1779: */
1780:
1781: int i, j, d, h, k;
1782: double **out, cov[NCOVMAX+1];
1783: double **newm;
1784:
1785: /* Hstepm could be zero and should return the unit matrix */
1786: for (i=1;i<=nlstate+ndeath;i++)
1787: for (j=1;j<=nlstate+ndeath;j++){
1788: oldm[i][j]=(i==j ? 1.0 : 0.0);
1789: po[i][j][0]=(i==j ? 1.0 : 0.0);
1790: }
1791: /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1792: for(h=1; h <=nhstepm; h++){
1793: for(d=1; d <=hstepm; d++){
1794: newm=savm;
1795: /* Covariates have to be included here again */
1796: cov[1]=1.;
1797: cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
1798: for (k=1; k<=cptcovn;k++)
1799: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1800: for (k=1; k<=cptcovage;k++)
1801: cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
1802: for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1803: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
1804:
1805:
1806: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
1807: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1808: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
1809: pmij(pmmij,cov,ncovmodel,x,nlstate));
1810: savm=oldm;
1811: oldm=newm;
1812: }
1813: for(i=1; i<=nlstate+ndeath; i++)
1814: for(j=1;j<=nlstate+ndeath;j++) {
1815: po[i][j][h]=newm[i][j];
1816: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1817: }
1818: /*printf("h=%d ",h);*/
1819: } /* end h */
1820: /* printf("\n H=%d \n",h); */
1821: return po;
1822: }
1823:
1824: #ifdef NLOPT
1825: double myfunc(unsigned n, const double *p1, double *grad, void *pd){
1826: double fret;
1827: double *xt;
1828: int j;
1829: myfunc_data *d2 = (myfunc_data *) pd;
1830: /* xt = (p1-1); */
1831: xt=vector(1,n);
1832: for (j=1;j<=n;j++) xt[j]=p1[j-1]; /* xt[1]=p1[0] */
1833:
1834: fret=(d2->function)(xt); /* p xt[1]@8 is fine */
1835: /* fret=(*func)(xt); /\* p xt[1]@8 is fine *\/ */
1836: printf("Function = %.12lf ",fret);
1837: for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]);
1838: printf("\n");
1839: free_vector(xt,1,n);
1840: return fret;
1841: }
1842: #endif
1843:
1844: /*************** log-likelihood *************/
1845: double func( double *x)
1846: {
1847: int i, ii, j, k, mi, d, kk;
1848: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1849: double **out;
1850: double sw; /* Sum of weights */
1851: double lli; /* Individual log likelihood */
1852: int s1, s2;
1853: double bbh, survp;
1854: long ipmx;
1855: /*extern weight */
1856: /* We are differentiating ll according to initial status */
1857: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
1858: /*for(i=1;i<imx;i++)
1859: printf(" %d\n",s[4][i]);
1860: */
1861:
1862: ++countcallfunc;
1863:
1864: cov[1]=1.;
1865:
1866: for(k=1; k<=nlstate; k++) ll[k]=0.;
1867:
1868: if(mle==1){
1869: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1870: /* Computes the values of the ncovmodel covariates of the model
1871: depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
1872: Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
1873: to be observed in j being in i according to the model.
1874: */
1875: for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1876: cov[2+k]=covar[Tvar[k]][i];
1877: }
1878: /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4]
1879: is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]
1880: has been calculated etc */
1881: for(mi=1; mi<= wav[i]-1; mi++){
1882: for (ii=1;ii<=nlstate+ndeath;ii++)
1883: for (j=1;j<=nlstate+ndeath;j++){
1884: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1885: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1886: }
1887: for(d=0; d<dh[mi][i]; d++){
1888: newm=savm;
1889: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1890: for (kk=1; kk<=cptcovage;kk++) {
1891: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; /* Tage[kk] gives the data-covariate associated with age */
1892: }
1893: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1894: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1895: savm=oldm;
1896: oldm=newm;
1897: } /* end mult */
1898:
1899: /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
1900: /* But now since version 0.9 we anticipate for bias at large stepm.
1901: * If stepm is larger than one month (smallest stepm) and if the exact delay
1902: * (in months) between two waves is not a multiple of stepm, we rounded to
1903: * the nearest (and in case of equal distance, to the lowest) interval but now
1904: * we keep into memory the bias bh[mi][i] and also the previous matrix product
1905: * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
1906: * probability in order to take into account the bias as a fraction of the way
1907: * from savm to out if bh is negative or even beyond if bh is positive. bh varies
1908: * -stepm/2 to stepm/2 .
1909: * For stepm=1 the results are the same as for previous versions of Imach.
1910: * For stepm > 1 the results are less biased than in previous versions.
1911: */
1912: s1=s[mw[mi][i]][i];
1913: s2=s[mw[mi+1][i]][i];
1914: bbh=(double)bh[mi][i]/(double)stepm;
1915: /* bias bh is positive if real duration
1916: * is higher than the multiple of stepm and negative otherwise.
1917: */
1918: /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
1919: if( s2 > nlstate){
1920: /* i.e. if s2 is a death state and if the date of death is known
1921: then the contribution to the likelihood is the probability to
1922: die between last step unit time and current step unit time,
1923: which is also equal to probability to die before dh
1924: minus probability to die before dh-stepm .
1925: In version up to 0.92 likelihood was computed
1926: as if date of death was unknown. Death was treated as any other
1927: health state: the date of the interview describes the actual state
1928: and not the date of a change in health state. The former idea was
1929: to consider that at each interview the state was recorded
1930: (healthy, disable or death) and IMaCh was corrected; but when we
1931: introduced the exact date of death then we should have modified
1932: the contribution of an exact death to the likelihood. This new
1933: contribution is smaller and very dependent of the step unit
1934: stepm. It is no more the probability to die between last interview
1935: and month of death but the probability to survive from last
1936: interview up to one month before death multiplied by the
1937: probability to die within a month. Thanks to Chris
1938: Jackson for correcting this bug. Former versions increased
1939: mortality artificially. The bad side is that we add another loop
1940: which slows down the processing. The difference can be up to 10%
1941: lower mortality.
1942: */
1943: lli=log(out[s1][s2] - savm[s1][s2]);
1944:
1945:
1946: } else if (s2==-2) {
1947: for (j=1,survp=0. ; j<=nlstate; j++)
1948: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1949: /*survp += out[s1][j]; */
1950: lli= log(survp);
1951: }
1952:
1953: else if (s2==-4) {
1954: for (j=3,survp=0. ; j<=nlstate; j++)
1955: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1956: lli= log(survp);
1957: }
1958:
1959: else if (s2==-5) {
1960: for (j=1,survp=0. ; j<=2; j++)
1961: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
1962: lli= log(survp);
1963: }
1964:
1965: else{
1966: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1967: /* 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 */
1968: }
1969: /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
1970: /*if(lli ==000.0)*/
1971: /*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); */
1972: ipmx +=1;
1973: sw += weight[i];
1974: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1975: } /* end of wave */
1976: } /* end of individual */
1977: } else if(mle==2){
1978: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1979: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1980: for(mi=1; mi<= wav[i]-1; mi++){
1981: for (ii=1;ii<=nlstate+ndeath;ii++)
1982: for (j=1;j<=nlstate+ndeath;j++){
1983: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
1984: savm[ii][j]=(ii==j ? 1.0 : 0.0);
1985: }
1986: for(d=0; d<=dh[mi][i]; d++){
1987: newm=savm;
1988: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
1989: for (kk=1; kk<=cptcovage;kk++) {
1990: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1991: }
1992: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
1993: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1994: savm=oldm;
1995: oldm=newm;
1996: } /* end mult */
1997:
1998: s1=s[mw[mi][i]][i];
1999: s2=s[mw[mi+1][i]][i];
2000: bbh=(double)bh[mi][i]/(double)stepm;
2001: 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 */
2002: ipmx +=1;
2003: sw += weight[i];
2004: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2005: } /* end of wave */
2006: } /* end of individual */
2007: } else if(mle==3){ /* exponential inter-extrapolation */
2008: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2009: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2010: for(mi=1; mi<= wav[i]-1; mi++){
2011: for (ii=1;ii<=nlstate+ndeath;ii++)
2012: for (j=1;j<=nlstate+ndeath;j++){
2013: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2014: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2015: }
2016: for(d=0; d<dh[mi][i]; d++){
2017: newm=savm;
2018: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2019: for (kk=1; kk<=cptcovage;kk++) {
2020: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2021: }
2022: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2023: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2024: savm=oldm;
2025: oldm=newm;
2026: } /* end mult */
2027:
2028: s1=s[mw[mi][i]][i];
2029: s2=s[mw[mi+1][i]][i];
2030: bbh=(double)bh[mi][i]/(double)stepm;
2031: 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 */
2032: ipmx +=1;
2033: sw += weight[i];
2034: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2035: } /* end of wave */
2036: } /* end of individual */
2037: }else if (mle==4){ /* ml=4 no inter-extrapolation */
2038: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2039: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2040: for(mi=1; mi<= wav[i]-1; mi++){
2041: for (ii=1;ii<=nlstate+ndeath;ii++)
2042: for (j=1;j<=nlstate+ndeath;j++){
2043: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2044: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2045: }
2046: for(d=0; d<dh[mi][i]; d++){
2047: newm=savm;
2048: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2049: for (kk=1; kk<=cptcovage;kk++) {
2050: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2051: }
2052:
2053: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2054: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2055: savm=oldm;
2056: oldm=newm;
2057: } /* end mult */
2058:
2059: s1=s[mw[mi][i]][i];
2060: s2=s[mw[mi+1][i]][i];
2061: if( s2 > nlstate){
2062: lli=log(out[s1][s2] - savm[s1][s2]);
2063: }else{
2064: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2065: }
2066: ipmx +=1;
2067: sw += weight[i];
2068: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2069: /* 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]); */
2070: } /* end of wave */
2071: } /* end of individual */
2072: }else{ /* ml=5 no inter-extrapolation no jackson =0.8a */
2073: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2074: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2075: for(mi=1; mi<= wav[i]-1; mi++){
2076: for (ii=1;ii<=nlstate+ndeath;ii++)
2077: for (j=1;j<=nlstate+ndeath;j++){
2078: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2079: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2080: }
2081: for(d=0; d<dh[mi][i]; d++){
2082: newm=savm;
2083: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2084: for (kk=1; kk<=cptcovage;kk++) {
2085: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2086: }
2087:
2088: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2089: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2090: savm=oldm;
2091: oldm=newm;
2092: } /* end mult */
2093:
2094: s1=s[mw[mi][i]][i];
2095: s2=s[mw[mi+1][i]][i];
2096: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
2097: ipmx +=1;
2098: sw += weight[i];
2099: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2100: /*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]);*/
2101: } /* end of wave */
2102: } /* end of individual */
2103: } /* End of if */
2104: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2105: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2106: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2107: return -l;
2108: }
2109:
2110: /*************** log-likelihood *************/
2111: double funcone( double *x)
2112: {
2113: /* Same as likeli but slower because of a lot of printf and if */
2114: int i, ii, j, k, mi, d, kk;
2115: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
2116: double **out;
2117: double lli; /* Individual log likelihood */
2118: double llt;
2119: int s1, s2;
2120: double bbh, survp;
2121: /*extern weight */
2122: /* We are differentiating ll according to initial status */
2123: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
2124: /*for(i=1;i<imx;i++)
2125: printf(" %d\n",s[4][i]);
2126: */
2127: cov[1]=1.;
2128:
2129: for(k=1; k<=nlstate; k++) ll[k]=0.;
2130:
2131: for (i=1,ipmx=0, sw=0.; i<=imx; i++){
2132: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
2133: for(mi=1; mi<= wav[i]-1; mi++){
2134: for (ii=1;ii<=nlstate+ndeath;ii++)
2135: for (j=1;j<=nlstate+ndeath;j++){
2136: oldm[ii][j]=(ii==j ? 1.0 : 0.0);
2137: savm[ii][j]=(ii==j ? 1.0 : 0.0);
2138: }
2139: for(d=0; d<dh[mi][i]; d++){
2140: newm=savm;
2141: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
2142: for (kk=1; kk<=cptcovage;kk++) {
2143: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
2144: }
2145: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
2146: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
2147: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
2148: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
2149: /* 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
2150: savm=oldm;
2151: oldm=newm;
2152: } /* end mult */
2153:
2154: s1=s[mw[mi][i]][i];
2155: s2=s[mw[mi+1][i]][i];
2156: bbh=(double)bh[mi][i]/(double)stepm;
2157: /* bias is positive if real duration
2158: * is higher than the multiple of stepm and negative otherwise.
2159: */
2160: if( s2 > nlstate && (mle <5) ){ /* Jackson */
2161: lli=log(out[s1][s2] - savm[s1][s2]);
2162: } else if (s2==-2) {
2163: for (j=1,survp=0. ; j<=nlstate; j++)
2164: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
2165: lli= log(survp);
2166: }else if (mle==1){
2167: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2168: } else if(mle==2){
2169: 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 */
2170: } else if(mle==3){ /* exponential inter-extrapolation */
2171: 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 */
2172: } else if (mle==4){ /* mle=4 no inter-extrapolation */
2173: lli=log(out[s1][s2]); /* Original formula */
2174: } else{ /* mle=0 back to 1 */
2175: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
2176: /*lli=log(out[s1][s2]); */ /* Original formula */
2177: } /* End of if */
2178: ipmx +=1;
2179: sw += weight[i];
2180: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
2181: /*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]); */
2182: if(globpr){
2183: fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
2184: %11.6f %11.6f %11.6f ", \
2185: num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
2186: 2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
2187: for(k=1,llt=0.,l=0.; k<=nlstate; k++){
2188: llt +=ll[k]*gipmx/gsw;
2189: fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
2190: }
2191: fprintf(ficresilk," %10.6f\n", -llt);
2192: }
2193: } /* end of wave */
2194: } /* end of individual */
2195: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
2196: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
2197: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
2198: if(globpr==0){ /* First time we count the contributions and weights */
2199: gipmx=ipmx;
2200: gsw=sw;
2201: }
2202: return -l;
2203: }
2204:
2205:
2206: /*************** function likelione ***********/
2207: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
2208: {
2209: /* This routine should help understanding what is done with
2210: the selection of individuals/waves and
2211: to check the exact contribution to the likelihood.
2212: Plotting could be done.
2213: */
2214: int k;
2215:
2216: if(*globpri !=0){ /* Just counts and sums, no printings */
2217: strcpy(fileresilk,"ilk");
2218: strcat(fileresilk,fileres);
2219: if((ficresilk=fopen(fileresilk,"w"))==NULL) {
2220: printf("Problem with resultfile: %s\n", fileresilk);
2221: fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
2222: }
2223: 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");
2224: fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
2225: /* i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
2226: for(k=1; k<=nlstate; k++)
2227: fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
2228: fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
2229: }
2230:
2231: *fretone=(*funcone)(p);
2232: if(*globpri !=0){
2233: fclose(ficresilk);
2234: fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
2235: fflush(fichtm);
2236: }
2237: return;
2238: }
2239:
2240:
2241: /*********** Maximum Likelihood Estimation ***************/
2242:
2243: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
2244: {
2245: int i,j, iter=0;
2246: double **xi;
2247: double fret;
2248: double fretone; /* Only one call to likelihood */
2249: /* char filerespow[FILENAMELENGTH];*/
2250:
2251: #ifdef NLOPT
2252: int creturn;
2253: nlopt_opt opt;
2254: /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
2255: double *lb;
2256: double minf; /* the minimum objective value, upon return */
2257: double * p1; /* Shifted parameters from 0 instead of 1 */
2258: myfunc_data dinst, *d = &dinst;
2259: #endif
2260:
2261:
2262: xi=matrix(1,npar,1,npar);
2263: for (i=1;i<=npar;i++)
2264: for (j=1;j<=npar;j++)
2265: xi[i][j]=(i==j ? 1.0 : 0.0);
2266: printf("Powell\n"); fprintf(ficlog,"Powell\n");
2267: strcpy(filerespow,"pow");
2268: strcat(filerespow,fileres);
2269: if((ficrespow=fopen(filerespow,"w"))==NULL) {
2270: printf("Problem with resultfile: %s\n", filerespow);
2271: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
2272: }
2273: fprintf(ficrespow,"# Powell\n# iter -2*LL");
2274: for (i=1;i<=nlstate;i++)
2275: for(j=1;j<=nlstate+ndeath;j++)
2276: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
2277: fprintf(ficrespow,"\n");
2278: #ifdef POWELL
2279: powell(p,xi,npar,ftol,&iter,&fret,func);
2280: #endif
2281:
2282: #ifdef NLOPT
2283: #ifdef NEWUOA
2284: opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
2285: #else
2286: opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
2287: #endif
2288: lb=vector(0,npar-1);
2289: for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
2290: nlopt_set_lower_bounds(opt, lb);
2291: nlopt_set_initial_step1(opt, 0.1);
2292:
2293: p1= (p+1); /* p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
2294: d->function = func;
2295: printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
2296: nlopt_set_min_objective(opt, myfunc, d);
2297: nlopt_set_xtol_rel(opt, ftol);
2298: if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
2299: printf("nlopt failed! %d\n",creturn);
2300: }
2301: else {
2302: printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
2303: printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
2304: iter=1; /* not equal */
2305: }
2306: nlopt_destroy(opt);
2307: #endif
2308: free_matrix(xi,1,npar,1,npar);
2309: fclose(ficrespow);
2310: printf("#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2311: fprintf(ficlog,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2312: fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
2313:
2314: }
2315:
2316: /**** Computes Hessian and covariance matrix ***/
2317: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
2318: {
2319: double **a,**y,*x,pd;
2320: double **hess;
2321: int i, j;
2322: int *indx;
2323:
2324: double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
2325: double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
2326: void lubksb(double **a, int npar, int *indx, double b[]) ;
2327: void ludcmp(double **a, int npar, int *indx, double *d) ;
2328: double gompertz(double p[]);
2329: hess=matrix(1,npar,1,npar);
2330:
2331: printf("\nCalculation of the hessian matrix. Wait...\n");
2332: fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
2333: for (i=1;i<=npar;i++){
2334: printf("%d",i);fflush(stdout);
2335: fprintf(ficlog,"%d",i);fflush(ficlog);
2336:
2337: hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
2338:
2339: /* printf(" %f ",p[i]);
2340: printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
2341: }
2342:
2343: for (i=1;i<=npar;i++) {
2344: for (j=1;j<=npar;j++) {
2345: if (j>i) {
2346: printf(".%d%d",i,j);fflush(stdout);
2347: fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
2348: hess[i][j]=hessij(p,delti,i,j,func,npar);
2349:
2350: hess[j][i]=hess[i][j];
2351: /*printf(" %lf ",hess[i][j]);*/
2352: }
2353: }
2354: }
2355: printf("\n");
2356: fprintf(ficlog,"\n");
2357:
2358: printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
2359: fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
2360:
2361: a=matrix(1,npar,1,npar);
2362: y=matrix(1,npar,1,npar);
2363: x=vector(1,npar);
2364: indx=ivector(1,npar);
2365: for (i=1;i<=npar;i++)
2366: for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
2367: ludcmp(a,npar,indx,&pd);
2368:
2369: for (j=1;j<=npar;j++) {
2370: for (i=1;i<=npar;i++) x[i]=0;
2371: x[j]=1;
2372: lubksb(a,npar,indx,x);
2373: for (i=1;i<=npar;i++){
2374: matcov[i][j]=x[i];
2375: }
2376: }
2377:
2378: printf("\n#Hessian matrix#\n");
2379: fprintf(ficlog,"\n#Hessian matrix#\n");
2380: for (i=1;i<=npar;i++) {
2381: for (j=1;j<=npar;j++) {
2382: printf("%.3e ",hess[i][j]);
2383: fprintf(ficlog,"%.3e ",hess[i][j]);
2384: }
2385: printf("\n");
2386: fprintf(ficlog,"\n");
2387: }
2388:
2389: /* Recompute Inverse */
2390: for (i=1;i<=npar;i++)
2391: for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
2392: ludcmp(a,npar,indx,&pd);
2393:
2394: /* printf("\n#Hessian matrix recomputed#\n");
2395:
2396: for (j=1;j<=npar;j++) {
2397: for (i=1;i<=npar;i++) x[i]=0;
2398: x[j]=1;
2399: lubksb(a,npar,indx,x);
2400: for (i=1;i<=npar;i++){
2401: y[i][j]=x[i];
2402: printf("%.3e ",y[i][j]);
2403: fprintf(ficlog,"%.3e ",y[i][j]);
2404: }
2405: printf("\n");
2406: fprintf(ficlog,"\n");
2407: }
2408: */
2409:
2410: free_matrix(a,1,npar,1,npar);
2411: free_matrix(y,1,npar,1,npar);
2412: free_vector(x,1,npar);
2413: free_ivector(indx,1,npar);
2414: free_matrix(hess,1,npar,1,npar);
2415:
2416:
2417: }
2418:
2419: /*************** hessian matrix ****************/
2420: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
2421: {
2422: int i;
2423: int l=1, lmax=20;
2424: double k1,k2;
2425: double p2[MAXPARM+1]; /* identical to x */
2426: double res;
2427: double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
2428: double fx;
2429: int k=0,kmax=10;
2430: double l1;
2431:
2432: fx=func(x);
2433: for (i=1;i<=npar;i++) p2[i]=x[i];
2434: for(l=0 ; l <=lmax; l++){ /* Enlarging the zone around the Maximum */
2435: l1=pow(10,l);
2436: delts=delt;
2437: for(k=1 ; k <kmax; k=k+1){
2438: delt = delta*(l1*k);
2439: p2[theta]=x[theta] +delt;
2440: k1=func(p2)-fx; /* Might be negative if too close to the theoretical maximum */
2441: p2[theta]=x[theta]-delt;
2442: k2=func(p2)-fx;
2443: /*res= (k1-2.0*fx+k2)/delt/delt; */
2444: res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
2445:
2446: #ifdef DEBUGHESS
2447: 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);
2448: 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);
2449: #endif
2450: /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
2451: if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
2452: k=kmax;
2453: }
2454: else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
2455: k=kmax; l=lmax*10;
2456: }
2457: else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){
2458: delts=delt;
2459: }
2460: }
2461: }
2462: delti[theta]=delts;
2463: return res;
2464:
2465: }
2466:
2467: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
2468: {
2469: int i;
2470: int l=1, lmax=20;
2471: double k1,k2,k3,k4,res,fx;
2472: double p2[MAXPARM+1];
2473: int k;
2474:
2475: fx=func(x);
2476: for (k=1; k<=2; k++) {
2477: for (i=1;i<=npar;i++) p2[i]=x[i];
2478: p2[thetai]=x[thetai]+delti[thetai]/k;
2479: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2480: k1=func(p2)-fx;
2481:
2482: p2[thetai]=x[thetai]+delti[thetai]/k;
2483: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2484: k2=func(p2)-fx;
2485:
2486: p2[thetai]=x[thetai]-delti[thetai]/k;
2487: p2[thetaj]=x[thetaj]+delti[thetaj]/k;
2488: k3=func(p2)-fx;
2489:
2490: p2[thetai]=x[thetai]-delti[thetai]/k;
2491: p2[thetaj]=x[thetaj]-delti[thetaj]/k;
2492: k4=func(p2)-fx;
2493: res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
2494: #ifdef DEBUG
2495: 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);
2496: 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);
2497: #endif
2498: }
2499: return res;
2500: }
2501:
2502: /************** Inverse of matrix **************/
2503: void ludcmp(double **a, int n, int *indx, double *d)
2504: {
2505: int i,imax,j,k;
2506: double big,dum,sum,temp;
2507: double *vv;
2508:
2509: vv=vector(1,n);
2510: *d=1.0;
2511: for (i=1;i<=n;i++) {
2512: big=0.0;
2513: for (j=1;j<=n;j++)
2514: if ((temp=fabs(a[i][j])) > big) big=temp;
2515: if (big == 0.0) nrerror("Singular matrix in routine ludcmp");
2516: vv[i]=1.0/big;
2517: }
2518: for (j=1;j<=n;j++) {
2519: for (i=1;i<j;i++) {
2520: sum=a[i][j];
2521: for (k=1;k<i;k++) sum -= a[i][k]*a[k][j];
2522: a[i][j]=sum;
2523: }
2524: big=0.0;
2525: for (i=j;i<=n;i++) {
2526: sum=a[i][j];
2527: for (k=1;k<j;k++)
2528: sum -= a[i][k]*a[k][j];
2529: a[i][j]=sum;
2530: if ( (dum=vv[i]*fabs(sum)) >= big) {
2531: big=dum;
2532: imax=i;
2533: }
2534: }
2535: if (j != imax) {
2536: for (k=1;k<=n;k++) {
2537: dum=a[imax][k];
2538: a[imax][k]=a[j][k];
2539: a[j][k]=dum;
2540: }
2541: *d = -(*d);
2542: vv[imax]=vv[j];
2543: }
2544: indx[j]=imax;
2545: if (a[j][j] == 0.0) a[j][j]=TINY;
2546: if (j != n) {
2547: dum=1.0/(a[j][j]);
2548: for (i=j+1;i<=n;i++) a[i][j] *= dum;
2549: }
2550: }
2551: free_vector(vv,1,n); /* Doesn't work */
2552: ;
2553: }
2554:
2555: void lubksb(double **a, int n, int *indx, double b[])
2556: {
2557: int i,ii=0,ip,j;
2558: double sum;
2559:
2560: for (i=1;i<=n;i++) {
2561: ip=indx[i];
2562: sum=b[ip];
2563: b[ip]=b[i];
2564: if (ii)
2565: for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
2566: else if (sum) ii=i;
2567: b[i]=sum;
2568: }
2569: for (i=n;i>=1;i--) {
2570: sum=b[i];
2571: for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
2572: b[i]=sum/a[i][i];
2573: }
2574: }
2575:
2576: void pstamp(FILE *fichier)
2577: {
2578: fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
2579: }
2580:
2581: /************ Frequencies ********************/
2582: 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[])
2583: { /* Some frequencies */
2584:
2585: int i, m, jk, j1, bool, z1,j;
2586: int first;
2587: double ***freq; /* Frequencies */
2588: double *pp, **prop;
2589: double pos,posprop, k2, dateintsum=0,k2cpt=0;
2590: char fileresp[FILENAMELENGTH];
2591:
2592: pp=vector(1,nlstate);
2593: prop=matrix(1,nlstate,iagemin,iagemax+3);
2594: strcpy(fileresp,"p");
2595: strcat(fileresp,fileres);
2596: if((ficresp=fopen(fileresp,"w"))==NULL) {
2597: printf("Problem with prevalence resultfile: %s\n", fileresp);
2598: fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
2599: exit(0);
2600: }
2601: freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
2602: j1=0;
2603:
2604: j=cptcoveff;
2605: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2606:
2607: first=1;
2608:
2609: /* for(k1=1; k1<=j ; k1++){ */ /* Loop on covariates */
2610: /* for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
2611: /* j1++; */
2612: for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
2613: /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
2614: scanf("%d", i);*/
2615: for (i=-5; i<=nlstate+ndeath; i++)
2616: for (jk=-5; jk<=nlstate+ndeath; jk++)
2617: for(m=iagemin; m <= iagemax+3; m++)
2618: freq[i][jk][m]=0;
2619:
2620: for (i=1; i<=nlstate; i++)
2621: for(m=iagemin; m <= iagemax+3; m++)
2622: prop[i][m]=0;
2623:
2624: dateintsum=0;
2625: k2cpt=0;
2626: for (i=1; i<=imx; i++) {
2627: bool=1;
2628: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
2629: for (z1=1; z1<=cptcoveff; z1++)
2630: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
2631: /* Tests if the value of each of the covariates of i is equal to filter j1 */
2632: bool=0;
2633: /* 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",
2634: bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
2635: j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
2636: /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
2637: }
2638: }
2639:
2640: if (bool==1){
2641: for(m=firstpass; m<=lastpass; m++){
2642: k2=anint[m][i]+(mint[m][i]/12.);
2643: /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
2644: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2645: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2646: if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
2647: if (m<lastpass) {
2648: freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
2649: freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
2650: }
2651:
2652: if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
2653: dateintsum=dateintsum+k2;
2654: k2cpt++;
2655: }
2656: /*}*/
2657: }
2658: }
2659: } /* end i */
2660:
2661: /* fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
2662: pstamp(ficresp);
2663: if (cptcovn>0) {
2664: fprintf(ficresp, "\n#********** Variable ");
2665: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2666: fprintf(ficresp, "**********\n#");
2667: fprintf(ficlog, "\n#********** Variable ");
2668: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
2669: fprintf(ficlog, "**********\n#");
2670: }
2671: for(i=1; i<=nlstate;i++)
2672: fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
2673: fprintf(ficresp, "\n");
2674:
2675: for(i=iagemin; i <= iagemax+3; i++){
2676: if(i==iagemax+3){
2677: fprintf(ficlog,"Total");
2678: }else{
2679: if(first==1){
2680: first=0;
2681: printf("See log file for details...\n");
2682: }
2683: fprintf(ficlog,"Age %d", i);
2684: }
2685: for(jk=1; jk <=nlstate ; jk++){
2686: for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
2687: pp[jk] += freq[jk][m][i];
2688: }
2689: for(jk=1; jk <=nlstate ; jk++){
2690: for(m=-1, pos=0; m <=0 ; m++)
2691: pos += freq[jk][m][i];
2692: if(pp[jk]>=1.e-10){
2693: if(first==1){
2694: printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
2695: }
2696: fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
2697: }else{
2698: if(first==1)
2699: printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2700: fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
2701: }
2702: }
2703:
2704: for(jk=1; jk <=nlstate ; jk++){
2705: for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
2706: pp[jk] += freq[jk][m][i];
2707: }
2708: for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
2709: pos += pp[jk];
2710: posprop += prop[jk][i];
2711: }
2712: for(jk=1; jk <=nlstate ; jk++){
2713: if(pos>=1.e-5){
2714: if(first==1)
2715: printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2716: fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
2717: }else{
2718: if(first==1)
2719: printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2720: fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
2721: }
2722: if( i <= iagemax){
2723: if(pos>=1.e-5){
2724: fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
2725: /*probs[i][jk][j1]= pp[jk]/pos;*/
2726: /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
2727: }
2728: else
2729: fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
2730: }
2731: }
2732:
2733: for(jk=-1; jk <=nlstate+ndeath; jk++)
2734: for(m=-1; m <=nlstate+ndeath; m++)
2735: if(freq[jk][m][i] !=0 ) {
2736: if(first==1)
2737: printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
2738: fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
2739: }
2740: if(i <= iagemax)
2741: fprintf(ficresp,"\n");
2742: if(first==1)
2743: printf("Others in log...\n");
2744: fprintf(ficlog,"\n");
2745: }
2746: /*}*/
2747: }
2748: dateintmean=dateintsum/k2cpt;
2749:
2750: fclose(ficresp);
2751: free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
2752: free_vector(pp,1,nlstate);
2753: free_matrix(prop,1,nlstate,iagemin, iagemax+3);
2754: /* End of Freq */
2755: }
2756:
2757: /************ Prevalence ********************/
2758: 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)
2759: {
2760: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
2761: in each health status at the date of interview (if between dateprev1 and dateprev2).
2762: We still use firstpass and lastpass as another selection.
2763: */
2764:
2765: int i, m, jk, j1, bool, z1,j;
2766:
2767: double **prop;
2768: double posprop;
2769: double y2; /* in fractional years */
2770: int iagemin, iagemax;
2771: int first; /** to stop verbosity which is redirected to log file */
2772:
2773: iagemin= (int) agemin;
2774: iagemax= (int) agemax;
2775: /*pp=vector(1,nlstate);*/
2776: prop=matrix(1,nlstate,iagemin,iagemax+3);
2777: /* freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
2778: j1=0;
2779:
2780: /*j=cptcoveff;*/
2781: if (cptcovn<1) {j=1;ncodemax[1]=1;}
2782:
2783: first=1;
2784: for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
2785: /*for(i1=1; i1<=ncodemax[k1];i1++){
2786: j1++;*/
2787:
2788: for (i=1; i<=nlstate; i++)
2789: for(m=iagemin; m <= iagemax+3; m++)
2790: prop[i][m]=0.0;
2791:
2792: for (i=1; i<=imx; i++) { /* Each individual */
2793: bool=1;
2794: if (cptcovn>0) {
2795: for (z1=1; z1<=cptcoveff; z1++)
2796: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]])
2797: bool=0;
2798: }
2799: if (bool==1) {
2800: for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
2801: y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
2802: if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
2803: if(agev[m][i]==0) agev[m][i]=iagemax+1;
2804: if(agev[m][i]==1) agev[m][i]=iagemax+2;
2805: 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);
2806: if (s[m][i]>0 && s[m][i]<=nlstate) {
2807: /*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]]);*/
2808: prop[s[m][i]][(int)agev[m][i]] += weight[i];
2809: prop[s[m][i]][iagemax+3] += weight[i];
2810: }
2811: }
2812: } /* end selection of waves */
2813: }
2814: }
2815: for(i=iagemin; i <= iagemax+3; i++){
2816: for(jk=1,posprop=0; jk <=nlstate ; jk++) {
2817: posprop += prop[jk][i];
2818: }
2819:
2820: for(jk=1; jk <=nlstate ; jk++){
2821: if( i <= iagemax){
2822: if(posprop>=1.e-5){
2823: probs[i][jk][j1]= prop[jk][i]/posprop;
2824: } else{
2825: if(first==1){
2826: first=0;
2827: 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]);
2828: }
2829: }
2830: }
2831: }/* end jk */
2832: }/* end i */
2833: /*} *//* end i1 */
2834: } /* end j1 */
2835:
2836: /* free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
2837: /*free_vector(pp,1,nlstate);*/
2838: free_matrix(prop,1,nlstate, iagemin,iagemax+3);
2839: } /* End of prevalence */
2840:
2841: /************* Waves Concatenation ***************/
2842:
2843: 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)
2844: {
2845: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
2846: Death is a valid wave (if date is known).
2847: mw[mi][i] is the mi (mi=1 to wav[i]) effective wave of individual i
2848: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
2849: and mw[mi+1][i]. dh depends on stepm.
2850: */
2851:
2852: int i, mi, m;
2853: /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
2854: double sum=0., jmean=0.;*/
2855: int first;
2856: int j, k=0,jk, ju, jl;
2857: double sum=0.;
2858: first=0;
2859: jmin=100000;
2860: jmax=-1;
2861: jmean=0.;
2862: for(i=1; i<=imx; i++){
2863: mi=0;
2864: m=firstpass;
2865: while(s[m][i] <= nlstate){
2866: if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
2867: mw[++mi][i]=m;
2868: if(m >=lastpass)
2869: break;
2870: else
2871: m++;
2872: }/* end while */
2873: if (s[m][i] > nlstate){
2874: mi++; /* Death is another wave */
2875: /* if(mi==0) never been interviewed correctly before death */
2876: /* Only death is a correct wave */
2877: mw[mi][i]=m;
2878: }
2879:
2880: wav[i]=mi;
2881: if(mi==0){
2882: nbwarn++;
2883: if(first==0){
2884: printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
2885: first=1;
2886: }
2887: if(first==1){
2888: fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
2889: }
2890: } /* end mi==0 */
2891: } /* End individuals */
2892:
2893: for(i=1; i<=imx; i++){
2894: for(mi=1; mi<wav[i];mi++){
2895: if (stepm <=0)
2896: dh[mi][i]=1;
2897: else{
2898: if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
2899: if (agedc[i] < 2*AGESUP) {
2900: j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12);
2901: if(j==0) j=1; /* Survives at least one month after exam */
2902: else if(j<0){
2903: nberr++;
2904: 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]);
2905: j=1; /* Temporary Dangerous patch */
2906: 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);
2907: 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]);
2908: 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);
2909: }
2910: k=k+1;
2911: if (j >= jmax){
2912: jmax=j;
2913: ijmax=i;
2914: }
2915: if (j <= jmin){
2916: jmin=j;
2917: ijmin=i;
2918: }
2919: sum=sum+j;
2920: /*if (j<0) printf("j=%d num=%d \n",j,i);*/
2921: /* printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
2922: }
2923: }
2924: else{
2925: j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
2926: /* 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]); */
2927:
2928: k=k+1;
2929: if (j >= jmax) {
2930: jmax=j;
2931: ijmax=i;
2932: }
2933: else if (j <= jmin){
2934: jmin=j;
2935: ijmin=i;
2936: }
2937: /* if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
2938: /*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]);*/
2939: if(j<0){
2940: nberr++;
2941: 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]);
2942: 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]);
2943: }
2944: sum=sum+j;
2945: }
2946: jk= j/stepm;
2947: jl= j -jk*stepm;
2948: ju= j -(jk+1)*stepm;
2949: if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
2950: if(jl==0){
2951: dh[mi][i]=jk;
2952: bh[mi][i]=0;
2953: }else{ /* We want a negative bias in order to only have interpolation ie
2954: * to avoid the price of an extra matrix product in likelihood */
2955: dh[mi][i]=jk+1;
2956: bh[mi][i]=ju;
2957: }
2958: }else{
2959: if(jl <= -ju){
2960: dh[mi][i]=jk;
2961: bh[mi][i]=jl; /* bias is positive if real duration
2962: * is higher than the multiple of stepm and negative otherwise.
2963: */
2964: }
2965: else{
2966: dh[mi][i]=jk+1;
2967: bh[mi][i]=ju;
2968: }
2969: if(dh[mi][i]==0){
2970: dh[mi][i]=1; /* At least one step */
2971: bh[mi][i]=ju; /* At least one step */
2972: /* 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);*/
2973: }
2974: } /* end if mle */
2975: }
2976: } /* end wave */
2977: }
2978: jmean=sum/k;
2979: 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);
2980: 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);
2981: }
2982:
2983: /*********** Tricode ****************************/
2984: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
2985: {
2986: /**< Uses cptcovn+2*cptcovprod as the number of covariates */
2987: /* Tvar[i]=atoi(stre); find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1
2988: * Boring subroutine which should only output nbcode[Tvar[j]][k]
2989: * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
2990: * nbcode[Tvar[j]][1]=
2991: */
2992:
2993: int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
2994: int modmaxcovj=0; /* Modality max of covariates j */
2995: int cptcode=0; /* Modality max of covariates j */
2996: int modmincovj=0; /* Modality min of covariates j */
2997:
2998:
2999: cptcoveff=0;
3000:
3001: for (k=-1; k < maxncov; k++) Ndum[k]=0;
3002: for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
3003:
3004: /* Loop on covariates without age and products */
3005: for (j=1; j<=(cptcovs); j++) { /* model V1 + V2*age+ V3 + V3*V4 : V1 + V3 = 2 only */
3006: for (i=1; i<=imx; i++) { /* Lopp on individuals: reads the data file to get the maximum value of the
3007: modality of this covariate Vj*/
3008: ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
3009: * If product of Vn*Vm, still boolean *:
3010: * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
3011: * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0 */
3012: /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
3013: modality of the nth covariate of individual i. */
3014: if (ij > modmaxcovj)
3015: modmaxcovj=ij;
3016: else if (ij < modmincovj)
3017: modmincovj=ij;
3018: if ((ij < -1) && (ij > NCOVMAX)){
3019: printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
3020: exit(1);
3021: }else
3022: Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
3023: /* If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
3024: /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
3025: /* getting the maximum value of the modality of the covariate
3026: (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
3027: female is 1, then modmaxcovj=1.*/
3028: }
3029: printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
3030: cptcode=modmaxcovj;
3031: /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
3032: /*for (i=0; i<=cptcode; i++) {*/
3033: for (i=modmincovj; i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
3034: printf("Frequencies of covariates %d V%d %d\n", j, Tvar[j], Ndum[i]);
3035: if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
3036: ncodemax[j]++; /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
3037: }
3038: /* In fact ncodemax[j]=2 (dichotom. variables only) but it could be more for
3039: historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
3040: } /* Ndum[-1] number of undefined modalities */
3041:
3042: /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
3043: /* For covariate j, modalities could be 1, 2, 3, 4. If Ndum[2]=0 ncodemax[j] is not 4 but 3 */
3044: /* If Ndum[3}= 635; Ndum[4]=0; Ndum[5]=0; Ndum[6]=27; Ndum[7]=125;
3045: modmincovj=3; modmaxcovj = 7;
3046: There are only 3 modalities non empty (or 2 if 27 is too few) : ncodemax[j]=3;
3047: which will be coded 0, 1, 2 which in binary on 3-1 digits are 0=00 1=01, 2=10; defining two dummy
3048: variables V1_1 and V1_2.
3049: nbcode[Tvar[j]][ij]=k;
3050: nbcode[Tvar[j]][1]=0;
3051: nbcode[Tvar[j]][2]=1;
3052: nbcode[Tvar[j]][3]=2;
3053: */
3054: ij=1; /* ij is similar to i but can jumps over null modalities */
3055: for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
3056: for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
3057: /*recode from 0 */
3058: if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
3059: nbcode[Tvar[j]][ij]=k; /* stores the modality in an array nbcode.
3060: k is a modality. If we have model=V1+V1*sex
3061: then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
3062: ij++;
3063: }
3064: if (ij > ncodemax[j]) break;
3065: } /* end of loop on */
3066: } /* end of loop on modality */
3067: } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/
3068:
3069: for (k=-1; k< maxncov; k++) Ndum[k]=0;
3070:
3071: for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */
3072: /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
3073: ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
3074: Ndum[ij]++;
3075: }
3076:
3077: ij=1;
3078: for (i=0; i<= maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
3079: /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
3080: if((Ndum[i]!=0) && (i<=ncovcol)){
3081: /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
3082: Tvaraff[ij]=i; /*For printing (unclear) */
3083: ij++;
3084: }else
3085: Tvaraff[ij]=0;
3086: }
3087: ij--;
3088: cptcoveff=ij; /*Number of total covariates*/
3089:
3090: }
3091:
3092:
3093: /*********** Health Expectancies ****************/
3094:
3095: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
3096:
3097: {
3098: /* Health expectancies, no variances */
3099: int i, j, nhstepm, hstepm, h, nstepm;
3100: int nhstepma, nstepma; /* Decreasing with age */
3101: double age, agelim, hf;
3102: double ***p3mat;
3103: double eip;
3104:
3105: pstamp(ficreseij);
3106: fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
3107: fprintf(ficreseij,"# Age");
3108: for(i=1; i<=nlstate;i++){
3109: for(j=1; j<=nlstate;j++){
3110: fprintf(ficreseij," e%1d%1d ",i,j);
3111: }
3112: fprintf(ficreseij," e%1d. ",i);
3113: }
3114: fprintf(ficreseij,"\n");
3115:
3116:
3117: if(estepm < stepm){
3118: printf ("Problem %d lower than %d\n",estepm, stepm);
3119: }
3120: else hstepm=estepm;
3121: /* We compute the life expectancy from trapezoids spaced every estepm months
3122: * This is mainly to measure the difference between two models: for example
3123: * if stepm=24 months pijx are given only every 2 years and by summing them
3124: * we are calculating an estimate of the Life Expectancy assuming a linear
3125: * progression in between and thus overestimating or underestimating according
3126: * to the curvature of the survival function. If, for the same date, we
3127: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3128: * to compare the new estimate of Life expectancy with the same linear
3129: * hypothesis. A more precise result, taking into account a more precise
3130: * curvature will be obtained if estepm is as small as stepm. */
3131:
3132: /* For example we decided to compute the life expectancy with the smallest unit */
3133: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3134: nhstepm is the number of hstepm from age to agelim
3135: nstepm is the number of stepm from age to agelin.
3136: Look at hpijx to understand the reason of that which relies in memory size
3137: and note for a fixed period like estepm months */
3138: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3139: survival function given by stepm (the optimization length). Unfortunately it
3140: means that if the survival funtion is printed only each two years of age and if
3141: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3142: results. So we changed our mind and took the option of the best precision.
3143: */
3144: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3145:
3146: agelim=AGESUP;
3147: /* If stepm=6 months */
3148: /* Computed by stepm unit matrices, product of hstepm matrices, stored
3149: in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
3150:
3151: /* nhstepm age range expressed in number of stepm */
3152: nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3153: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3154: /* if (stepm >= YEARM) hstepm=1;*/
3155: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3156: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3157:
3158: for (age=bage; age<=fage; age ++){
3159: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3160: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3161: /* if (stepm >= YEARM) hstepm=1;*/
3162: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3163:
3164: /* If stepm=6 months */
3165: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3166: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3167:
3168: hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3169:
3170: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3171:
3172: printf("%d|",(int)age);fflush(stdout);
3173: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3174:
3175: /* Computing expectancies */
3176: for(i=1; i<=nlstate;i++)
3177: for(j=1; j<=nlstate;j++)
3178: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3179: eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
3180:
3181: /* 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]);*/
3182:
3183: }
3184:
3185: fprintf(ficreseij,"%3.0f",age );
3186: for(i=1; i<=nlstate;i++){
3187: eip=0;
3188: for(j=1; j<=nlstate;j++){
3189: eip +=eij[i][j][(int)age];
3190: fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
3191: }
3192: fprintf(ficreseij,"%9.4f", eip );
3193: }
3194: fprintf(ficreseij,"\n");
3195:
3196: }
3197: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3198: printf("\n");
3199: fprintf(ficlog,"\n");
3200:
3201: }
3202:
3203: 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[] )
3204:
3205: {
3206: /* Covariances of health expectancies eij and of total life expectancies according
3207: to initial status i, ei. .
3208: */
3209: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
3210: int nhstepma, nstepma; /* Decreasing with age */
3211: double age, agelim, hf;
3212: double ***p3matp, ***p3matm, ***varhe;
3213: double **dnewm,**doldm;
3214: double *xp, *xm;
3215: double **gp, **gm;
3216: double ***gradg, ***trgradg;
3217: int theta;
3218:
3219: double eip, vip;
3220:
3221: varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
3222: xp=vector(1,npar);
3223: xm=vector(1,npar);
3224: dnewm=matrix(1,nlstate*nlstate,1,npar);
3225: doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
3226:
3227: pstamp(ficresstdeij);
3228: fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
3229: fprintf(ficresstdeij,"# Age");
3230: for(i=1; i<=nlstate;i++){
3231: for(j=1; j<=nlstate;j++)
3232: fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
3233: fprintf(ficresstdeij," e%1d. ",i);
3234: }
3235: fprintf(ficresstdeij,"\n");
3236:
3237: pstamp(ficrescveij);
3238: fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
3239: fprintf(ficrescveij,"# Age");
3240: for(i=1; i<=nlstate;i++)
3241: for(j=1; j<=nlstate;j++){
3242: cptj= (j-1)*nlstate+i;
3243: for(i2=1; i2<=nlstate;i2++)
3244: for(j2=1; j2<=nlstate;j2++){
3245: cptj2= (j2-1)*nlstate+i2;
3246: if(cptj2 <= cptj)
3247: fprintf(ficrescveij," %1d%1d,%1d%1d",i,j,i2,j2);
3248: }
3249: }
3250: fprintf(ficrescveij,"\n");
3251:
3252: if(estepm < stepm){
3253: printf ("Problem %d lower than %d\n",estepm, stepm);
3254: }
3255: else hstepm=estepm;
3256: /* We compute the life expectancy from trapezoids spaced every estepm months
3257: * This is mainly to measure the difference between two models: for example
3258: * if stepm=24 months pijx are given only every 2 years and by summing them
3259: * we are calculating an estimate of the Life Expectancy assuming a linear
3260: * progression in between and thus overestimating or underestimating according
3261: * to the curvature of the survival function. If, for the same date, we
3262: * estimate the model with stepm=1 month, we can keep estepm to 24 months
3263: * to compare the new estimate of Life expectancy with the same linear
3264: * hypothesis. A more precise result, taking into account a more precise
3265: * curvature will be obtained if estepm is as small as stepm. */
3266:
3267: /* For example we decided to compute the life expectancy with the smallest unit */
3268: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3269: nhstepm is the number of hstepm from age to agelim
3270: nstepm is the number of stepm from age to agelin.
3271: Look at hpijx to understand the reason of that which relies in memory size
3272: and note for a fixed period like estepm months */
3273: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3274: survival function given by stepm (the optimization length). Unfortunately it
3275: means that if the survival funtion is printed only each two years of age and if
3276: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3277: results. So we changed our mind and took the option of the best precision.
3278: */
3279: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3280:
3281: /* If stepm=6 months */
3282: /* nhstepm age range expressed in number of stepm */
3283: agelim=AGESUP;
3284: nstepm=(int) rint((agelim-bage)*YEARM/stepm);
3285: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3286: /* if (stepm >= YEARM) hstepm=1;*/
3287: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3288:
3289: p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3290: p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3291: gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
3292: trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
3293: gp=matrix(0,nhstepm,1,nlstate*nlstate);
3294: gm=matrix(0,nhstepm,1,nlstate*nlstate);
3295:
3296: for (age=bage; age<=fage; age ++){
3297: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
3298: /* Typically if 20 years nstepm = 20*12/6=40 stepm */
3299: /* if (stepm >= YEARM) hstepm=1;*/
3300: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
3301:
3302: /* If stepm=6 months */
3303: /* Computed by stepm unit matrices, product of hstepma matrices, stored
3304: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
3305:
3306: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3307:
3308: /* Computing Variances of health expectancies */
3309: /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
3310: decrease memory allocation */
3311: for(theta=1; theta <=npar; theta++){
3312: for(i=1; i<=npar; i++){
3313: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3314: xm[i] = x[i] - (i==theta ?delti[theta]:0);
3315: }
3316: hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);
3317: hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);
3318:
3319: for(j=1; j<= nlstate; j++){
3320: for(i=1; i<=nlstate; i++){
3321: for(h=0; h<=nhstepm-1; h++){
3322: gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
3323: gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
3324: }
3325: }
3326: }
3327:
3328: for(ij=1; ij<= nlstate*nlstate; ij++)
3329: for(h=0; h<=nhstepm-1; h++){
3330: gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
3331: }
3332: }/* End theta */
3333:
3334:
3335: for(h=0; h<=nhstepm-1; h++)
3336: for(j=1; j<=nlstate*nlstate;j++)
3337: for(theta=1; theta <=npar; theta++)
3338: trgradg[h][j][theta]=gradg[h][theta][j];
3339:
3340:
3341: for(ij=1;ij<=nlstate*nlstate;ij++)
3342: for(ji=1;ji<=nlstate*nlstate;ji++)
3343: varhe[ij][ji][(int)age] =0.;
3344:
3345: printf("%d|",(int)age);fflush(stdout);
3346: fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
3347: for(h=0;h<=nhstepm-1;h++){
3348: for(k=0;k<=nhstepm-1;k++){
3349: matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
3350: matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
3351: for(ij=1;ij<=nlstate*nlstate;ij++)
3352: for(ji=1;ji<=nlstate*nlstate;ji++)
3353: varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
3354: }
3355: }
3356:
3357: /* Computing expectancies */
3358: hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);
3359: for(i=1; i<=nlstate;i++)
3360: for(j=1; j<=nlstate;j++)
3361: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
3362: eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
3363:
3364: /* 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]);*/
3365:
3366: }
3367:
3368: fprintf(ficresstdeij,"%3.0f",age );
3369: for(i=1; i<=nlstate;i++){
3370: eip=0.;
3371: vip=0.;
3372: for(j=1; j<=nlstate;j++){
3373: eip += eij[i][j][(int)age];
3374: for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
3375: vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
3376: fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
3377: }
3378: fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
3379: }
3380: fprintf(ficresstdeij,"\n");
3381:
3382: fprintf(ficrescveij,"%3.0f",age );
3383: for(i=1; i<=nlstate;i++)
3384: for(j=1; j<=nlstate;j++){
3385: cptj= (j-1)*nlstate+i;
3386: for(i2=1; i2<=nlstate;i2++)
3387: for(j2=1; j2<=nlstate;j2++){
3388: cptj2= (j2-1)*nlstate+i2;
3389: if(cptj2 <= cptj)
3390: fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
3391: }
3392: }
3393: fprintf(ficrescveij,"\n");
3394:
3395: }
3396: free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
3397: free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
3398: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
3399: free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
3400: free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3401: free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3402: printf("\n");
3403: fprintf(ficlog,"\n");
3404:
3405: free_vector(xm,1,npar);
3406: free_vector(xp,1,npar);
3407: free_matrix(dnewm,1,nlstate*nlstate,1,npar);
3408: free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
3409: free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
3410: }
3411:
3412: /************ Variance ******************/
3413: 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[])
3414: {
3415: /* Variance of health expectancies */
3416: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
3417: /* double **newm;*/
3418: /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
3419:
3420: int movingaverage();
3421: double **dnewm,**doldm;
3422: double **dnewmp,**doldmp;
3423: int i, j, nhstepm, hstepm, h, nstepm ;
3424: int k;
3425: double *xp;
3426: double **gp, **gm; /* for var eij */
3427: double ***gradg, ***trgradg; /*for var eij */
3428: double **gradgp, **trgradgp; /* for var p point j */
3429: double *gpp, *gmp; /* for var p point j */
3430: double **varppt; /* for var p point j nlstate to nlstate+ndeath */
3431: double ***p3mat;
3432: double age,agelim, hf;
3433: double ***mobaverage;
3434: int theta;
3435: char digit[4];
3436: char digitp[25];
3437:
3438: char fileresprobmorprev[FILENAMELENGTH];
3439:
3440: if(popbased==1){
3441: if(mobilav!=0)
3442: strcpy(digitp,"-populbased-mobilav-");
3443: else strcpy(digitp,"-populbased-nomobil-");
3444: }
3445: else
3446: strcpy(digitp,"-stablbased-");
3447:
3448: if (mobilav!=0) {
3449: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3450: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
3451: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
3452: printf(" Error in movingaverage mobilav=%d\n",mobilav);
3453: }
3454: }
3455:
3456: strcpy(fileresprobmorprev,"prmorprev");
3457: sprintf(digit,"%-d",ij);
3458: /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
3459: strcat(fileresprobmorprev,digit); /* Tvar to be done */
3460: strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
3461: strcat(fileresprobmorprev,fileres);
3462: if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
3463: printf("Problem with resultfile: %s\n", fileresprobmorprev);
3464: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
3465: }
3466: printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3467:
3468: fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
3469: pstamp(ficresprobmorprev);
3470: 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);
3471: fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
3472: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3473: fprintf(ficresprobmorprev," p.%-d SE",j);
3474: for(i=1; i<=nlstate;i++)
3475: fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
3476: }
3477: fprintf(ficresprobmorprev,"\n");
3478: fprintf(ficgp,"\n# Routine varevsij");
3479: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
3480: 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");
3481: fprintf(fichtm,"\n<br>%s <br>\n",digitp);
3482: /* } */
3483: varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3484: pstamp(ficresvij);
3485: fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n# (weighted average of eij where weights are ");
3486: if(popbased==1)
3487: 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);
3488: else
3489: fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
3490: fprintf(ficresvij,"# Age");
3491: for(i=1; i<=nlstate;i++)
3492: for(j=1; j<=nlstate;j++)
3493: fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
3494: fprintf(ficresvij,"\n");
3495:
3496: xp=vector(1,npar);
3497: dnewm=matrix(1,nlstate,1,npar);
3498: doldm=matrix(1,nlstate,1,nlstate);
3499: dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
3500: doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3501:
3502: gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
3503: gpp=vector(nlstate+1,nlstate+ndeath);
3504: gmp=vector(nlstate+1,nlstate+ndeath);
3505: trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
3506:
3507: if(estepm < stepm){
3508: printf ("Problem %d lower than %d\n",estepm, stepm);
3509: }
3510: else hstepm=estepm;
3511: /* For example we decided to compute the life expectancy with the smallest unit */
3512: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm.
3513: nhstepm is the number of hstepm from age to agelim
3514: nstepm is the number of stepm from age to agelin.
3515: Look at function hpijx to understand why (it is linked to memory size questions) */
3516: /* We decided (b) to get a life expectancy respecting the most precise curvature of the
3517: survival function given by stepm (the optimization length). Unfortunately it
3518: means that if the survival funtion is printed every two years of age and if
3519: you sum them up and add 1 year (area under the trapezoids) you won't get the same
3520: results. So we changed our mind and took the option of the best precision.
3521: */
3522: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */
3523: agelim = AGESUP;
3524: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3525: nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3526: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
3527: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3528: gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
3529: gp=matrix(0,nhstepm,1,nlstate);
3530: gm=matrix(0,nhstepm,1,nlstate);
3531:
3532:
3533: for(theta=1; theta <=npar; theta++){
3534: for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
3535: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3536: }
3537: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3538: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3539:
3540: if (popbased==1) {
3541: if(mobilav ==0){
3542: for(i=1; i<=nlstate;i++)
3543: prlim[i][i]=probs[(int)age][i][ij];
3544: }else{ /* mobilav */
3545: for(i=1; i<=nlstate;i++)
3546: prlim[i][i]=mobaverage[(int)age][i][ij];
3547: }
3548: }
3549:
3550: for(j=1; j<= nlstate; j++){
3551: for(h=0; h<=nhstepm; h++){
3552: for(i=1, gp[h][j]=0.;i<=nlstate;i++)
3553: gp[h][j] += prlim[i][i]*p3mat[i][j][h];
3554: }
3555: }
3556: /* This for computing probability of death (h=1 means
3557: computed over hstepm matrices product = hstepm*stepm months)
3558: as a weighted average of prlim.
3559: */
3560: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3561: for(i=1,gpp[j]=0.; i<= nlstate; i++)
3562: gpp[j] += prlim[i][i]*p3mat[i][j][1];
3563: }
3564: /* end probability of death */
3565:
3566: for(i=1; i<=npar; i++) /* Computes gradient x - delta */
3567: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3568: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);
3569: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3570:
3571: if (popbased==1) {
3572: if(mobilav ==0){
3573: for(i=1; i<=nlstate;i++)
3574: prlim[i][i]=probs[(int)age][i][ij];
3575: }else{ /* mobilav */
3576: for(i=1; i<=nlstate;i++)
3577: prlim[i][i]=mobaverage[(int)age][i][ij];
3578: }
3579: }
3580:
3581: for(j=1; j<= nlstate; j++){ /* Sum of wi * eij = e.j */
3582: for(h=0; h<=nhstepm; h++){
3583: for(i=1, gm[h][j]=0.;i<=nlstate;i++)
3584: gm[h][j] += prlim[i][i]*p3mat[i][j][h];
3585: }
3586: }
3587: /* This for computing probability of death (h=1 means
3588: computed over hstepm matrices product = hstepm*stepm months)
3589: as a weighted average of prlim.
3590: */
3591: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3592: for(i=1,gmp[j]=0.; i<= nlstate; i++)
3593: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3594: }
3595: /* end probability of death */
3596:
3597: for(j=1; j<= nlstate; j++) /* vareij */
3598: for(h=0; h<=nhstepm; h++){
3599: gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
3600: }
3601:
3602: for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
3603: gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
3604: }
3605:
3606: } /* End theta */
3607:
3608: trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
3609:
3610: for(h=0; h<=nhstepm; h++) /* veij */
3611: for(j=1; j<=nlstate;j++)
3612: for(theta=1; theta <=npar; theta++)
3613: trgradg[h][j][theta]=gradg[h][theta][j];
3614:
3615: for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
3616: for(theta=1; theta <=npar; theta++)
3617: trgradgp[j][theta]=gradgp[theta][j];
3618:
3619:
3620: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */
3621: for(i=1;i<=nlstate;i++)
3622: for(j=1;j<=nlstate;j++)
3623: vareij[i][j][(int)age] =0.;
3624:
3625: for(h=0;h<=nhstepm;h++){
3626: for(k=0;k<=nhstepm;k++){
3627: matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
3628: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
3629: for(i=1;i<=nlstate;i++)
3630: for(j=1;j<=nlstate;j++)
3631: vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
3632: }
3633: }
3634:
3635: /* pptj */
3636: matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
3637: matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
3638: for(j=nlstate+1;j<=nlstate+ndeath;j++)
3639: for(i=nlstate+1;i<=nlstate+ndeath;i++)
3640: varppt[j][i]=doldmp[j][i];
3641: /* end ppptj */
3642: /* x centered again */
3643: hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);
3644: prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
3645:
3646: if (popbased==1) {
3647: if(mobilav ==0){
3648: for(i=1; i<=nlstate;i++)
3649: prlim[i][i]=probs[(int)age][i][ij];
3650: }else{ /* mobilav */
3651: for(i=1; i<=nlstate;i++)
3652: prlim[i][i]=mobaverage[(int)age][i][ij];
3653: }
3654: }
3655:
3656: /* This for computing probability of death (h=1 means
3657: computed over hstepm (estepm) matrices product = hstepm*stepm months)
3658: as a weighted average of prlim.
3659: */
3660: for(j=nlstate+1;j<=nlstate+ndeath;j++){
3661: for(i=1,gmp[j]=0.;i<= nlstate; i++)
3662: gmp[j] += prlim[i][i]*p3mat[i][j][1];
3663: }
3664: /* end probability of death */
3665:
3666: fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
3667: for(j=nlstate+1; j<=(nlstate+ndeath);j++){
3668: fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
3669: for(i=1; i<=nlstate;i++){
3670: fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
3671: }
3672: }
3673: fprintf(ficresprobmorprev,"\n");
3674:
3675: fprintf(ficresvij,"%.0f ",age );
3676: for(i=1; i<=nlstate;i++)
3677: for(j=1; j<=nlstate;j++){
3678: fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
3679: }
3680: fprintf(ficresvij,"\n");
3681: free_matrix(gp,0,nhstepm,1,nlstate);
3682: free_matrix(gm,0,nhstepm,1,nlstate);
3683: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
3684: free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
3685: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
3686: } /* End age */
3687: free_vector(gpp,nlstate+1,nlstate+ndeath);
3688: free_vector(gmp,nlstate+1,nlstate+ndeath);
3689: free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
3690: free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
3691: fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
3692: /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
3693: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
3694: /* fprintf(ficgp,"\n plot \"%s\" u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
3695: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
3696: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
3697: fprintf(ficgp,"\n plot \"%s\" u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
3698: fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
3699: fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
3700: fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
3701: 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);
3702: /* 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);
3703: */
3704: /* fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
3705: fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
3706:
3707: free_vector(xp,1,npar);
3708: free_matrix(doldm,1,nlstate,1,nlstate);
3709: free_matrix(dnewm,1,nlstate,1,npar);
3710: free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3711: free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
3712: free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
3713: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
3714: fclose(ficresprobmorprev);
3715: fflush(ficgp);
3716: fflush(fichtm);
3717: } /* end varevsij */
3718:
3719: /************ Variance of prevlim ******************/
3720: 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[])
3721: {
3722: /* Variance of prevalence limit */
3723: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
3724:
3725: double **dnewm,**doldm;
3726: int i, j, nhstepm, hstepm;
3727: double *xp;
3728: double *gp, *gm;
3729: double **gradg, **trgradg;
3730: double age,agelim;
3731: int theta;
3732:
3733: pstamp(ficresvpl);
3734: fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
3735: fprintf(ficresvpl,"# Age");
3736: for(i=1; i<=nlstate;i++)
3737: fprintf(ficresvpl," %1d-%1d",i,i);
3738: fprintf(ficresvpl,"\n");
3739:
3740: xp=vector(1,npar);
3741: dnewm=matrix(1,nlstate,1,npar);
3742: doldm=matrix(1,nlstate,1,nlstate);
3743:
3744: hstepm=1*YEARM; /* Every year of age */
3745: hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */
3746: agelim = AGESUP;
3747: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
3748: nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
3749: if (stepm >= YEARM) hstepm=1;
3750: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
3751: gradg=matrix(1,npar,1,nlstate);
3752: gp=vector(1,nlstate);
3753: gm=vector(1,nlstate);
3754:
3755: for(theta=1; theta <=npar; theta++){
3756: for(i=1; i<=npar; i++){ /* Computes gradient */
3757: xp[i] = x[i] + (i==theta ?delti[theta]:0);
3758: }
3759: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3760: for(i=1;i<=nlstate;i++)
3761: gp[i] = prlim[i][i];
3762:
3763: for(i=1; i<=npar; i++) /* Computes gradient */
3764: xp[i] = x[i] - (i==theta ?delti[theta]:0);
3765: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
3766: for(i=1;i<=nlstate;i++)
3767: gm[i] = prlim[i][i];
3768:
3769: for(i=1;i<=nlstate;i++)
3770: gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
3771: } /* End theta */
3772:
3773: trgradg =matrix(1,nlstate,1,npar);
3774:
3775: for(j=1; j<=nlstate;j++)
3776: for(theta=1; theta <=npar; theta++)
3777: trgradg[j][theta]=gradg[theta][j];
3778:
3779: for(i=1;i<=nlstate;i++)
3780: varpl[i][(int)age] =0.;
3781: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
3782: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
3783: for(i=1;i<=nlstate;i++)
3784: varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
3785:
3786: fprintf(ficresvpl,"%.0f ",age );
3787: for(i=1; i<=nlstate;i++)
3788: fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
3789: fprintf(ficresvpl,"\n");
3790: free_vector(gp,1,nlstate);
3791: free_vector(gm,1,nlstate);
3792: free_matrix(gradg,1,npar,1,nlstate);
3793: free_matrix(trgradg,1,nlstate,1,npar);
3794: } /* End age */
3795:
3796: free_vector(xp,1,npar);
3797: free_matrix(doldm,1,nlstate,1,npar);
3798: free_matrix(dnewm,1,nlstate,1,nlstate);
3799:
3800: }
3801:
3802: /************ Variance of one-step probabilities ******************/
3803: 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[])
3804: {
3805: int i, j=0, k1, l1, tj;
3806: int k2, l2, j1, z1;
3807: int k=0, l;
3808: int first=1, first1, first2;
3809: double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
3810: double **dnewm,**doldm;
3811: double *xp;
3812: double *gp, *gm;
3813: double **gradg, **trgradg;
3814: double **mu;
3815: double age, cov[NCOVMAX+1];
3816: double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
3817: int theta;
3818: char fileresprob[FILENAMELENGTH];
3819: char fileresprobcov[FILENAMELENGTH];
3820: char fileresprobcor[FILENAMELENGTH];
3821: double ***varpij;
3822:
3823: strcpy(fileresprob,"prob");
3824: strcat(fileresprob,fileres);
3825: if((ficresprob=fopen(fileresprob,"w"))==NULL) {
3826: printf("Problem with resultfile: %s\n", fileresprob);
3827: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
3828: }
3829: strcpy(fileresprobcov,"probcov");
3830: strcat(fileresprobcov,fileres);
3831: if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
3832: printf("Problem with resultfile: %s\n", fileresprobcov);
3833: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
3834: }
3835: strcpy(fileresprobcor,"probcor");
3836: strcat(fileresprobcor,fileres);
3837: if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
3838: printf("Problem with resultfile: %s\n", fileresprobcor);
3839: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
3840: }
3841: printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3842: fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
3843: printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3844: fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
3845: printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3846: fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
3847: pstamp(ficresprob);
3848: fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
3849: fprintf(ficresprob,"# Age");
3850: pstamp(ficresprobcov);
3851: fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
3852: fprintf(ficresprobcov,"# Age");
3853: pstamp(ficresprobcor);
3854: fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
3855: fprintf(ficresprobcor,"# Age");
3856:
3857:
3858: for(i=1; i<=nlstate;i++)
3859: for(j=1; j<=(nlstate+ndeath);j++){
3860: fprintf(ficresprob," p%1d-%1d (SE)",i,j);
3861: fprintf(ficresprobcov," p%1d-%1d ",i,j);
3862: fprintf(ficresprobcor," p%1d-%1d ",i,j);
3863: }
3864: /* fprintf(ficresprob,"\n");
3865: fprintf(ficresprobcov,"\n");
3866: fprintf(ficresprobcor,"\n");
3867: */
3868: xp=vector(1,npar);
3869: dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3870: doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
3871: mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
3872: varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
3873: first=1;
3874: fprintf(ficgp,"\n# Routine varprob");
3875: fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
3876: fprintf(fichtm,"\n");
3877:
3878: fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
3879: fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
3880: file %s<br>\n",optionfilehtmcov);
3881: fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
3882: and drawn. It helps understanding how is the covariance between two incidences.\
3883: They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
3884: 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. \
3885: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
3886: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
3887: standard deviations wide on each axis. <br>\
3888: Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
3889: and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
3890: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
3891:
3892: cov[1]=1;
3893: /* tj=cptcoveff; */
3894: tj = (int) pow(2,cptcoveff);
3895: if (cptcovn<1) {tj=1;ncodemax[1]=1;}
3896: j1=0;
3897: for(j1=1; j1<=tj;j1++){
3898: /*for(i1=1; i1<=ncodemax[t];i1++){ */
3899: /*j1++;*/
3900: if (cptcovn>0) {
3901: fprintf(ficresprob, "\n#********** Variable ");
3902: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3903: fprintf(ficresprob, "**********\n#\n");
3904: fprintf(ficresprobcov, "\n#********** Variable ");
3905: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3906: fprintf(ficresprobcov, "**********\n#\n");
3907:
3908: fprintf(ficgp, "\n#********** Variable ");
3909: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3910: fprintf(ficgp, "**********\n#\n");
3911:
3912:
3913: fprintf(fichtmcov, "\n<hr size=\"2\" color=\"#EC5E5E\">********** Variable ");
3914: for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3915: fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
3916:
3917: fprintf(ficresprobcor, "\n#********** Variable ");
3918: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
3919: fprintf(ficresprobcor, "**********\n#");
3920: }
3921:
3922: gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
3923: trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
3924: gp=vector(1,(nlstate)*(nlstate+ndeath));
3925: gm=vector(1,(nlstate)*(nlstate+ndeath));
3926: for (age=bage; age<=fage; age ++){
3927: cov[2]=age;
3928: for (k=1; k<=cptcovn;k++) {
3929: cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
3930: * 1 1 1 1 1
3931: * 2 2 1 1 1
3932: * 3 1 2 1 1
3933: */
3934: /* nbcode[1][1]=0 nbcode[1][2]=1;*/
3935: }
3936: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
3937: for (k=1; k<=cptcovprod;k++)
3938: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
3939:
3940:
3941: for(theta=1; theta <=npar; theta++){
3942: for(i=1; i<=npar; i++)
3943: xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
3944:
3945: pmij(pmmij,cov,ncovmodel,xp,nlstate);
3946:
3947: k=0;
3948: for(i=1; i<= (nlstate); i++){
3949: for(j=1; j<=(nlstate+ndeath);j++){
3950: k=k+1;
3951: gp[k]=pmmij[i][j];
3952: }
3953: }
3954:
3955: for(i=1; i<=npar; i++)
3956: xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
3957:
3958: pmij(pmmij,cov,ncovmodel,xp,nlstate);
3959: k=0;
3960: for(i=1; i<=(nlstate); i++){
3961: for(j=1; j<=(nlstate+ndeath);j++){
3962: k=k+1;
3963: gm[k]=pmmij[i][j];
3964: }
3965: }
3966:
3967: for(i=1; i<= (nlstate)*(nlstate+ndeath); i++)
3968: gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];
3969: }
3970:
3971: for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
3972: for(theta=1; theta <=npar; theta++)
3973: trgradg[j][theta]=gradg[theta][j];
3974:
3975: matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov);
3976: matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
3977:
3978: pmij(pmmij,cov,ncovmodel,x,nlstate);
3979:
3980: k=0;
3981: for(i=1; i<=(nlstate); i++){
3982: for(j=1; j<=(nlstate+ndeath);j++){
3983: k=k+1;
3984: mu[k][(int) age]=pmmij[i][j];
3985: }
3986: }
3987: for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
3988: for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
3989: varpij[i][j][(int)age] = doldm[i][j];
3990:
3991: /*printf("\n%d ",(int)age);
3992: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
3993: printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
3994: fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
3995: }*/
3996:
3997: fprintf(ficresprob,"\n%d ",(int)age);
3998: fprintf(ficresprobcov,"\n%d ",(int)age);
3999: fprintf(ficresprobcor,"\n%d ",(int)age);
4000:
4001: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
4002: fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
4003: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
4004: fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
4005: fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
4006: }
4007: i=0;
4008: for (k=1; k<=(nlstate);k++){
4009: for (l=1; l<=(nlstate+ndeath);l++){
4010: i++;
4011: fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
4012: fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
4013: for (j=1; j<=i;j++){
4014: /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
4015: fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
4016: fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
4017: }
4018: }
4019: }/* end of loop for state */
4020: } /* end of loop for age */
4021: free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
4022: free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
4023: free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4024: free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
4025:
4026: /* Confidence intervalle of pij */
4027: /*
4028: fprintf(ficgp,"\nunset parametric;unset label");
4029: fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
4030: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
4031: 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);
4032: fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
4033: fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
4034: fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
4035: */
4036:
4037: /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
4038: first1=1;first2=2;
4039: for (k2=1; k2<=(nlstate);k2++){
4040: for (l2=1; l2<=(nlstate+ndeath);l2++){
4041: if(l2==k2) continue;
4042: j=(k2-1)*(nlstate+ndeath)+l2;
4043: for (k1=1; k1<=(nlstate);k1++){
4044: for (l1=1; l1<=(nlstate+ndeath);l1++){
4045: if(l1==k1) continue;
4046: i=(k1-1)*(nlstate+ndeath)+l1;
4047: if(i<=j) continue;
4048: for (age=bage; age<=fage; age ++){
4049: if ((int)age %5==0){
4050: v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
4051: v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
4052: cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
4053: mu1=mu[i][(int) age]/stepm*YEARM ;
4054: mu2=mu[j][(int) age]/stepm*YEARM;
4055: c12=cv12/sqrt(v1*v2);
4056: /* Computing eigen value of matrix of covariance */
4057: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
4058: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
4059: if ((lc2 <0) || (lc1 <0) ){
4060: if(first2==1){
4061: first1=0;
4062: 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);
4063: }
4064: 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);
4065: /* lc1=fabs(lc1); */ /* If we want to have them positive */
4066: /* lc2=fabs(lc2); */
4067: }
4068:
4069: /* Eigen vectors */
4070: v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
4071: /*v21=sqrt(1.-v11*v11); *//* error */
4072: v21=(lc1-v1)/cv12*v11;
4073: v12=-v21;
4074: v22=v11;
4075: tnalp=v21/v11;
4076: if(first1==1){
4077: first1=0;
4078: 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);
4079: }
4080: 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);
4081: /*printf(fignu*/
4082: /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
4083: /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
4084: if(first==1){
4085: first=0;
4086: fprintf(ficgp,"\nset parametric;unset label");
4087: 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);
4088: fprintf(ficgp,"\nset ter png small size 320, 240");
4089: fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
4090: :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
4091: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
4092: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
4093: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4094: fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4095: fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
4096: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4097: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4098: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4099: 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",\
4100: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4101: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4102: }else{
4103: first=0;
4104: fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
4105: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
4106: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
4107: 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",\
4108: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
4109: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
4110: }/* if first */
4111: } /* age mod 5 */
4112: } /* end loop age */
4113: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
4114: first=1;
4115: } /*l12 */
4116: } /* k12 */
4117: } /*l1 */
4118: }/* k1 */
4119: /* } */ /* loop covariates */
4120: }
4121: free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
4122: free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
4123: free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
4124: free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
4125: free_vector(xp,1,npar);
4126: fclose(ficresprob);
4127: fclose(ficresprobcov);
4128: fclose(ficresprobcor);
4129: fflush(ficgp);
4130: fflush(fichtmcov);
4131: }
4132:
4133:
4134: /******************* Printing html file ***********/
4135: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
4136: int lastpass, int stepm, int weightopt, char model[],\
4137: int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
4138: int popforecast, int estepm ,\
4139: double jprev1, double mprev1,double anprev1, \
4140: double jprev2, double mprev2,double anprev2){
4141: int jj1, k1, i1, cpt;
4142:
4143: fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
4144: <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
4145: </ul>");
4146: fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
4147: - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
4148: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
4149: fprintf(fichtm,"\
4150: - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
4151: stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
4152: fprintf(fichtm,"\
4153: - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
4154: subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
4155: fprintf(fichtm,"\
4156: - (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): \
4157: <a href=\"%s\">%s</a> <br>\n",
4158: estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
4159: fprintf(fichtm,"\
4160: - Population projections by age and states: \
4161: <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
4162:
4163: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
4164:
4165: m=pow(2,cptcoveff);
4166: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4167:
4168: jj1=0;
4169: for(k1=1; k1<=m;k1++){
4170: for(i1=1; i1<=ncodemax[k1];i1++){
4171: jj1++;
4172: if (cptcovn > 0) {
4173: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4174: for (cpt=1; cpt<=cptcoveff;cpt++)
4175: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4176: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4177: }
4178: /* Pij */
4179: 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> \
4180: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
4181: /* Quasi-incidences */
4182: fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
4183: 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> \
4184: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);
4185: /* Period (stable) prevalence in each health state */
4186: for(cpt=1; cpt<=nlstate;cpt++){
4187: 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> \
4188: <img src=\"%s%d_%d.png\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
4189: }
4190: for(cpt=1; cpt<=nlstate;cpt++) {
4191: 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> \
4192: <img src=\"%s%d%d.png\">",cpt,nlstate,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
4193: }
4194: } /* end i1 */
4195: }/* End k1 */
4196: fprintf(fichtm,"</ul>");
4197:
4198:
4199: fprintf(fichtm,"\
4200: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
4201: - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
4202:
4203: fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4204: subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
4205: fprintf(fichtm,"\
4206: - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4207: subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
4208:
4209: fprintf(fichtm,"\
4210: - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
4211: subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
4212: fprintf(fichtm,"\
4213: - 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): \
4214: <a href=\"%s\">%s</a> <br>\n</li>",
4215: estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
4216: fprintf(fichtm,"\
4217: - (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): \
4218: <a href=\"%s\">%s</a> <br>\n</li>",
4219: estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
4220: fprintf(fichtm,"\
4221: - 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",
4222: estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
4223: fprintf(fichtm,"\
4224: - 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",
4225: estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
4226: fprintf(fichtm,"\
4227: - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
4228: subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
4229:
4230: /* if(popforecast==1) fprintf(fichtm,"\n */
4231: /* - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
4232: /* - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
4233: /* <br>",fileres,fileres,fileres,fileres); */
4234: /* else */
4235: /* 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); */
4236: fflush(fichtm);
4237: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
4238:
4239: m=pow(2,cptcoveff);
4240: if (cptcovn < 1) {m=1;ncodemax[1]=1;}
4241:
4242: jj1=0;
4243: for(k1=1; k1<=m;k1++){
4244: for(i1=1; i1<=ncodemax[k1];i1++){
4245: jj1++;
4246: if (cptcovn > 0) {
4247: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
4248: for (cpt=1; cpt<=cptcoveff;cpt++)
4249: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
4250: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
4251: }
4252: for(cpt=1; cpt<=nlstate;cpt++) {
4253: fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
4254: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
4255: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);
4256: }
4257: fprintf(fichtm,"\n<br>- Total life expectancy by age and \
4258: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
4259: true period expectancies (those weighted with period prevalences are also\
4260: drawn in addition to the population based expectancies computed using\
4261: observed and cahotic prevalences: %s%d.png<br>\
4262: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
4263: } /* end i1 */
4264: }/* End k1 */
4265: fprintf(fichtm,"</ul>");
4266: fflush(fichtm);
4267: }
4268:
4269: /******************* Gnuplot file **************/
4270: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
4271:
4272: char dirfileres[132],optfileres[132];
4273: int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
4274: int ng=0;
4275: /* if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
4276: /* printf("Problem with file %s",optionfilegnuplot); */
4277: /* fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
4278: /* } */
4279:
4280: /*#ifdef windows */
4281: fprintf(ficgp,"cd \"%s\" \n",pathc);
4282: /*#endif */
4283: m=pow(2,cptcoveff);
4284:
4285: strcpy(dirfileres,optionfilefiname);
4286: strcpy(optfileres,"vpl");
4287: /* 1eme*/
4288: fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
4289: for (cpt=1; cpt<= nlstate ; cpt ++) {
4290: for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
4291: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
4292: fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
4293: fprintf(ficgp,"set xlabel \"Age\" \n\
4294: set ylabel \"Probability\" \n\
4295: set ter png small size 320, 240\n\
4296: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
4297:
4298: for (i=1; i<= nlstate ; i ++) {
4299: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4300: else fprintf(ficgp," %%*lf (%%*lf)");
4301: }
4302: fprintf(ficgp,"\" t\"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);
4303: for (i=1; i<= nlstate ; i ++) {
4304: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4305: else fprintf(ficgp," %%*lf (%%*lf)");
4306: }
4307: 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);
4308: for (i=1; i<= nlstate ; i ++) {
4309: if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
4310: else fprintf(ficgp," %%*lf (%%*lf)");
4311: }
4312: 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));
4313: }
4314: }
4315: /*2 eme*/
4316: fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
4317: for (k1=1; k1<= m ; k1 ++) {
4318: fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
4319: fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
4320:
4321: for (i=1; i<= nlstate+1 ; i ++) {
4322: k=2*i;
4323: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4324: for (j=1; j<= nlstate+1 ; j ++) {
4325: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4326: else fprintf(ficgp," %%*lf (%%*lf)");
4327: }
4328: if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
4329: else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
4330: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4331: for (j=1; j<= nlstate+1 ; j ++) {
4332: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4333: else fprintf(ficgp," %%*lf (%%*lf)");
4334: }
4335: fprintf(ficgp,"\" t\"\" w l lt 0,");
4336: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
4337: for (j=1; j<= nlstate+1 ; j ++) {
4338: if (j==i) fprintf(ficgp," %%lf (%%lf)");
4339: else fprintf(ficgp," %%*lf (%%*lf)");
4340: }
4341: if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
4342: else fprintf(ficgp,"\" t\"\" w l lt 0,");
4343: }
4344: }
4345:
4346: /*3eme*/
4347:
4348: for (k1=1; k1<= m ; k1 ++) {
4349: for (cpt=1; cpt<= nlstate ; cpt ++) {
4350: /* k=2+nlstate*(2*cpt-2); */
4351: k=2+(nlstate+1)*(cpt-1);
4352: fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
4353: fprintf(ficgp,"set ter png small size 320, 240\n\
4354: 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);
4355: /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4356: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4357: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4358: fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
4359: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
4360: fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
4361:
4362: */
4363: for (i=1; i< nlstate ; i ++) {
4364: 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);
4365: /* 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);*/
4366:
4367: }
4368: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
4369: }
4370: }
4371:
4372: /* CV preval stable (period) */
4373: for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
4374: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
4375: k=3;
4376: fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
4377: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
4378: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
4379: set ter png small size 320, 240\n\
4380: unset log y\n\
4381: plot [%.f:%.f] ", ageminpar, agemaxpar);
4382: for (i=1; i<= nlstate ; i ++){
4383: if(i==1)
4384: fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
4385: else
4386: fprintf(ficgp,", '' ");
4387: l=(nlstate+ndeath)*(i-1)+1;
4388: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
4389: for (j=1; j<= (nlstate-1) ; j ++)
4390: fprintf(ficgp,"+$%d",k+l+j);
4391: fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
4392: } /* nlstate */
4393: fprintf(ficgp,"\n");
4394: } /* end cpt state*/
4395: } /* end covariate */
4396:
4397: /* proba elementaires */
4398: for(i=1,jk=1; i <=nlstate; i++){
4399: for(k=1; k <=(nlstate+ndeath); k++){
4400: if (k != i) {
4401: for(j=1; j <=ncovmodel; j++){
4402: fprintf(ficgp,"p%d=%f ",jk,p[jk]);
4403: jk++;
4404: fprintf(ficgp,"\n");
4405: }
4406: }
4407: }
4408: }
4409: /*goto avoid;*/
4410: for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
4411: for(jk=1; jk <=m; jk++) {
4412: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng);
4413: if (ng==2)
4414: fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
4415: else
4416: fprintf(ficgp,"\nset title \"Probability\"\n");
4417: fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot [%.f:%.f] ",ageminpar,agemaxpar);
4418: i=1;
4419: for(k2=1; k2<=nlstate; k2++) {
4420: k3=i;
4421: for(k=1; k<=(nlstate+ndeath); k++) {
4422: if (k != k2){
4423: if(ng==2)
4424: fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
4425: else
4426: fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
4427: ij=1;/* To be checked else nbcode[0][0] wrong */
4428: for(j=3; j <=ncovmodel; j++) {
4429: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /\* Bug valgrind *\/ */
4430: /* /\*fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);*\/ */
4431: /* ij++; */
4432: /* } */
4433: /* else */
4434: fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4435: }
4436: fprintf(ficgp,")/(1");
4437:
4438: for(k1=1; k1 <=nlstate; k1++){
4439: fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
4440: ij=1;
4441: for(j=3; j <=ncovmodel; j++){
4442: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { */
4443: /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]); */
4444: /* ij++; */
4445: /* } */
4446: /* else */
4447: fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
4448: }
4449: fprintf(ficgp,")");
4450: }
4451: fprintf(ficgp,") t \"p%d%d\" ", k2,k);
4452: if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
4453: i=i+ncovmodel;
4454: }
4455: } /* end k */
4456: } /* end k2 */
4457: } /* end jk */
4458: } /* end ng */
4459: /* avoid: */
4460: fflush(ficgp);
4461: } /* end gnuplot */
4462:
4463:
4464: /*************** Moving average **************/
4465: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
4466:
4467: int i, cpt, cptcod;
4468: int modcovmax =1;
4469: int mobilavrange, mob;
4470: double age;
4471:
4472: modcovmax=2*cptcoveff;/* Max number of modalities. We suppose
4473: a covariate has 2 modalities */
4474: if (cptcovn<1) modcovmax=1; /* At least 1 pass */
4475:
4476: if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
4477: if(mobilav==1) mobilavrange=5; /* default */
4478: else mobilavrange=mobilav;
4479: for (age=bage; age<=fage; age++)
4480: for (i=1; i<=nlstate;i++)
4481: for (cptcod=1;cptcod<=modcovmax;cptcod++)
4482: mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
4483: /* We keep the original values on the extreme ages bage, fage and for
4484: fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
4485: we use a 5 terms etc. until the borders are no more concerned.
4486: */
4487: for (mob=3;mob <=mobilavrange;mob=mob+2){
4488: for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
4489: for (i=1; i<=nlstate;i++){
4490: for (cptcod=1;cptcod<=modcovmax;cptcod++){
4491: mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
4492: for (cpt=1;cpt<=(mob-1)/2;cpt++){
4493: mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
4494: mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
4495: }
4496: mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
4497: }
4498: }
4499: }/* end age */
4500: }/* end mob */
4501: }else return -1;
4502: return 0;
4503: }/* End movingaverage */
4504:
4505:
4506: /************** Forecasting ******************/
4507: 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){
4508: /* proj1, year, month, day of starting projection
4509: agemin, agemax range of age
4510: dateprev1 dateprev2 range of dates during which prevalence is computed
4511: anproj2 year of en of projection (same day and month as proj1).
4512: */
4513: int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
4514: double agec; /* generic age */
4515: double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
4516: double *popeffectif,*popcount;
4517: double ***p3mat;
4518: double ***mobaverage;
4519: char fileresf[FILENAMELENGTH];
4520:
4521: agelim=AGESUP;
4522: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4523:
4524: strcpy(fileresf,"f");
4525: strcat(fileresf,fileres);
4526: if((ficresf=fopen(fileresf,"w"))==NULL) {
4527: printf("Problem with forecast resultfile: %s\n", fileresf);
4528: fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
4529: }
4530: printf("Computing forecasting: result on file '%s' \n", fileresf);
4531: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
4532:
4533: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4534:
4535: if (mobilav!=0) {
4536: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4537: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4538: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4539: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4540: }
4541: }
4542:
4543: stepsize=(int) (stepm+YEARM-1)/YEARM;
4544: if (stepm<=12) stepsize=1;
4545: if(estepm < stepm){
4546: printf ("Problem %d lower than %d\n",estepm, stepm);
4547: }
4548: else hstepm=estepm;
4549:
4550: hstepm=hstepm/stepm;
4551: yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp and
4552: fractional in yp1 */
4553: anprojmean=yp;
4554: yp2=modf((yp1*12),&yp);
4555: mprojmean=yp;
4556: yp1=modf((yp2*30.5),&yp);
4557: jprojmean=yp;
4558: if(jprojmean==0) jprojmean=1;
4559: if(mprojmean==0) jprojmean=1;
4560:
4561: i1=cptcoveff;
4562: if (cptcovn < 1){i1=1;}
4563:
4564: fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);
4565:
4566: fprintf(ficresf,"#****** Routine prevforecast **\n");
4567:
4568: /* if (h==(int)(YEARM*yearp)){ */
4569: for(cptcov=1, k=0;cptcov<=i1;cptcov++){
4570: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4571: k=k+1;
4572: fprintf(ficresf,"\n#******");
4573: for(j=1;j<=cptcoveff;j++) {
4574: 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]]);
4575: }
4576: fprintf(ficresf,"******\n");
4577: fprintf(ficresf,"# Covariate valuofcovar yearproj age");
4578: for(j=1; j<=nlstate+ndeath;j++){
4579: for(i=1; i<=nlstate;i++)
4580: fprintf(ficresf," p%d%d",i,j);
4581: fprintf(ficresf," p.%d",j);
4582: }
4583: for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
4584: fprintf(ficresf,"\n");
4585: fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);
4586:
4587: for (agec=fage; agec>=(ageminpar-1); agec--){
4588: nhstepm=(int) rint((agelim-agec)*YEARM/stepm);
4589: nhstepm = nhstepm/hstepm;
4590: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4591: oldm=oldms;savm=savms;
4592: hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
4593:
4594: for (h=0; h<=nhstepm; h++){
4595: if (h*hstepm/YEARM*stepm ==yearp) {
4596: fprintf(ficresf,"\n");
4597: for(j=1;j<=cptcoveff;j++)
4598: fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4599: fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
4600: }
4601: for(j=1; j<=nlstate+ndeath;j++) {
4602: ppij=0.;
4603: for(i=1; i<=nlstate;i++) {
4604: if (mobilav==1)
4605: ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
4606: else {
4607: ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
4608: }
4609: if (h*hstepm/YEARM*stepm== yearp) {
4610: fprintf(ficresf," %.3f", p3mat[i][j][h]);
4611: }
4612: } /* end i */
4613: if (h*hstepm/YEARM*stepm==yearp) {
4614: fprintf(ficresf," %.3f", ppij);
4615: }
4616: }/* end j */
4617: } /* end h */
4618: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4619: } /* end agec */
4620: } /* end yearp */
4621: } /* end cptcod */
4622: } /* end cptcov */
4623:
4624: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4625:
4626: fclose(ficresf);
4627: }
4628:
4629: /************** Forecasting *****not tested NB*************/
4630: 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){
4631:
4632: int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
4633: int *popage;
4634: double calagedatem, agelim, kk1, kk2;
4635: double *popeffectif,*popcount;
4636: double ***p3mat,***tabpop,***tabpopprev;
4637: double ***mobaverage;
4638: char filerespop[FILENAMELENGTH];
4639:
4640: tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4641: tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4642: agelim=AGESUP;
4643: calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
4644:
4645: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
4646:
4647:
4648: strcpy(filerespop,"pop");
4649: strcat(filerespop,fileres);
4650: if((ficrespop=fopen(filerespop,"w"))==NULL) {
4651: printf("Problem with forecast resultfile: %s\n", filerespop);
4652: fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
4653: }
4654: printf("Computing forecasting: result on file '%s' \n", filerespop);
4655: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
4656:
4657: if (cptcoveff==0) ncodemax[cptcoveff]=1;
4658:
4659: if (mobilav!=0) {
4660: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4661: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
4662: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
4663: printf(" Error in movingaverage mobilav=%d\n",mobilav);
4664: }
4665: }
4666:
4667: stepsize=(int) (stepm+YEARM-1)/YEARM;
4668: if (stepm<=12) stepsize=1;
4669:
4670: agelim=AGESUP;
4671:
4672: hstepm=1;
4673: hstepm=hstepm/stepm;
4674:
4675: if (popforecast==1) {
4676: if((ficpop=fopen(popfile,"r"))==NULL) {
4677: printf("Problem with population file : %s\n",popfile);exit(0);
4678: fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
4679: }
4680: popage=ivector(0,AGESUP);
4681: popeffectif=vector(0,AGESUP);
4682: popcount=vector(0,AGESUP);
4683:
4684: i=1;
4685: while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
4686:
4687: imx=i;
4688: for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
4689: }
4690:
4691: for(cptcov=1,k=0;cptcov<=i2;cptcov++){
4692: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
4693: k=k+1;
4694: fprintf(ficrespop,"\n#******");
4695: for(j=1;j<=cptcoveff;j++) {
4696: fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
4697: }
4698: fprintf(ficrespop,"******\n");
4699: fprintf(ficrespop,"# Age");
4700: for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
4701: if (popforecast==1) fprintf(ficrespop," [Population]");
4702:
4703: for (cpt=0; cpt<=0;cpt++) {
4704: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4705:
4706: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4707: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4708: nhstepm = nhstepm/hstepm;
4709:
4710: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4711: oldm=oldms;savm=savms;
4712: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4713:
4714: for (h=0; h<=nhstepm; h++){
4715: if (h==(int) (calagedatem+YEARM*cpt)) {
4716: fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4717: }
4718: for(j=1; j<=nlstate+ndeath;j++) {
4719: kk1=0.;kk2=0;
4720: for(i=1; i<=nlstate;i++) {
4721: if (mobilav==1)
4722: kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
4723: else {
4724: kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
4725: }
4726: }
4727: if (h==(int)(calagedatem+12*cpt)){
4728: tabpop[(int)(agedeb)][j][cptcod]=kk1;
4729: /*fprintf(ficrespop," %.3f", kk1);
4730: if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
4731: }
4732: }
4733: for(i=1; i<=nlstate;i++){
4734: kk1=0.;
4735: for(j=1; j<=nlstate;j++){
4736: kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];
4737: }
4738: tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
4739: }
4740:
4741: if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++)
4742: fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
4743: }
4744: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4745: }
4746: }
4747:
4748: /******/
4749:
4750: for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {
4751: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);
4752: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){
4753: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);
4754: nhstepm = nhstepm/hstepm;
4755:
4756: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4757: oldm=oldms;savm=savms;
4758: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
4759: for (h=0; h<=nhstepm; h++){
4760: if (h==(int) (calagedatem+YEARM*cpt)) {
4761: fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
4762: }
4763: for(j=1; j<=nlstate+ndeath;j++) {
4764: kk1=0.;kk2=0;
4765: for(i=1; i<=nlstate;i++) {
4766: kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];
4767: }
4768: if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);
4769: }
4770: }
4771: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
4772: }
4773: }
4774: }
4775: }
4776:
4777: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4778:
4779: if (popforecast==1) {
4780: free_ivector(popage,0,AGESUP);
4781: free_vector(popeffectif,0,AGESUP);
4782: free_vector(popcount,0,AGESUP);
4783: }
4784: free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4785: free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
4786: fclose(ficrespop);
4787: } /* End of popforecast */
4788:
4789: int fileappend(FILE *fichier, char *optionfich)
4790: {
4791: if((fichier=fopen(optionfich,"a"))==NULL) {
4792: printf("Problem with file: %s\n", optionfich);
4793: fprintf(ficlog,"Problem with file: %s\n", optionfich);
4794: return (0);
4795: }
4796: fflush(fichier);
4797: return (1);
4798: }
4799:
4800:
4801: /**************** function prwizard **********************/
4802: void prwizard(int ncovmodel, int nlstate, int ndeath, char model[], FILE *ficparo)
4803: {
4804:
4805: /* Wizard to print covariance matrix template */
4806:
4807: char ca[32], cb[32];
4808: int i,j, k, li, lj, lk, ll, jj, npar, itimes;
4809: int numlinepar;
4810:
4811: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4812: fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
4813: for(i=1; i <=nlstate; i++){
4814: jj=0;
4815: for(j=1; j <=nlstate+ndeath; j++){
4816: if(j==i) continue;
4817: jj++;
4818: /*ca[0]= k+'a'-1;ca[1]='\0';*/
4819: printf("%1d%1d",i,j);
4820: fprintf(ficparo,"%1d%1d",i,j);
4821: for(k=1; k<=ncovmodel;k++){
4822: /* printf(" %lf",param[i][j][k]); */
4823: /* fprintf(ficparo," %lf",param[i][j][k]); */
4824: printf(" 0.");
4825: fprintf(ficparo," 0.");
4826: }
4827: printf("\n");
4828: fprintf(ficparo,"\n");
4829: }
4830: }
4831: printf("# Scales (for hessian or gradient estimation)\n");
4832: fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
4833: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/
4834: for(i=1; i <=nlstate; i++){
4835: jj=0;
4836: for(j=1; j <=nlstate+ndeath; j++){
4837: if(j==i) continue;
4838: jj++;
4839: fprintf(ficparo,"%1d%1d",i,j);
4840: printf("%1d%1d",i,j);
4841: fflush(stdout);
4842: for(k=1; k<=ncovmodel;k++){
4843: /* printf(" %le",delti3[i][j][k]); */
4844: /* fprintf(ficparo," %le",delti3[i][j][k]); */
4845: printf(" 0.");
4846: fprintf(ficparo," 0.");
4847: }
4848: numlinepar++;
4849: printf("\n");
4850: fprintf(ficparo,"\n");
4851: }
4852: }
4853: printf("# Covariance matrix\n");
4854: /* # 121 Var(a12)\n\ */
4855: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4856: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
4857: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
4858: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
4859: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
4860: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
4861: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4862: fflush(stdout);
4863: fprintf(ficparo,"# Covariance matrix\n");
4864: /* # 121 Var(a12)\n\ */
4865: /* # 122 Cov(b12,a12) Var(b12)\n\ */
4866: /* # ...\n\ */
4867: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
4868:
4869: for(itimes=1;itimes<=2;itimes++){
4870: jj=0;
4871: for(i=1; i <=nlstate; i++){
4872: for(j=1; j <=nlstate+ndeath; j++){
4873: if(j==i) continue;
4874: for(k=1; k<=ncovmodel;k++){
4875: jj++;
4876: ca[0]= k+'a'-1;ca[1]='\0';
4877: if(itimes==1){
4878: printf("#%1d%1d%d",i,j,k);
4879: fprintf(ficparo,"#%1d%1d%d",i,j,k);
4880: }else{
4881: printf("%1d%1d%d",i,j,k);
4882: fprintf(ficparo,"%1d%1d%d",i,j,k);
4883: /* printf(" %.5le",matcov[i][j]); */
4884: }
4885: ll=0;
4886: for(li=1;li <=nlstate; li++){
4887: for(lj=1;lj <=nlstate+ndeath; lj++){
4888: if(lj==li) continue;
4889: for(lk=1;lk<=ncovmodel;lk++){
4890: ll++;
4891: if(ll<=jj){
4892: cb[0]= lk +'a'-1;cb[1]='\0';
4893: if(ll<jj){
4894: if(itimes==1){
4895: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4896: fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
4897: }else{
4898: printf(" 0.");
4899: fprintf(ficparo," 0.");
4900: }
4901: }else{
4902: if(itimes==1){
4903: printf(" Var(%s%1d%1d)",ca,i,j);
4904: fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
4905: }else{
4906: printf(" 0.");
4907: fprintf(ficparo," 0.");
4908: }
4909: }
4910: }
4911: } /* end lk */
4912: } /* end lj */
4913: } /* end li */
4914: printf("\n");
4915: fprintf(ficparo,"\n");
4916: numlinepar++;
4917: } /* end k*/
4918: } /*end j */
4919: } /* end i */
4920: } /* end itimes */
4921:
4922: } /* end of prwizard */
4923: /******************* Gompertz Likelihood ******************************/
4924: double gompertz(double x[])
4925: {
4926: double A,B,L=0.0,sump=0.,num=0.;
4927: int i,n=0; /* n is the size of the sample */
4928:
4929: for (i=0;i<=imx-1 ; i++) {
4930: sump=sump+weight[i];
4931: /* sump=sump+1;*/
4932: num=num+1;
4933: }
4934:
4935:
4936: /* for (i=0; i<=imx; i++)
4937: 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]);*/
4938:
4939: for (i=1;i<=imx ; i++)
4940: {
4941: if (cens[i] == 1 && wav[i]>1)
4942: A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
4943:
4944: if (cens[i] == 0 && wav[i]>1)
4945: A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
4946: +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);
4947:
4948: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
4949: if (wav[i] > 1 ) { /* ??? */
4950: L=L+A*weight[i];
4951: /* 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]);*/
4952: }
4953: }
4954:
4955: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
4956:
4957: return -2*L*num/sump;
4958: }
4959:
4960: #ifdef GSL
4961: /******************* Gompertz_f Likelihood ******************************/
4962: double gompertz_f(const gsl_vector *v, void *params)
4963: {
4964: double A,B,LL=0.0,sump=0.,num=0.;
4965: double *x= (double *) v->data;
4966: int i,n=0; /* n is the size of the sample */
4967:
4968: for (i=0;i<=imx-1 ; i++) {
4969: sump=sump+weight[i];
4970: /* sump=sump+1;*/
4971: num=num+1;
4972: }
4973:
4974:
4975: /* for (i=0; i<=imx; i++)
4976: 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]);*/
4977: printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
4978: for (i=1;i<=imx ; i++)
4979: {
4980: if (cens[i] == 1 && wav[i]>1)
4981: A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
4982:
4983: if (cens[i] == 0 && wav[i]>1)
4984: A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
4985: +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);
4986:
4987: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
4988: if (wav[i] > 1 ) { /* ??? */
4989: LL=LL+A*weight[i];
4990: /* 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]);*/
4991: }
4992: }
4993:
4994: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
4995: printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
4996:
4997: return -2*LL*num/sump;
4998: }
4999: #endif
5000:
5001: /******************* Printing html file ***********/
5002: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
5003: int lastpass, int stepm, int weightopt, char model[],\
5004: int imx, double p[],double **matcov,double agemortsup){
5005: int i,k;
5006:
5007: fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
5008: fprintf(fichtm," mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
5009: for (i=1;i<=2;i++)
5010: 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]));
5011: fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
5012: fprintf(fichtm,"</ul>");
5013:
5014: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
5015:
5016: 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>");
5017:
5018: for (k=agegomp;k<(agemortsup-2);k++)
5019: 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]);
5020:
5021:
5022: fflush(fichtm);
5023: }
5024:
5025: /******************* Gnuplot file **************/
5026: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
5027:
5028: char dirfileres[132],optfileres[132];
5029:
5030: int ng;
5031:
5032:
5033: /*#ifdef windows */
5034: fprintf(ficgp,"cd \"%s\" \n",pathc);
5035: /*#endif */
5036:
5037:
5038: strcpy(dirfileres,optionfilefiname);
5039: strcpy(optfileres,"vpl");
5040: fprintf(ficgp,"set out \"graphmort.png\"\n ");
5041: fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n ");
5042: fprintf(ficgp, "set ter png small size 320, 240\n set log y\n");
5043: /* fprintf(ficgp, "set size 0.65,0.65\n"); */
5044: fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
5045:
5046: }
5047:
5048: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
5049: {
5050:
5051: /*-------- data file ----------*/
5052: FILE *fic;
5053: char dummy[]=" ";
5054: int i=0, j=0, n=0;
5055: int linei, month, year,iout;
5056: char line[MAXLINE], linetmp[MAXLINE];
5057: char stra[MAXLINE], strb[MAXLINE];
5058: char *stratrunc;
5059: int lstra;
5060:
5061:
5062: if((fic=fopen(datafile,"r"))==NULL) {
5063: printf("Problem while opening datafile: %s\n", datafile);return 1;
5064: fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
5065: }
5066:
5067: i=1;
5068: linei=0;
5069: while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
5070: linei=linei+1;
5071: for(j=strlen(line); j>=0;j--){ /* Untabifies line */
5072: if(line[j] == '\t')
5073: line[j] = ' ';
5074: }
5075: for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
5076: ;
5077: };
5078: line[j+1]=0; /* Trims blanks at end of line */
5079: if(line[0]=='#'){
5080: fprintf(ficlog,"Comment line\n%s\n",line);
5081: printf("Comment line\n%s\n",line);
5082: continue;
5083: }
5084: trimbb(linetmp,line); /* Trims multiple blanks in line */
5085: strcpy(line, linetmp);
5086:
5087:
5088: for (j=maxwav;j>=1;j--){
5089: cutv(stra, strb, line, ' ');
5090: if(strb[0]=='.') { /* Missing status */
5091: lval=-1;
5092: }else{
5093: errno=0;
5094: lval=strtol(strb,&endptr,10);
5095: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
5096: if( strb[0]=='\0' || (*endptr != '\0')){
5097: 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);
5098: 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);
5099: return 1;
5100: }
5101: }
5102: s[j][i]=lval;
5103:
5104: strcpy(line,stra);
5105: cutv(stra, strb,line,' ');
5106: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
5107: }
5108: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
5109: month=99;
5110: year=9999;
5111: }else{
5112: 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);
5113: 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);
5114: return 1;
5115: }
5116: anint[j][i]= (double) year;
5117: mint[j][i]= (double)month;
5118: strcpy(line,stra);
5119: } /* ENd Waves */
5120:
5121: cutv(stra, strb,line,' ');
5122: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
5123: }
5124: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){
5125: month=99;
5126: year=9999;
5127: }else{
5128: 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);
5129: 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);
5130: return 1;
5131: }
5132: andc[i]=(double) year;
5133: moisdc[i]=(double) month;
5134: strcpy(line,stra);
5135:
5136: cutv(stra, strb,line,' ');
5137: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
5138: }
5139: else if( (iout=sscanf(strb,"%s.", dummy)) != 0){
5140: month=99;
5141: year=9999;
5142: }else{
5143: 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);
5144: 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);
5145: return 1;
5146: }
5147: if (year==9999) {
5148: 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);
5149: 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);
5150: return 1;
5151:
5152: }
5153: annais[i]=(double)(year);
5154: moisnais[i]=(double)(month);
5155: strcpy(line,stra);
5156:
5157: cutv(stra, strb,line,' ');
5158: errno=0;
5159: dval=strtod(strb,&endptr);
5160: if( strb[0]=='\0' || (*endptr != '\0')){
5161: printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight. Exiting.\n",dval, i,line,linei);
5162: 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);
5163: fflush(ficlog);
5164: return 1;
5165: }
5166: weight[i]=dval;
5167: strcpy(line,stra);
5168:
5169: for (j=ncovcol;j>=1;j--){
5170: cutv(stra, strb,line,' ');
5171: if(strb[0]=='.') { /* Missing status */
5172: lval=-1;
5173: }else{
5174: errno=0;
5175: lval=strtol(strb,&endptr,10);
5176: if( strb[0]=='\0' || (*endptr != '\0')){
5177: 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);
5178: 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);
5179: return 1;
5180: }
5181: }
5182: if(lval <-1 || lval >1){
5183: printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
5184: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5185: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5186: For example, for multinomial values like 1, 2 and 3,\n \
5187: build V1=0 V2=0 for the reference value (1),\n \
5188: V1=1 V2=0 for (2) \n \
5189: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5190: output of IMaCh is often meaningless.\n \
5191: Exiting.\n",lval,linei, i,line,j);
5192: fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
5193: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
5194: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
5195: For example, for multinomial values like 1, 2 and 3,\n \
5196: build V1=0 V2=0 for the reference value (1),\n \
5197: V1=1 V2=0 for (2) \n \
5198: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
5199: output of IMaCh is often meaningless.\n \
5200: Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
5201: return 1;
5202: }
5203: covar[j][i]=(double)(lval);
5204: strcpy(line,stra);
5205: }
5206: lstra=strlen(stra);
5207:
5208: if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
5209: stratrunc = &(stra[lstra-9]);
5210: num[i]=atol(stratrunc);
5211: }
5212: else
5213: num[i]=atol(stra);
5214: /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
5215: 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;}*/
5216:
5217: i=i+1;
5218: } /* End loop reading data */
5219:
5220: *imax=i-1; /* Number of individuals */
5221: fclose(fic);
5222:
5223: return (0);
5224: /* endread: */
5225: printf("Exiting readdata: ");
5226: fclose(fic);
5227: return (1);
5228:
5229:
5230:
5231: }
5232: void removespace(char *str) {
5233: char *p1 = str, *p2 = str;
5234: do
5235: while (*p2 == ' ')
5236: p2++;
5237: while (*p1++ == *p2++);
5238: }
5239:
5240: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
5241: * Model V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age
5242: * - cptcovt total number of covariates of the model nbocc(+)+1 = 8
5243: * - cptcovn or number of covariates k of the models excluding age*products =6
5244: * - cptcovage number of covariates with age*products =2
5245: * - cptcovs number of simple covariates
5246: * - 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
5247: * which is a new column after the 9 (ncovcol) variables.
5248: * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
5249: * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
5250: * Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
5251: * - Tvard[k] p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
5252: */
5253: {
5254: int i, j, k, ks;
5255: int j1, k1, k2;
5256: char modelsav[80];
5257: char stra[80], strb[80], strc[80], strd[80],stre[80];
5258:
5259: /*removespace(model);*/
5260: if (strlen(model) >1){ /* If there is at least 1 covariate */
5261: j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
5262: j=nbocc(model,'+'); /**< j=Number of '+' */
5263: j1=nbocc(model,'*'); /**< j1=Number of '*' */
5264: cptcovs=j+1-j1; /**< Number of simple covariates V1+V2*age+V3 +V3*V4=> V1 + V3 =2 */
5265: cptcovt= j+1; /* Number of total covariates in the model V1 + V2*age+ V3 + V3*V4=> 4*/
5266: /* including age products which are counted in cptcovage.
5267: * but the covariates which are products must be treated separately: ncovn=4- 2=2 (V1+V3). */
5268: cptcovprod=j1; /**< Number of products V1*V2 +v3*age = 2 */
5269: cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1 */
5270: strcpy(modelsav,model);
5271: if (strstr(model,"AGE") !=0){
5272: printf("Error. AGE must be in lower case 'age' model=%s ",model);
5273: fprintf(ficlog,"Error. AGE must be in lower case model=%s ",model);fflush(ficlog);
5274: return 1;
5275: }
5276: if (strstr(model,"v") !=0){
5277: printf("Error. 'v' must be in upper case 'V' model=%s ",model);
5278: fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
5279: return 1;
5280: }
5281:
5282: /* Design
5283: * V1 V2 V3 V4 V5 V6 V7 V8 V9 Weight
5284: * < ncovcol=8 >
5285: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
5286: * k= 1 2 3 4 5 6 7 8
5287: * cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
5288: * covar[k,i], value of kth covariate if not including age for individual i:
5289: * covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
5290: * Tvar[k] # of the kth covariate: Tvar[1]=2 Tvar[4]=3 Tvar[8]=8
5291: * if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and
5292: * Tage[++cptcovage]=k
5293: * if products, new covar are created after ncovcol with k1
5294: * Tvar[k]=ncovcol+k1; # of the kth covariate product: Tvar[5]=ncovcol+1=10 Tvar[6]=ncovcol+1=11
5295: * Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
5296: * 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
5297: * Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
5298: * Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
5299: * V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11
5300: * < ncovcol=8 >
5301: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 d1 d1 d2 d2
5302: * k= 1 2 3 4 5 6 7 8 9 10 11 12
5303: * Tvar[k]= 2 1 3 3 10 11 8 8 5 6 7 8
5304: * p Tvar[1]@12={2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5305: * p Tprod[1]@2={ 6, 5}
5306: *p Tvard[1][1]@4= {7, 8, 5, 6}
5307: * covar[k][i]= V2 V1 ? V3 V5*V6? V7*V8? ? V8
5308: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
5309: *How to reorganize?
5310: * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
5311: * Tvars {2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6}
5312: * {2, 1, 4, 8, 5, 6, 3, 7}
5313: * Struct []
5314: */
5315:
5316: /* This loop fills the array Tvar from the string 'model'.*/
5317: /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
5318: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 */
5319: /* k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
5320: /* k=3 V4 Tvar[k=3]= 4 (from V4) */
5321: /* k=2 V1 Tvar[k=2]= 1 (from V1) */
5322: /* k=1 Tvar[1]=2 (from V2) */
5323: /* k=5 Tvar[5] */
5324: /* for (k=1; k<=cptcovn;k++) { */
5325: /* cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
5326: /* } */
5327: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
5328: /*
5329: * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
5330: for(k=cptcovt; k>=1;k--) /**< Number of covariates */
5331: Tvar[k]=0;
5332: cptcovage=0;
5333: for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
5334: cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+'
5335: modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */
5336: if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
5337: /* printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
5338: /*scanf("%d",i);*/
5339: if (strchr(strb,'*')) { /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
5340: cutl(strc,strd,strb,'*'); /**< strd*strc Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
5341: if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
5342: /* covar is not filled and then is empty */
5343: cptcovprod--;
5344: cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
5345: Tvar[k]=atoi(stre); /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2 */
5346: cptcovage++; /* Sums the number of covariates which include age as a product */
5347: Tage[cptcovage]=k; /* Tage[1] = 4 */
5348: /*printf("stre=%s ", stre);*/
5349: } else if (strcmp(strd,"age")==0) { /* or age*Vn */
5350: cptcovprod--;
5351: cutl(stre,strb,strc,'V');
5352: Tvar[k]=atoi(stre);
5353: cptcovage++;
5354: Tage[cptcovage]=k;
5355: } else { /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2 strb=V3*V2*/
5356: /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
5357: cptcovn++;
5358: cptcovprodnoage++;k1++;
5359: cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
5360: Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
5361: because this model-covariate is a construction we invent a new column
5362: ncovcol + k1
5363: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
5364: Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
5365: cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
5366: Tprod[k1]=k; /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 */
5367: Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
5368: Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
5369: k2=k2+2;
5370: Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
5371: Tvar[cptcovt+k2+1]=Tvard[k1][2]; /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
5372: for (i=1; i<=lastobs;i++){
5373: /* Computes the new covariate which is a product of
5374: covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
5375: covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
5376: }
5377: } /* End age is not in the model */
5378: } /* End if model includes a product */
5379: else { /* no more sum */
5380: /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
5381: /* scanf("%d",i);*/
5382: cutl(strd,strc,strb,'V');
5383: ks++; /**< Number of simple covariates */
5384: cptcovn++;
5385: Tvar[k]=atoi(strd);
5386: }
5387: strcpy(modelsav,stra); /* modelsav=V2+V1+V4 stra=V2+V1+V4 */
5388: /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
5389: scanf("%d",i);*/
5390: } /* end of loop + */
5391: } /* end model */
5392:
5393: /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
5394: If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
5395:
5396: /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
5397: printf("cptcovprod=%d ", cptcovprod);
5398: fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
5399:
5400: scanf("%d ",i);*/
5401:
5402:
5403: return (0); /* with covar[new additional covariate if product] and Tage if age */
5404: /*endread:*/
5405: printf("Exiting decodemodel: ");
5406: return (1);
5407: }
5408:
5409: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
5410: {
5411: int i, m;
5412:
5413: for (i=1; i<=imx; i++) {
5414: for(m=2; (m<= maxwav); m++) {
5415: if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
5416: anint[m][i]=9999;
5417: s[m][i]=-1;
5418: }
5419: if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
5420: *nberr = *nberr + 1;
5421: 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);
5422: 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);
5423: s[m][i]=-1;
5424: }
5425: if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
5426: (*nberr)++;
5427: 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]);
5428: 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]);
5429: s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
5430: }
5431: }
5432: }
5433:
5434: for (i=1; i<=imx; i++) {
5435: agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
5436: for(m=firstpass; (m<= lastpass); m++){
5437: if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
5438: if (s[m][i] >= nlstate+1) {
5439: if(agedc[i]>0){
5440: if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
5441: agev[m][i]=agedc[i];
5442: /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
5443: }else {
5444: if ((int)andc[i]!=9999){
5445: nbwarn++;
5446: printf("Warning negative age at death: %ld line:%d\n",num[i],i);
5447: fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
5448: agev[m][i]=-1;
5449: }
5450: }
5451: } /* agedc > 0 */
5452: }
5453: else if(s[m][i] !=9){ /* Standard case, age in fractional
5454: years but with the precision of a month */
5455: agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
5456: if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
5457: agev[m][i]=1;
5458: else if(agev[m][i] < *agemin){
5459: *agemin=agev[m][i];
5460: printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
5461: }
5462: else if(agev[m][i] >*agemax){
5463: *agemax=agev[m][i];
5464: /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
5465: }
5466: /*agev[m][i]=anint[m][i]-annais[i];*/
5467: /* agev[m][i] = age[i]+2*m;*/
5468: }
5469: else { /* =9 */
5470: agev[m][i]=1;
5471: s[m][i]=-1;
5472: }
5473: }
5474: else /*= 0 Unknown */
5475: agev[m][i]=1;
5476: }
5477:
5478: }
5479: for (i=1; i<=imx; i++) {
5480: for(m=firstpass; (m<=lastpass); m++){
5481: if (s[m][i] > (nlstate+ndeath)) {
5482: (*nberr)++;
5483: 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);
5484: 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);
5485: return 1;
5486: }
5487: }
5488: }
5489:
5490: /*for (i=1; i<=imx; i++){
5491: for (m=firstpass; (m<lastpass); m++){
5492: printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
5493: }
5494:
5495: }*/
5496:
5497:
5498: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
5499: fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
5500:
5501: return (0);
5502: /* endread:*/
5503: printf("Exiting calandcheckages: ");
5504: return (1);
5505: }
5506:
5507: #if defined(_MSC_VER)
5508: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
5509: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
5510: //#include "stdafx.h"
5511: //#include <stdio.h>
5512: //#include <tchar.h>
5513: //#include <windows.h>
5514: //#include <iostream>
5515: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
5516:
5517: LPFN_ISWOW64PROCESS fnIsWow64Process;
5518:
5519: BOOL IsWow64()
5520: {
5521: BOOL bIsWow64 = FALSE;
5522:
5523: //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
5524: // (HANDLE, PBOOL);
5525:
5526: //LPFN_ISWOW64PROCESS fnIsWow64Process;
5527:
5528: HMODULE module = GetModuleHandle(_T("kernel32"));
5529: const char funcName[] = "IsWow64Process";
5530: fnIsWow64Process = (LPFN_ISWOW64PROCESS)
5531: GetProcAddress(module, funcName);
5532:
5533: if (NULL != fnIsWow64Process)
5534: {
5535: if (!fnIsWow64Process(GetCurrentProcess(),
5536: &bIsWow64))
5537: //throw std::exception("Unknown error");
5538: printf("Unknown error\n");
5539: }
5540: return bIsWow64 != FALSE;
5541: }
5542: #endif
5543:
5544: void syscompilerinfo()
5545: {
5546: /* #include "syscompilerinfo.h"*/
5547:
5548: #if defined __INTEL_COMPILER
5549: #if defined(__GNUC__)
5550: struct utsname sysInfo; /* For Intel on Linux and OS/X */
5551: #endif
5552: #elif defined(__GNUC__)
5553: #ifndef __APPLE__
5554: #include <gnu/libc-version.h> /* Only on gnu */
5555: #endif
5556: struct utsname sysInfo;
5557: int cross = CROSS;
5558: if (cross){
5559: printf("Cross-");
5560: fprintf(ficlog, "Cross-");
5561: }
5562: #endif
5563:
5564: #include <stdint.h>
5565:
5566: printf("Compiled with:");fprintf(ficlog,"Compiled with:");
5567: #if defined(__clang__)
5568: printf(" Clang/LLVM");fprintf(ficlog," Clang/LLVM"); /* Clang/LLVM. ---------------------------------------------- */
5569: #endif
5570: #if defined(__ICC) || defined(__INTEL_COMPILER)
5571: printf(" Intel ICC/ICPC");fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
5572: #endif
5573: #if defined(__GNUC__) || defined(__GNUG__)
5574: printf(" GNU GCC/G++");fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
5575: #endif
5576: #if defined(__HP_cc) || defined(__HP_aCC)
5577: printf(" Hewlett-Packard C/aC++");fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
5578: #endif
5579: #if defined(__IBMC__) || defined(__IBMCPP__)
5580: printf(" IBM XL C/C++"); fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
5581: #endif
5582: #if defined(_MSC_VER)
5583: printf(" Microsoft Visual Studio");fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
5584: #endif
5585: #if defined(__PGI)
5586: printf(" Portland Group PGCC/PGCPP");fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
5587: #endif
5588: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
5589: printf(" Oracle Solaris Studio");fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
5590: #endif
5591: printf(" for ");fprintf(ficlog," for ");
5592:
5593: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
5594: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
5595: // Windows (x64 and x86)
5596: printf("Windows (x64 and x86) ");fprintf(ficlog,"Windows (x64 and x86) ");
5597: #elif __unix__ // all unices, not all compilers
5598: // Unix
5599: printf("Unix ");fprintf(ficlog,"Unix ");
5600: #elif __linux__
5601: // linux
5602: printf("linux ");fprintf(ficlog,"linux ");
5603: #elif __APPLE__
5604: // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
5605: printf("Mac OS ");fprintf(ficlog,"Mac OS ");
5606: #endif
5607:
5608: /* __MINGW32__ */
5609: /* __CYGWIN__ */
5610: /* __MINGW64__ */
5611: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
5612: /* _MSC_VER //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /? */
5613: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
5614: /* _WIN64 // Defined for applications for Win64. */
5615: /* _M_X64 // Defined for compilations that target x64 processors. */
5616: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
5617:
5618: #if UINTPTR_MAX == 0xffffffff
5619: printf(" 32-bit"); fprintf(ficlog," 32-bit");/* 32-bit */
5620: #elif UINTPTR_MAX == 0xffffffffffffffff
5621: printf(" 64-bit"); fprintf(ficlog," 64-bit");/* 64-bit */
5622: #else
5623: printf(" wtf-bit"); fprintf(ficlog," wtf-bit");/* wtf */
5624: #endif
5625:
5626: #if defined(__GNUC__)
5627: # if defined(__GNUC_PATCHLEVEL__)
5628: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
5629: + __GNUC_MINOR__ * 100 \
5630: + __GNUC_PATCHLEVEL__)
5631: # else
5632: # define __GNUC_VERSION__ (__GNUC__ * 10000 \
5633: + __GNUC_MINOR__ * 100)
5634: # endif
5635: printf(" using GNU C version %d.\n", __GNUC_VERSION__);
5636: fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
5637:
5638: if (uname(&sysInfo) != -1) {
5639: printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
5640: fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
5641: }
5642: else
5643: perror("uname() error");
5644: //#ifndef __INTEL_COMPILER
5645: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
5646: printf("GNU libc version: %s\n", gnu_get_libc_version());
5647: fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
5648: #endif
5649: #endif
5650:
5651: // void main()
5652: // {
5653: #if defined(_MSC_VER)
5654: if (IsWow64()){
5655: printf("The program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
5656: fprintf(ficlog, "The program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
5657: }
5658: else{
5659: printf("The process is not running under WOW64 (i.e probably on a 64bit Windows).\n");
5660: fprintf(ficlog,"The programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
5661: }
5662: // printf("\nPress Enter to continue...");
5663: // getchar();
5664: // }
5665:
5666: #endif
5667:
5668:
5669: }
5670:
5671: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar){
5672: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
5673: int i, j, k, i1 ;
5674: double ftolpl = 1.e-10;
5675: double age, agebase, agelim;
5676:
5677: strcpy(filerespl,"pl");
5678: strcat(filerespl,fileres);
5679: if((ficrespl=fopen(filerespl,"w"))==NULL) {
5680: printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
5681: fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
5682: }
5683: printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
5684: fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
5685: pstamp(ficrespl);
5686: fprintf(ficrespl,"# Period (stable) prevalence \n");
5687: fprintf(ficrespl,"#Age ");
5688: for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
5689: fprintf(ficrespl,"\n");
5690:
5691: /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
5692:
5693: agebase=ageminpar;
5694: agelim=agemaxpar;
5695:
5696: i1=pow(2,cptcoveff);
5697: if (cptcovn < 1){i1=1;}
5698:
5699: for(cptcov=1,k=0;cptcov<=i1;cptcov++){
5700: /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
5701: //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
5702: k=k+1;
5703: /* to clean */
5704: //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtab[cptcod][cptcov]);
5705: fprintf(ficrespl,"\n#******");
5706: printf("\n#******");
5707: fprintf(ficlog,"\n#******");
5708: for(j=1;j<=cptcoveff;j++) {
5709: fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5710: printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5711: fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5712: }
5713: fprintf(ficrespl,"******\n");
5714: printf("******\n");
5715: fprintf(ficlog,"******\n");
5716:
5717: fprintf(ficrespl,"#Age ");
5718: for(j=1;j<=cptcoveff;j++) {
5719: fprintf(ficrespl,"V%d %d",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5720: }
5721: for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
5722: fprintf(ficrespl,"\n");
5723:
5724: for (age=agebase; age<=agelim; age++){
5725: /* for (age=agebase; age<=agebase; age++){ */
5726: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
5727: fprintf(ficrespl,"%.0f ",age );
5728: for(j=1;j<=cptcoveff;j++)
5729: fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5730: for(i=1; i<=nlstate;i++)
5731: fprintf(ficrespl," %.5f", prlim[i][i]);
5732: fprintf(ficrespl,"\n");
5733: } /* Age */
5734: /* was end of cptcod */
5735: } /* cptcov */
5736: }
5737:
5738: int hPijx(double *p, int bage, int fage){
5739: /*------------- h Pij x at various ages ------------*/
5740:
5741: int stepsize;
5742: int agelim;
5743: int hstepm;
5744: int nhstepm;
5745: int h, i, i1, j, k;
5746:
5747: double agedeb;
5748: double ***p3mat;
5749:
5750: strcpy(filerespij,"pij"); strcat(filerespij,fileres);
5751: if((ficrespij=fopen(filerespij,"w"))==NULL) {
5752: printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
5753: fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
5754: }
5755: printf("Computing pij: result on file '%s' \n", filerespij);
5756: fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
5757:
5758: stepsize=(int) (stepm+YEARM-1)/YEARM;
5759: /*if (stepm<=24) stepsize=2;*/
5760:
5761: agelim=AGESUP;
5762: hstepm=stepsize*YEARM; /* Every year of age */
5763: hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
5764:
5765: /* hstepm=1; aff par mois*/
5766: pstamp(ficrespij);
5767: fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
5768: i1= pow(2,cptcoveff);
5769: for(cptcov=1,k=0;cptcov<=i1;cptcov++){
5770: /*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
5771: k=k+1;
5772: /* for (k=1; k <= (int) pow(2,cptcoveff); k++){*/
5773: fprintf(ficrespij,"\n#****** ");
5774: for(j=1;j<=cptcoveff;j++)
5775: fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
5776: fprintf(ficrespij,"******\n");
5777:
5778: for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
5779: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
5780: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
5781:
5782: /* nhstepm=nhstepm*YEARM; aff par mois*/
5783:
5784: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5785: oldm=oldms;savm=savms;
5786: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
5787: fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
5788: for(i=1; i<=nlstate;i++)
5789: for(j=1; j<=nlstate+ndeath;j++)
5790: fprintf(ficrespij," %1d-%1d",i,j);
5791: fprintf(ficrespij,"\n");
5792: for (h=0; h<=nhstepm; h++){
5793: /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
5794: fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
5795: for(i=1; i<=nlstate;i++)
5796: for(j=1; j<=nlstate+ndeath;j++)
5797: fprintf(ficrespij," %.5f", p3mat[i][j][h]);
5798: fprintf(ficrespij,"\n");
5799: }
5800: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
5801: fprintf(ficrespij,"\n");
5802: }
5803: /*}*/
5804: }
5805: }
5806:
5807:
5808: /***********************************************/
5809: /**************** Main Program *****************/
5810: /***********************************************/
5811:
5812: int main(int argc, char *argv[])
5813: {
5814: #ifdef GSL
5815: const gsl_multimin_fminimizer_type *T;
5816: size_t iteri = 0, it;
5817: int rval = GSL_CONTINUE;
5818: int status = GSL_SUCCESS;
5819: double ssval;
5820: #endif
5821: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
5822: int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
5823:
5824: int jj, ll, li, lj, lk;
5825: int numlinepar=0; /* Current linenumber of parameter file */
5826: int itimes;
5827: int NDIM=2;
5828: int vpopbased=0;
5829:
5830: char ca[32], cb[32];
5831: /* FILE *fichtm; *//* Html File */
5832: /* FILE *ficgp;*/ /*Gnuplot File */
5833: struct stat info;
5834: double agedeb;
5835: double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
5836:
5837: double fret;
5838: double dum; /* Dummy variable */
5839: double ***p3mat;
5840: double ***mobaverage;
5841:
5842: char line[MAXLINE];
5843: char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
5844: char pathr[MAXLINE], pathimach[MAXLINE];
5845: char *tok, *val; /* pathtot */
5846: int firstobs=1, lastobs=10;
5847: int c, h , cpt;
5848: int jl;
5849: int i1, j1, jk, stepsize;
5850: int *tab;
5851: int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
5852: int mobilav=0,popforecast=0;
5853: int hstepm, nhstepm;
5854: int agemortsup;
5855: float sumlpop=0.;
5856: double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
5857: double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
5858:
5859: double bage=0, fage=110, age, agelim, agebase;
5860: double ftolpl=FTOL;
5861: double **prlim;
5862: double ***param; /* Matrix of parameters */
5863: double *p;
5864: double **matcov; /* Matrix of covariance */
5865: double ***delti3; /* Scale */
5866: double *delti; /* Scale */
5867: double ***eij, ***vareij;
5868: double **varpl; /* Variances of prevalence limits by age */
5869: double *epj, vepp;
5870:
5871: double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
5872: double **ximort;
5873: char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
5874: int *dcwave;
5875:
5876: char z[1]="c";
5877:
5878: /*char *strt;*/
5879: char strtend[80];
5880:
5881:
5882: /* setlocale (LC_ALL, ""); */
5883: /* bindtextdomain (PACKAGE, LOCALEDIR); */
5884: /* textdomain (PACKAGE); */
5885: /* setlocale (LC_CTYPE, ""); */
5886: /* setlocale (LC_MESSAGES, ""); */
5887:
5888: /* gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
5889: rstart_time = time(NULL);
5890: /* (void) gettimeofday(&start_time,&tzp);*/
5891: start_time = *localtime(&rstart_time);
5892: curr_time=start_time;
5893: /*tml = *localtime(&start_time.tm_sec);*/
5894: /* strcpy(strstart,asctime(&tml)); */
5895: strcpy(strstart,asctime(&start_time));
5896:
5897: /* printf("Localtime (at start)=%s",strstart); */
5898: /* tp.tm_sec = tp.tm_sec +86400; */
5899: /* tm = *localtime(&start_time.tm_sec); */
5900: /* tmg.tm_year=tmg.tm_year +dsign*dyear; */
5901: /* tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
5902: /* tmg.tm_hour=tmg.tm_hour + 1; */
5903: /* tp.tm_sec = mktime(&tmg); */
5904: /* strt=asctime(&tmg); */
5905: /* printf("Time(after) =%s",strstart); */
5906: /* (void) time (&time_value);
5907: * printf("time=%d,t-=%d\n",time_value,time_value-86400);
5908: * tm = *localtime(&time_value);
5909: * strstart=asctime(&tm);
5910: * printf("tim_value=%d,asctime=%s\n",time_value,strstart);
5911: */
5912:
5913: nberr=0; /* Number of errors and warnings */
5914: nbwarn=0;
5915: getcwd(pathcd, size);
5916:
5917: printf("\n%s\n%s",version,fullversion);
5918: if(argc <=1){
5919: printf("\nEnter the parameter file name: ");
5920: fgets(pathr,FILENAMELENGTH,stdin);
5921: i=strlen(pathr);
5922: if(pathr[i-1]=='\n')
5923: pathr[i-1]='\0';
5924: i=strlen(pathr);
5925: if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
5926: pathr[i-1]='\0';
5927: for (tok = pathr; tok != NULL; ){
5928: printf("Pathr |%s|\n",pathr);
5929: while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
5930: printf("val= |%s| pathr=%s\n",val,pathr);
5931: strcpy (pathtot, val);
5932: if(pathr[0] == '\0') break; /* Dirty */
5933: }
5934: }
5935: else{
5936: strcpy(pathtot,argv[1]);
5937: }
5938: /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
5939: /*cygwin_split_path(pathtot,path,optionfile);
5940: printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
5941: /* cutv(path,optionfile,pathtot,'\\');*/
5942:
5943: /* Split argv[0], imach program to get pathimach */
5944: printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
5945: split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
5946: printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
5947: /* strcpy(pathimach,argv[0]); */
5948: /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
5949: split(pathtot,path,optionfile,optionfilext,optionfilefiname);
5950: printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
5951: chdir(path); /* Can be a relative path */
5952: if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
5953: printf("Current directory %s!\n",pathcd);
5954: strcpy(command,"mkdir ");
5955: strcat(command,optionfilefiname);
5956: if((outcmd=system(command)) != 0){
5957: printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
5958: /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
5959: /* fclose(ficlog); */
5960: /* exit(1); */
5961: }
5962: /* if((imk=mkdir(optionfilefiname))<0){ */
5963: /* perror("mkdir"); */
5964: /* } */
5965:
5966: /*-------- arguments in the command line --------*/
5967:
5968: /* Log file */
5969: strcat(filelog, optionfilefiname);
5970: strcat(filelog,".log"); /* */
5971: if((ficlog=fopen(filelog,"w"))==NULL) {
5972: printf("Problem with logfile %s\n",filelog);
5973: goto end;
5974: }
5975: fprintf(ficlog,"Log filename:%s\n",filelog);
5976: fprintf(ficlog,"\n%s\n%s",version,fullversion);
5977: fprintf(ficlog,"\nEnter the parameter file name: \n");
5978: fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
5979: path=%s \n\
5980: optionfile=%s\n\
5981: optionfilext=%s\n\
5982: optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
5983:
5984: syscompilerinfo();
5985:
5986: printf("Local time (at start):%s",strstart);
5987: fprintf(ficlog,"Local time (at start): %s",strstart);
5988: fflush(ficlog);
5989: /* (void) gettimeofday(&curr_time,&tzp); */
5990: /* printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
5991:
5992: /* */
5993: strcpy(fileres,"r");
5994: strcat(fileres, optionfilefiname);
5995: strcat(fileres,".txt"); /* Other files have txt extension */
5996:
5997: /*---------arguments file --------*/
5998:
5999: if((ficpar=fopen(optionfile,"r"))==NULL) {
6000: printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
6001: fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
6002: fflush(ficlog);
6003: /* goto end; */
6004: exit(70);
6005: }
6006:
6007:
6008:
6009: strcpy(filereso,"o");
6010: strcat(filereso,fileres);
6011: if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
6012: printf("Problem with Output resultfile: %s\n", filereso);
6013: fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
6014: fflush(ficlog);
6015: goto end;
6016: }
6017:
6018: /* Reads comments: lines beginning with '#' */
6019: numlinepar=0;
6020: while((c=getc(ficpar))=='#' && c!= EOF){
6021: ungetc(c,ficpar);
6022: fgets(line, MAXLINE, ficpar);
6023: numlinepar++;
6024: fputs(line,stdout);
6025: fputs(line,ficparo);
6026: fputs(line,ficlog);
6027: }
6028: ungetc(c,ficpar);
6029:
6030: 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);
6031: numlinepar++;
6032: 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);
6033: 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);
6034: 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);
6035: fflush(ficlog);
6036: while((c=getc(ficpar))=='#' && c!= EOF){
6037: ungetc(c,ficpar);
6038: fgets(line, MAXLINE, ficpar);
6039: numlinepar++;
6040: fputs(line, stdout);
6041: //puts(line);
6042: fputs(line,ficparo);
6043: fputs(line,ficlog);
6044: }
6045: ungetc(c,ficpar);
6046:
6047:
6048: covar=matrix(0,NCOVMAX,1,n); /**< used in readdata */
6049: cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
6050: /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
6051: v1+v2*age+v2*v3 makes cptcovn = 3
6052: */
6053: if (strlen(model)>1)
6054: 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*/
6055: else
6056: ncovmodel=2;
6057: nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
6058: nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
6059: npar= nforce*ncovmodel; /* Number of parameters like aij*/
6060: if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
6061: 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);
6062: 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);
6063: fflush(stdout);
6064: fclose (ficlog);
6065: goto end;
6066: }
6067: delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6068: delti=delti3[1][1];
6069: /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
6070: if(mle==-1){ /* Print a wizard for help writing covariance matrix */
6071: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
6072: printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
6073: fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
6074: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
6075: fclose (ficparo);
6076: fclose (ficlog);
6077: goto end;
6078: exit(0);
6079: }
6080: else if(mle==-3) {
6081: prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
6082: printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
6083: fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
6084: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6085: matcov=matrix(1,npar,1,npar);
6086: }
6087: else{
6088: /* Read guessed parameters */
6089: /* Reads comments: lines beginning with '#' */
6090: while((c=getc(ficpar))=='#' && c!= EOF){
6091: ungetc(c,ficpar);
6092: fgets(line, MAXLINE, ficpar);
6093: numlinepar++;
6094: fputs(line,stdout);
6095: fputs(line,ficparo);
6096: fputs(line,ficlog);
6097: }
6098: ungetc(c,ficpar);
6099:
6100: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
6101: for(i=1; i <=nlstate; i++){
6102: j=0;
6103: for(jj=1; jj <=nlstate+ndeath; jj++){
6104: if(jj==i) continue;
6105: j++;
6106: fscanf(ficpar,"%1d%1d",&i1,&j1);
6107: if ((i1 != i) && (j1 != j)){
6108: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
6109: It might be a problem of design; if ncovcol and the model are correct\n \
6110: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
6111: exit(1);
6112: }
6113: fprintf(ficparo,"%1d%1d",i1,j1);
6114: if(mle==1)
6115: printf("%1d%1d",i,j);
6116: fprintf(ficlog,"%1d%1d",i,j);
6117: for(k=1; k<=ncovmodel;k++){
6118: fscanf(ficpar," %lf",¶m[i][j][k]);
6119: if(mle==1){
6120: printf(" %lf",param[i][j][k]);
6121: fprintf(ficlog," %lf",param[i][j][k]);
6122: }
6123: else
6124: fprintf(ficlog," %lf",param[i][j][k]);
6125: fprintf(ficparo," %lf",param[i][j][k]);
6126: }
6127: fscanf(ficpar,"\n");
6128: numlinepar++;
6129: if(mle==1)
6130: printf("\n");
6131: fprintf(ficlog,"\n");
6132: fprintf(ficparo,"\n");
6133: }
6134: }
6135: fflush(ficlog);
6136:
6137: /* Reads scales values */
6138: p=param[1][1];
6139:
6140: /* Reads comments: lines beginning with '#' */
6141: while((c=getc(ficpar))=='#' && c!= EOF){
6142: ungetc(c,ficpar);
6143: fgets(line, MAXLINE, ficpar);
6144: numlinepar++;
6145: fputs(line,stdout);
6146: fputs(line,ficparo);
6147: fputs(line,ficlog);
6148: }
6149: ungetc(c,ficpar);
6150:
6151: for(i=1; i <=nlstate; i++){
6152: for(j=1; j <=nlstate+ndeath-1; j++){
6153: fscanf(ficpar,"%1d%1d",&i1,&j1);
6154: if ( (i1-i) * (j1-j) != 0){
6155: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
6156: exit(1);
6157: }
6158: printf("%1d%1d",i,j);
6159: fprintf(ficparo,"%1d%1d",i1,j1);
6160: fprintf(ficlog,"%1d%1d",i1,j1);
6161: for(k=1; k<=ncovmodel;k++){
6162: fscanf(ficpar,"%le",&delti3[i][j][k]);
6163: printf(" %le",delti3[i][j][k]);
6164: fprintf(ficparo," %le",delti3[i][j][k]);
6165: fprintf(ficlog," %le",delti3[i][j][k]);
6166: }
6167: fscanf(ficpar,"\n");
6168: numlinepar++;
6169: printf("\n");
6170: fprintf(ficparo,"\n");
6171: fprintf(ficlog,"\n");
6172: }
6173: }
6174: fflush(ficlog);
6175:
6176: /* Reads covariance matrix */
6177: delti=delti3[1][1];
6178:
6179:
6180: /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
6181:
6182: /* Reads comments: lines beginning with '#' */
6183: while((c=getc(ficpar))=='#' && c!= EOF){
6184: ungetc(c,ficpar);
6185: fgets(line, MAXLINE, ficpar);
6186: numlinepar++;
6187: fputs(line,stdout);
6188: fputs(line,ficparo);
6189: fputs(line,ficlog);
6190: }
6191: ungetc(c,ficpar);
6192:
6193: matcov=matrix(1,npar,1,npar);
6194: for(i=1; i <=npar; i++)
6195: for(j=1; j <=npar; j++) matcov[i][j]=0.;
6196:
6197: for(i=1; i <=npar; i++){
6198: fscanf(ficpar,"%s",str);
6199: if(mle==1)
6200: printf("%s",str);
6201: fprintf(ficlog,"%s",str);
6202: fprintf(ficparo,"%s",str);
6203: for(j=1; j <=i; j++){
6204: fscanf(ficpar," %le",&matcov[i][j]);
6205: if(mle==1){
6206: printf(" %.5le",matcov[i][j]);
6207: }
6208: fprintf(ficlog," %.5le",matcov[i][j]);
6209: fprintf(ficparo," %.5le",matcov[i][j]);
6210: }
6211: fscanf(ficpar,"\n");
6212: numlinepar++;
6213: if(mle==1)
6214: printf("\n");
6215: fprintf(ficlog,"\n");
6216: fprintf(ficparo,"\n");
6217: }
6218: for(i=1; i <=npar; i++)
6219: for(j=i+1;j<=npar;j++)
6220: matcov[i][j]=matcov[j][i];
6221:
6222: if(mle==1)
6223: printf("\n");
6224: fprintf(ficlog,"\n");
6225:
6226: fflush(ficlog);
6227:
6228: /*-------- Rewriting parameter file ----------*/
6229: strcpy(rfileres,"r"); /* "Rparameterfile */
6230: strcat(rfileres,optionfilefiname); /* Parameter file first name*/
6231: strcat(rfileres,"."); /* */
6232: strcat(rfileres,optionfilext); /* Other files have txt extension */
6233: if((ficres =fopen(rfileres,"w"))==NULL) {
6234: printf("Problem writing new parameter file: %s\n", fileres);goto end;
6235: fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
6236: }
6237: fprintf(ficres,"#%s\n",version);
6238: } /* End of mle != -3 */
6239:
6240:
6241: n= lastobs;
6242: num=lvector(1,n);
6243: moisnais=vector(1,n);
6244: annais=vector(1,n);
6245: moisdc=vector(1,n);
6246: andc=vector(1,n);
6247: agedc=vector(1,n);
6248: cod=ivector(1,n);
6249: weight=vector(1,n);
6250: for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
6251: mint=matrix(1,maxwav,1,n);
6252: anint=matrix(1,maxwav,1,n);
6253: s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */
6254: tab=ivector(1,NCOVMAX);
6255: ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
6256:
6257: /* Reads data from file datafile */
6258: if (readdata(datafile, firstobs, lastobs, &imx)==1)
6259: goto end;
6260:
6261: /* Calculation of the number of parameters from char model */
6262: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4
6263: k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
6264: k=3 V4 Tvar[k=3]= 4 (from V4)
6265: k=2 V1 Tvar[k=2]= 1 (from V1)
6266: k=1 Tvar[1]=2 (from V2)
6267: */
6268: Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
6269: /* V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs).
6270: For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4,
6271: Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
6272: */
6273: /* For model-covariate k tells which data-covariate to use but
6274: because this model-covariate is a construction we invent a new column
6275: ncovcol + k1
6276: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
6277: Tvar[3=V1*V4]=4+1 etc */
6278: Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
6279: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
6280: if V2+V1+V1*V4+age*V3+V3*V2 TProd[k1=2]=5 (V3*V2)
6281: */
6282: Tvaraff=ivector(1,NCOVMAX); /* Unclear */
6283: 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
6284: * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd.
6285: * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
6286: Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
6287: 4 covariates (3 plus signs)
6288: Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
6289: */
6290:
6291: if(decodemodel(model, lastobs) == 1)
6292: goto end;
6293:
6294: if((double)(lastobs-imx)/(double)imx > 1.10){
6295: nbwarn++;
6296: 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);
6297: 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);
6298: }
6299: /* if(mle==1){*/
6300: if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
6301: for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
6302: }
6303:
6304: /*-calculation of age at interview from date of interview and age at death -*/
6305: agev=matrix(1,maxwav,1,imx);
6306:
6307: if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
6308: goto end;
6309:
6310:
6311: agegomp=(int)agemin;
6312: free_vector(moisnais,1,n);
6313: free_vector(annais,1,n);
6314: /* free_matrix(mint,1,maxwav,1,n);
6315: free_matrix(anint,1,maxwav,1,n);*/
6316: free_vector(moisdc,1,n);
6317: free_vector(andc,1,n);
6318: /* */
6319:
6320: wav=ivector(1,imx);
6321: dh=imatrix(1,lastpass-firstpass+1,1,imx);
6322: bh=imatrix(1,lastpass-firstpass+1,1,imx);
6323: mw=imatrix(1,lastpass-firstpass+1,1,imx);
6324:
6325: /* Concatenates waves */
6326: concatwav(wav, dh, bh, mw, s, agedc, agev, firstpass, lastpass, imx, nlstate, stepm);
6327: /* */
6328:
6329: /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
6330:
6331: nbcode=imatrix(0,NCOVMAX,0,NCOVMAX);
6332: ncodemax[1]=1;
6333: Ndum =ivector(-1,NCOVMAX);
6334: if (ncovmodel > 2)
6335: tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
6336:
6337: codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
6338: /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
6339: h=0;
6340:
6341:
6342: /*if (cptcovn > 0) */
6343:
6344:
6345: m=pow(2,cptcoveff);
6346:
6347: for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
6348: 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 */
6349: for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
6350: for(cpt=1; cpt <=pow(2,k-1); cpt++){ /* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 */
6351: h++;
6352: if (h>m)
6353: h=1;
6354: /**< codtab(h,k) k = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
6355: * h 1 2 3 4
6356: *______________________________
6357: * 1 i=1 1 i=1 1 i=1 1 i=1 1
6358: * 2 2 1 1 1
6359: * 3 i=2 1 2 1 1
6360: * 4 2 2 1 1
6361: * 5 i=3 1 i=2 1 2 1
6362: * 6 2 1 2 1
6363: * 7 i=4 1 2 2 1
6364: * 8 2 2 2 1
6365: * 9 i=5 1 i=3 1 i=2 1 1
6366: * 10 2 1 1 1
6367: * 11 i=6 1 2 1 1
6368: * 12 2 2 1 1
6369: * 13 i=7 1 i=4 1 2 1
6370: * 14 2 1 2 1
6371: * 15 i=8 1 2 2 1
6372: * 16 2 2 2 1
6373: */
6374: codtab[h][k]=j;
6375: /*codtab[h][Tvar[k]]=j;*/
6376: 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]]);
6377: }
6378: }
6379: }
6380: }
6381: /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]);
6382: codtab[1][2]=1;codtab[2][2]=2; */
6383: /* for(i=1; i <=m ;i++){
6384: for(k=1; k <=cptcovn; k++){
6385: printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
6386: }
6387: printf("\n");
6388: }
6389: scanf("%d",i);*/
6390:
6391: free_ivector(Ndum,-1,NCOVMAX);
6392:
6393:
6394:
6395: /*------------ gnuplot -------------*/
6396: strcpy(optionfilegnuplot,optionfilefiname);
6397: if(mle==-3)
6398: strcat(optionfilegnuplot,"-mort");
6399: strcat(optionfilegnuplot,".gp");
6400:
6401: if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
6402: printf("Problem with file %s",optionfilegnuplot);
6403: }
6404: else{
6405: fprintf(ficgp,"\n# %s\n", version);
6406: fprintf(ficgp,"# %s\n", optionfilegnuplot);
6407: //fprintf(ficgp,"set missing 'NaNq'\n");
6408: fprintf(ficgp,"set datafile missing 'NaNq'\n");
6409: }
6410: /* fclose(ficgp);*/
6411: /*--------- index.htm --------*/
6412:
6413: strcpy(optionfilehtm,optionfilefiname); /* Main html file */
6414: if(mle==-3)
6415: strcat(optionfilehtm,"-mort");
6416: strcat(optionfilehtm,".htm");
6417: if((fichtm=fopen(optionfilehtm,"w"))==NULL) {
6418: printf("Problem with %s \n",optionfilehtm);
6419: exit(0);
6420: }
6421:
6422: strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
6423: strcat(optionfilehtmcov,"-cov.htm");
6424: if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL) {
6425: printf("Problem with %s \n",optionfilehtmcov), exit(0);
6426: }
6427: else{
6428: fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6429: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6430: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
6431: optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
6432: }
6433:
6434: fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
6435: <hr size=\"2\" color=\"#EC5E5E\"> \n\
6436: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
6437: \n\
6438: <hr size=\"2\" color=\"#EC5E5E\">\
6439: <ul><li><h4>Parameter files</h4>\n\
6440: - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
6441: - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
6442: - Log file of the run: <a href=\"%s\">%s</a><br>\n\
6443: - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
6444: - Date and time at start: %s</ul>\n",\
6445: optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
6446: optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
6447: fileres,fileres,\
6448: filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
6449: fflush(fichtm);
6450:
6451: strcpy(pathr,path);
6452: strcat(pathr,optionfilefiname);
6453: chdir(optionfilefiname); /* Move to directory named optionfile */
6454:
6455: /* Calculates basic frequencies. Computes observed prevalence at single age
6456: and prints on file fileres'p'. */
6457: freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
6458:
6459: fprintf(fichtm,"\n");
6460: fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
6461: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
6462: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
6463: imx,agemin,agemax,jmin,jmax,jmean);
6464: pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6465: oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6466: newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6467: savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
6468: oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
6469:
6470:
6471: /* For Powell, parameters are in a vector p[] starting at p[1]
6472: so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
6473: p=param[1][1]; /* *(*(*(param +1)+1)+0) */
6474:
6475: globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
6476:
6477: if (mle==-3){
6478: ximort=matrix(1,NDIM,1,NDIM);
6479: /* ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
6480: cens=ivector(1,n);
6481: ageexmed=vector(1,n);
6482: agecens=vector(1,n);
6483: dcwave=ivector(1,n);
6484:
6485: for (i=1; i<=imx; i++){
6486: dcwave[i]=-1;
6487: for (m=firstpass; m<=lastpass; m++)
6488: if (s[m][i]>nlstate) {
6489: dcwave[i]=m;
6490: /* printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
6491: break;
6492: }
6493: }
6494:
6495: for (i=1; i<=imx; i++) {
6496: if (wav[i]>0){
6497: ageexmed[i]=agev[mw[1][i]][i];
6498: j=wav[i];
6499: agecens[i]=1.;
6500:
6501: if (ageexmed[i]> 1 && wav[i] > 0){
6502: agecens[i]=agev[mw[j][i]][i];
6503: cens[i]= 1;
6504: }else if (ageexmed[i]< 1)
6505: cens[i]= -1;
6506: if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
6507: cens[i]=0 ;
6508: }
6509: else cens[i]=-1;
6510: }
6511:
6512: for (i=1;i<=NDIM;i++) {
6513: for (j=1;j<=NDIM;j++)
6514: ximort[i][j]=(i == j ? 1.0 : 0.0);
6515: }
6516:
6517: /*p[1]=0.0268; p[NDIM]=0.083;*/
6518: /*printf("%lf %lf", p[1], p[2]);*/
6519:
6520:
6521: #ifdef GSL
6522: printf("GSL optimization\n"); fprintf(ficlog,"Powell\n");
6523: #else
6524: printf("Powell\n"); fprintf(ficlog,"Powell\n");
6525: #endif
6526: strcpy(filerespow,"pow-mort");
6527: strcat(filerespow,fileres);
6528: if((ficrespow=fopen(filerespow,"w"))==NULL) {
6529: printf("Problem with resultfile: %s\n", filerespow);
6530: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
6531: }
6532: #ifdef GSL
6533: fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
6534: #else
6535: fprintf(ficrespow,"# Powell\n# iter -2*LL");
6536: #endif
6537: /* for (i=1;i<=nlstate;i++)
6538: for(j=1;j<=nlstate+ndeath;j++)
6539: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
6540: */
6541: fprintf(ficrespow,"\n");
6542: #ifdef GSL
6543: /* gsl starts here */
6544: T = gsl_multimin_fminimizer_nmsimplex;
6545: gsl_multimin_fminimizer *sfm = NULL;
6546: gsl_vector *ss, *x;
6547: gsl_multimin_function minex_func;
6548:
6549: /* Initial vertex size vector */
6550: ss = gsl_vector_alloc (NDIM);
6551:
6552: if (ss == NULL){
6553: GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
6554: }
6555: /* Set all step sizes to 1 */
6556: gsl_vector_set_all (ss, 0.001);
6557:
6558: /* Starting point */
6559:
6560: x = gsl_vector_alloc (NDIM);
6561:
6562: if (x == NULL){
6563: gsl_vector_free(ss);
6564: GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
6565: }
6566:
6567: /* Initialize method and iterate */
6568: /* p[1]=0.0268; p[NDIM]=0.083; */
6569: /* gsl_vector_set(x, 0, 0.0268); */
6570: /* gsl_vector_set(x, 1, 0.083); */
6571: gsl_vector_set(x, 0, p[1]);
6572: gsl_vector_set(x, 1, p[2]);
6573:
6574: minex_func.f = &gompertz_f;
6575: minex_func.n = NDIM;
6576: minex_func.params = (void *)&p; /* ??? */
6577:
6578: sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
6579: gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
6580:
6581: printf("Iterations beginning .....\n\n");
6582: printf("Iter. # Intercept Slope -Log Likelihood Simplex size\n");
6583:
6584: iteri=0;
6585: while (rval == GSL_CONTINUE){
6586: iteri++;
6587: status = gsl_multimin_fminimizer_iterate(sfm);
6588:
6589: if (status) printf("error: %s\n", gsl_strerror (status));
6590: fflush(0);
6591:
6592: if (status)
6593: break;
6594:
6595: rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
6596: ssval = gsl_multimin_fminimizer_size (sfm);
6597:
6598: if (rval == GSL_SUCCESS)
6599: printf ("converged to a local maximum at\n");
6600:
6601: printf("%5d ", iteri);
6602: for (it = 0; it < NDIM; it++){
6603: printf ("%10.5f ", gsl_vector_get (sfm->x, it));
6604: }
6605: printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
6606: }
6607:
6608: printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
6609:
6610: gsl_vector_free(x); /* initial values */
6611: gsl_vector_free(ss); /* inital step size */
6612: for (it=0; it<NDIM; it++){
6613: p[it+1]=gsl_vector_get(sfm->x,it);
6614: fprintf(ficrespow," %.12lf", p[it]);
6615: }
6616: gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1) */
6617: #endif
6618: #ifdef POWELL
6619: powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
6620: #endif
6621: fclose(ficrespow);
6622:
6623: hesscov(matcov, p, NDIM, delti, 1e-4, gompertz);
6624:
6625: for(i=1; i <=NDIM; i++)
6626: for(j=i+1;j<=NDIM;j++)
6627: matcov[i][j]=matcov[j][i];
6628:
6629: printf("\nCovariance matrix\n ");
6630: for(i=1; i <=NDIM; i++) {
6631: for(j=1;j<=NDIM;j++){
6632: printf("%f ",matcov[i][j]);
6633: }
6634: printf("\n ");
6635: }
6636:
6637: printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
6638: for (i=1;i<=NDIM;i++)
6639: printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
6640:
6641: lsurv=vector(1,AGESUP);
6642: lpop=vector(1,AGESUP);
6643: tpop=vector(1,AGESUP);
6644: lsurv[agegomp]=100000;
6645:
6646: for (k=agegomp;k<=AGESUP;k++) {
6647: agemortsup=k;
6648: if (p[1]*exp(p[2]*(k-agegomp))>1) break;
6649: }
6650:
6651: for (k=agegomp;k<agemortsup;k++)
6652: lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
6653:
6654: for (k=agegomp;k<agemortsup;k++){
6655: lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
6656: sumlpop=sumlpop+lpop[k];
6657: }
6658:
6659: tpop[agegomp]=sumlpop;
6660: for (k=agegomp;k<(agemortsup-3);k++){
6661: /* tpop[k+1]=2;*/
6662: tpop[k+1]=tpop[k]-lpop[k];
6663: }
6664:
6665:
6666: printf("\nAge lx qx dx Lx Tx e(x)\n");
6667: for (k=agegomp;k<(agemortsup-2);k++)
6668: 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]);
6669:
6670:
6671: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6672: printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6673:
6674: printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
6675: stepm, weightopt,\
6676: model,imx,p,matcov,agemortsup);
6677:
6678: free_vector(lsurv,1,AGESUP);
6679: free_vector(lpop,1,AGESUP);
6680: free_vector(tpop,1,AGESUP);
6681: #ifdef GSL
6682: free_ivector(cens,1,n);
6683: free_vector(agecens,1,n);
6684: free_ivector(dcwave,1,n);
6685: free_matrix(ximort,1,NDIM,1,NDIM);
6686: #endif
6687: } /* Endof if mle==-3 */
6688:
6689: else{ /* For mle >=1 */
6690: globpr=0;/* debug */
6691: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
6692: printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6693: for (k=1; k<=npar;k++)
6694: printf(" %d %8.5f",k,p[k]);
6695: printf("\n");
6696: globpr=1; /* to print the contributions */
6697: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
6698: printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
6699: for (k=1; k<=npar;k++)
6700: printf(" %d %8.5f",k,p[k]);
6701: printf("\n");
6702: if(mle>=1){ /* Could be 1 or 2 */
6703: mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
6704: }
6705:
6706: /*--------- results files --------------*/
6707: 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);
6708:
6709:
6710: fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6711: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6712: fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
6713: for(i=1,jk=1; i <=nlstate; i++){
6714: for(k=1; k <=(nlstate+ndeath); k++){
6715: if (k != i) {
6716: printf("%d%d ",i,k);
6717: fprintf(ficlog,"%d%d ",i,k);
6718: fprintf(ficres,"%1d%1d ",i,k);
6719: for(j=1; j <=ncovmodel; j++){
6720: printf("%lf ",p[jk]);
6721: fprintf(ficlog,"%lf ",p[jk]);
6722: fprintf(ficres,"%lf ",p[jk]);
6723: jk++;
6724: }
6725: printf("\n");
6726: fprintf(ficlog,"\n");
6727: fprintf(ficres,"\n");
6728: }
6729: }
6730: }
6731: if(mle!=0){
6732: /* Computing hessian and covariance matrix */
6733: ftolhess=ftol; /* Usually correct */
6734: hesscov(matcov, p, npar, delti, ftolhess, func);
6735: }
6736: fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
6737: printf("# Scales (for hessian or gradient estimation)\n");
6738: fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
6739: for(i=1,jk=1; i <=nlstate; i++){
6740: for(j=1; j <=nlstate+ndeath; j++){
6741: if (j!=i) {
6742: fprintf(ficres,"%1d%1d",i,j);
6743: printf("%1d%1d",i,j);
6744: fprintf(ficlog,"%1d%1d",i,j);
6745: for(k=1; k<=ncovmodel;k++){
6746: printf(" %.5e",delti[jk]);
6747: fprintf(ficlog," %.5e",delti[jk]);
6748: fprintf(ficres," %.5e",delti[jk]);
6749: jk++;
6750: }
6751: printf("\n");
6752: fprintf(ficlog,"\n");
6753: fprintf(ficres,"\n");
6754: }
6755: }
6756: }
6757:
6758: 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");
6759: if(mle>=1)
6760: 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");
6761: 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");
6762: /* # 121 Var(a12)\n\ */
6763: /* # 122 Cov(b12,a12) Var(b12)\n\ */
6764: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
6765: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
6766: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
6767: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
6768: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
6769: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
6770:
6771:
6772: /* Just to have a covariance matrix which will be more understandable
6773: even is we still don't want to manage dictionary of variables
6774: */
6775: for(itimes=1;itimes<=2;itimes++){
6776: jj=0;
6777: for(i=1; i <=nlstate; i++){
6778: for(j=1; j <=nlstate+ndeath; j++){
6779: if(j==i) continue;
6780: for(k=1; k<=ncovmodel;k++){
6781: jj++;
6782: ca[0]= k+'a'-1;ca[1]='\0';
6783: if(itimes==1){
6784: if(mle>=1)
6785: printf("#%1d%1d%d",i,j,k);
6786: fprintf(ficlog,"#%1d%1d%d",i,j,k);
6787: fprintf(ficres,"#%1d%1d%d",i,j,k);
6788: }else{
6789: if(mle>=1)
6790: printf("%1d%1d%d",i,j,k);
6791: fprintf(ficlog,"%1d%1d%d",i,j,k);
6792: fprintf(ficres,"%1d%1d%d",i,j,k);
6793: }
6794: ll=0;
6795: for(li=1;li <=nlstate; li++){
6796: for(lj=1;lj <=nlstate+ndeath; lj++){
6797: if(lj==li) continue;
6798: for(lk=1;lk<=ncovmodel;lk++){
6799: ll++;
6800: if(ll<=jj){
6801: cb[0]= lk +'a'-1;cb[1]='\0';
6802: if(ll<jj){
6803: if(itimes==1){
6804: if(mle>=1)
6805: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6806: fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6807: fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
6808: }else{
6809: if(mle>=1)
6810: printf(" %.5e",matcov[jj][ll]);
6811: fprintf(ficlog," %.5e",matcov[jj][ll]);
6812: fprintf(ficres," %.5e",matcov[jj][ll]);
6813: }
6814: }else{
6815: if(itimes==1){
6816: if(mle>=1)
6817: printf(" Var(%s%1d%1d)",ca,i,j);
6818: fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
6819: fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
6820: }else{
6821: if(mle>=1)
6822: printf(" %.5e",matcov[jj][ll]);
6823: fprintf(ficlog," %.5e",matcov[jj][ll]);
6824: fprintf(ficres," %.5e",matcov[jj][ll]);
6825: }
6826: }
6827: }
6828: } /* end lk */
6829: } /* end lj */
6830: } /* end li */
6831: if(mle>=1)
6832: printf("\n");
6833: fprintf(ficlog,"\n");
6834: fprintf(ficres,"\n");
6835: numlinepar++;
6836: } /* end k*/
6837: } /*end j */
6838: } /* end i */
6839: } /* end itimes */
6840:
6841: fflush(ficlog);
6842: fflush(ficres);
6843:
6844: while((c=getc(ficpar))=='#' && c!= EOF){
6845: ungetc(c,ficpar);
6846: fgets(line, MAXLINE, ficpar);
6847: fputs(line,stdout);
6848: fputs(line,ficparo);
6849: }
6850: ungetc(c,ficpar);
6851:
6852: estepm=0;
6853: fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
6854: if (estepm==0 || estepm < stepm) estepm=stepm;
6855: if (fage <= 2) {
6856: bage = ageminpar;
6857: fage = agemaxpar;
6858: }
6859:
6860: fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
6861: fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6862: fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
6863:
6864: while((c=getc(ficpar))=='#' && c!= EOF){
6865: ungetc(c,ficpar);
6866: fgets(line, MAXLINE, ficpar);
6867: fputs(line,stdout);
6868: fputs(line,ficparo);
6869: }
6870: ungetc(c,ficpar);
6871:
6872: 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);
6873: 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);
6874: 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);
6875: printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
6876: 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);
6877:
6878: while((c=getc(ficpar))=='#' && c!= EOF){
6879: ungetc(c,ficpar);
6880: fgets(line, MAXLINE, ficpar);
6881: fputs(line,stdout);
6882: fputs(line,ficparo);
6883: }
6884: ungetc(c,ficpar);
6885:
6886:
6887: dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
6888: dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
6889:
6890: fscanf(ficpar,"pop_based=%d\n",&popbased);
6891: fprintf(ficparo,"pop_based=%d\n",popbased);
6892: fprintf(ficres,"pop_based=%d\n",popbased);
6893:
6894: while((c=getc(ficpar))=='#' && c!= EOF){
6895: ungetc(c,ficpar);
6896: fgets(line, MAXLINE, ficpar);
6897: fputs(line,stdout);
6898: fputs(line,ficparo);
6899: }
6900: ungetc(c,ficpar);
6901:
6902: 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);
6903: 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);
6904: 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);
6905: 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);
6906: 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);
6907: /* day and month of proj2 are not used but only year anproj2.*/
6908:
6909:
6910:
6911: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
6912: /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
6913:
6914: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
6915: printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
6916:
6917: printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
6918: model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
6919: jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
6920:
6921: /*------------ free_vector -------------*/
6922: /* chdir(path); */
6923:
6924: free_ivector(wav,1,imx);
6925: free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
6926: free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
6927: free_imatrix(mw,1,lastpass-firstpass+1,1,imx);
6928: free_lvector(num,1,n);
6929: free_vector(agedc,1,n);
6930: /*free_matrix(covar,0,NCOVMAX,1,n);*/
6931: /*free_matrix(covar,1,NCOVMAX,1,n);*/
6932: fclose(ficparo);
6933: fclose(ficres);
6934:
6935:
6936: /*--------------- Prevalence limit (period or stable prevalence) --------------*/
6937: /*#include "prevlim.h"*/ /* Use ficrespl, ficlog */
6938: prlim=matrix(1,nlstate,1,nlstate);
6939: prevalence_limit(p, prlim, ageminpar, agemaxpar);
6940: fclose(ficrespl);
6941:
6942: #ifdef FREEEXIT2
6943: #include "freeexit2.h"
6944: #endif
6945:
6946: /*------------- h Pij x at various ages ------------*/
6947: /*#include "hpijx.h"*/
6948: hPijx(p, bage, fage);
6949: fclose(ficrespij);
6950:
6951: /*-------------- Variance of one-step probabilities---*/
6952: k=1;
6953: varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
6954:
6955:
6956: probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
6957: for(i=1;i<=AGESUP;i++)
6958: for(j=1;j<=NCOVMAX;j++)
6959: for(k=1;k<=NCOVMAX;k++)
6960: probs[i][j][k]=0.;
6961:
6962: /*---------- Forecasting ------------------*/
6963: /*if((stepm == 1) && (strcmp(model,".")==0)){*/
6964: if(prevfcast==1){
6965: /* if(stepm ==1){*/
6966: prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
6967: /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
6968: /* } */
6969: /* else{ */
6970: /* erreur=108; */
6971: /* 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); */
6972: /* 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); */
6973: /* } */
6974: }
6975:
6976:
6977: /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
6978:
6979: prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
6980: /* 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",\
6981: ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
6982: */
6983:
6984: if (mobilav!=0) {
6985: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
6986: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
6987: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
6988: printf(" Error in movingaverage mobilav=%d\n",mobilav);
6989: }
6990: }
6991:
6992:
6993: /*---------- Health expectancies, no variances ------------*/
6994:
6995: strcpy(filerese,"e");
6996: strcat(filerese,fileres);
6997: if((ficreseij=fopen(filerese,"w"))==NULL) {
6998: printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
6999: fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
7000: }
7001: printf("Computing Health Expectancies: result on file '%s' \n", filerese);
7002: fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
7003: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
7004: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
7005:
7006: for (k=1; k <= (int) pow(2,cptcoveff); k++){
7007: fprintf(ficreseij,"\n#****** ");
7008: for(j=1;j<=cptcoveff;j++) {
7009: fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7010: }
7011: fprintf(ficreseij,"******\n");
7012:
7013: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
7014: oldm=oldms;savm=savms;
7015: evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);
7016:
7017: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
7018: /*}*/
7019: }
7020: fclose(ficreseij);
7021:
7022:
7023: /*---------- Health expectancies and variances ------------*/
7024:
7025:
7026: strcpy(filerest,"t");
7027: strcat(filerest,fileres);
7028: if((ficrest=fopen(filerest,"w"))==NULL) {
7029: printf("Problem with total LE resultfile: %s\n", filerest);goto end;
7030: fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
7031: }
7032: printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
7033: fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest);
7034:
7035:
7036: strcpy(fileresstde,"stde");
7037: strcat(fileresstde,fileres);
7038: if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
7039: printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
7040: fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
7041: }
7042: printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
7043: fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
7044:
7045: strcpy(filerescve,"cve");
7046: strcat(filerescve,fileres);
7047: if((ficrescveij=fopen(filerescve,"w"))==NULL) {
7048: printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
7049: fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
7050: }
7051: printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
7052: fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
7053:
7054: strcpy(fileresv,"v");
7055: strcat(fileresv,fileres);
7056: if((ficresvij=fopen(fileresv,"w"))==NULL) {
7057: printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
7058: fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
7059: }
7060: printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
7061: fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
7062:
7063: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
7064: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
7065:
7066: for (k=1; k <= (int) pow(2,cptcoveff); k++){
7067: fprintf(ficrest,"\n#****** ");
7068: for(j=1;j<=cptcoveff;j++)
7069: fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7070: fprintf(ficrest,"******\n");
7071:
7072: fprintf(ficresstdeij,"\n#****** ");
7073: fprintf(ficrescveij,"\n#****** ");
7074: for(j=1;j<=cptcoveff;j++) {
7075: fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7076: fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7077: }
7078: fprintf(ficresstdeij,"******\n");
7079: fprintf(ficrescveij,"******\n");
7080:
7081: fprintf(ficresvij,"\n#****** ");
7082: for(j=1;j<=cptcoveff;j++)
7083: fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7084: fprintf(ficresvij,"******\n");
7085:
7086: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
7087: oldm=oldms;savm=savms;
7088: cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
7089: /*
7090: */
7091: /* goto endfree; */
7092:
7093: vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
7094: pstamp(ficrest);
7095:
7096:
7097: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
7098: oldm=oldms;savm=savms; /* Segmentation fault */
7099: cptcod= 0; /* To be deleted */
7100: 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 */
7101: 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 ");
7102: if(vpopbased==1)
7103: 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);
7104: else
7105: fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
7106: fprintf(ficrest,"# Age e.. (std) ");
7107: for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
7108: fprintf(ficrest,"\n");
7109:
7110: epj=vector(1,nlstate+1);
7111: for(age=bage; age <=fage ;age++){
7112: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
7113: if (vpopbased==1) {
7114: if(mobilav ==0){
7115: for(i=1; i<=nlstate;i++)
7116: prlim[i][i]=probs[(int)age][i][k];
7117: }else{ /* mobilav */
7118: for(i=1; i<=nlstate;i++)
7119: prlim[i][i]=mobaverage[(int)age][i][k];
7120: }
7121: }
7122:
7123: fprintf(ficrest," %4.0f",age);
7124: for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
7125: for(i=1, epj[j]=0.;i <=nlstate;i++) {
7126: epj[j] += prlim[i][i]*eij[i][j][(int)age];
7127: /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
7128: }
7129: epj[nlstate+1] +=epj[j];
7130: }
7131:
7132: for(i=1, vepp=0.;i <=nlstate;i++)
7133: for(j=1;j <=nlstate;j++)
7134: vepp += vareij[i][j][(int)age];
7135: fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
7136: for(j=1;j <=nlstate;j++){
7137: fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
7138: }
7139: fprintf(ficrest,"\n");
7140: }
7141: }
7142: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
7143: free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
7144: free_vector(epj,1,nlstate+1);
7145: /*}*/
7146: }
7147: free_vector(weight,1,n);
7148: free_imatrix(Tvard,1,NCOVMAX,1,2);
7149: free_imatrix(s,1,maxwav+1,1,n);
7150: free_matrix(anint,1,maxwav,1,n);
7151: free_matrix(mint,1,maxwav,1,n);
7152: free_ivector(cod,1,n);
7153: free_ivector(tab,1,NCOVMAX);
7154: fclose(ficresstdeij);
7155: fclose(ficrescveij);
7156: fclose(ficresvij);
7157: fclose(ficrest);
7158: fclose(ficpar);
7159:
7160: /*------- Variance of period (stable) prevalence------*/
7161:
7162: strcpy(fileresvpl,"vpl");
7163: strcat(fileresvpl,fileres);
7164: if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
7165: printf("Problem with variance of period (stable) prevalence resultfile: %s\n", fileresvpl);
7166: exit(0);
7167: }
7168: printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
7169:
7170: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
7171: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
7172:
7173: for (k=1; k <= (int) pow(2,cptcoveff); k++){
7174: fprintf(ficresvpl,"\n#****** ");
7175: for(j=1;j<=cptcoveff;j++)
7176: fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
7177: fprintf(ficresvpl,"******\n");
7178:
7179: varpl=matrix(1,nlstate,(int) bage, (int) fage);
7180: oldm=oldms;savm=savms;
7181: varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
7182: free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
7183: /*}*/
7184: }
7185:
7186: fclose(ficresvpl);
7187:
7188: /*---------- End : free ----------------*/
7189: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
7190: free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
7191: } /* mle==-3 arrives here for freeing */
7192: /* endfree:*/
7193: free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
7194: free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
7195: free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
7196: free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
7197: free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
7198: free_matrix(covar,0,NCOVMAX,1,n);
7199: free_matrix(matcov,1,npar,1,npar);
7200: /*free_vector(delti,1,npar);*/
7201: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
7202: free_matrix(agev,1,maxwav,1,imx);
7203: free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
7204:
7205: free_ivector(ncodemax,1,NCOVMAX);
7206: free_ivector(Tvar,1,NCOVMAX);
7207: free_ivector(Tprod,1,NCOVMAX);
7208: free_ivector(Tvaraff,1,NCOVMAX);
7209: free_ivector(Tage,1,NCOVMAX);
7210:
7211: free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
7212: free_imatrix(codtab,1,100,1,10);
7213: fflush(fichtm);
7214: fflush(ficgp);
7215:
7216:
7217: if((nberr >0) || (nbwarn>0)){
7218: printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
7219: fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
7220: }else{
7221: printf("End of Imach\n");
7222: fprintf(ficlog,"End of Imach\n");
7223: }
7224: printf("See log file on %s\n",filelog);
7225: /* gettimeofday(&end_time, (struct timezone*)0);*/ /* after time */
7226: /*(void) gettimeofday(&end_time,&tzp);*/
7227: rend_time = time(NULL);
7228: end_time = *localtime(&rend_time);
7229: /* tml = *localtime(&end_time.tm_sec); */
7230: strcpy(strtend,asctime(&end_time));
7231: printf("Local time at start %s\nLocal time at end %s",strstart, strtend);
7232: fprintf(ficlog,"Local time at start %s\nLocal time at end %s\n",strstart, strtend);
7233: printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
7234:
7235: printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
7236: fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
7237: fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
7238: /* printf("Total time was %d uSec.\n", total_usecs);*/
7239: /* if(fileappend(fichtm,optionfilehtm)){ */
7240: fprintf(fichtm,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
7241: fclose(fichtm);
7242: fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend);
7243: fclose(fichtmcov);
7244: fclose(ficgp);
7245: fclose(ficlog);
7246: /*------ End -----------*/
7247:
7248:
7249: printf("Before Current directory %s!\n",pathcd);
7250: if(chdir(pathcd) != 0)
7251: printf("Can't move to directory %s!\n",path);
7252: if(getcwd(pathcd,MAXLINE) > 0)
7253: printf("Current directory %s!\n",pathcd);
7254: /*strcat(plotcmd,CHARSEPARATOR);*/
7255: sprintf(plotcmd,"gnuplot");
7256: #ifdef _WIN32
7257: sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
7258: #endif
7259: if(!stat(plotcmd,&info)){
7260: printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
7261: if(!stat(getenv("GNUPLOTBIN"),&info)){
7262: printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
7263: }else
7264: strcpy(pplotcmd,plotcmd);
7265: #ifdef __unix
7266: strcpy(plotcmd,GNUPLOTPROGRAM);
7267: if(!stat(plotcmd,&info)){
7268: printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
7269: }else
7270: strcpy(pplotcmd,plotcmd);
7271: #endif
7272: }else
7273: strcpy(pplotcmd,plotcmd);
7274:
7275: sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
7276: printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
7277:
7278: if((outcmd=system(plotcmd)) != 0){
7279: printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
7280: printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
7281: sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
7282: if((outcmd=system(plotcmd)) != 0)
7283: printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
7284: }
7285: printf(" Successful, please wait...");
7286: while (z[0] != 'q') {
7287: /* chdir(path); */
7288: printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
7289: scanf("%s",z);
7290: /* if (z[0] == 'c') system("./imach"); */
7291: if (z[0] == 'e') {
7292: #ifdef __APPLE__
7293: sprintf(pplotcmd, "open %s", optionfilehtm);
7294: #elif __linux
7295: sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
7296: #else
7297: sprintf(pplotcmd, "%s", optionfilehtm);
7298: #endif
7299: printf("Starting browser with: %s",pplotcmd);fflush(stdout);
7300: system(pplotcmd);
7301: }
7302: else if (z[0] == 'g') system(plotcmd);
7303: else if (z[0] == 'q') exit(0);
7304: }
7305: end:
7306: while (z[0] != 'q') {
7307: printf("\nType q for exiting: ");
7308: scanf("%s",z);
7309: }
7310: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>