![]() ![]() | ![]() |
Summary: trying to detect cross-compilation
1: /* $Id: imach.c,v 1.173 2015/01/03 12:06:26 brouard Exp $ 2: $State: Exp $ 3: $Log: imach.c,v $ 4: Revision 1.173 2015/01/03 12:06:26 brouard 5: Summary: trying to detect cross-compilation 6: 7: Revision 1.172 2014/12/27 12:07:47 brouard 8: Summary: Back from Visual Studio and Intel, options for compiling for Windows XP 9: 10: Revision 1.171 2014/12/23 13:26:59 brouard 11: Summary: Back from Visual C 12: 13: Still problem with utsname.h on Windows 14: 15: Revision 1.170 2014/12/23 11:17:12 brouard 16: Summary: Cleaning some \%% back to %% 17: 18: The escape was mandatory for a specific compiler (which one?), but too many warnings. 19: 20: Revision 1.169 2014/12/22 23:08:31 brouard 21: Summary: 0.98p 22: 23: Outputs some informations on compiler used, OS etc. Testing on different platforms. 24: 25: Revision 1.168 2014/12/22 15:17:42 brouard 26: Summary: update 27: 28: Revision 1.167 2014/12/22 13:50:56 brouard 29: Summary: Testing uname and compiler version and if compiled 32 or 64 30: 31: Testing on Linux 64 32: 33: Revision 1.166 2014/12/22 11:40:47 brouard 34: *** empty log message *** 35: 36: Revision 1.165 2014/12/16 11:20:36 brouard 37: Summary: After compiling on Visual C 38: 39: * imach.c (Module): Merging 1.61 to 1.162 40: 41: Revision 1.164 2014/12/16 10:52:11 brouard 42: Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn 43: 44: * imach.c (Module): Merging 1.61 to 1.162 45: 46: Revision 1.163 2014/12/16 10:30:11 brouard 47: * imach.c (Module): Merging 1.61 to 1.162 48: 49: Revision 1.162 2014/09/25 11:43:39 brouard 50: Summary: temporary backup 0.99! 51: 52: Revision 1.1 2014/09/16 11:06:58 brouard 53: Summary: With some code (wrong) for nlopt 54: 55: Author: 56: 57: Revision 1.161 2014/09/15 20:41:41 brouard 58: Summary: Problem with macro SQR on Intel compiler 59: 60: Revision 1.160 2014/09/02 09:24:05 brouard 61: *** empty log message *** 62: 63: Revision 1.159 2014/09/01 10:34:10 brouard 64: Summary: WIN32 65: Author: Brouard 66: 67: Revision 1.158 2014/08/27 17:11:51 brouard 68: *** empty log message *** 69: 70: Revision 1.157 2014/08/27 16:26:55 brouard 71: Summary: Preparing windows Visual studio version 72: Author: Brouard 73: 74: In order to compile on Visual studio, time.h is now correct and time_t 75: and tm struct should be used. difftime should be used but sometimes I 76: just make the differences in raw time format (time(&now). 77: Trying to suppress #ifdef LINUX 78: Add xdg-open for __linux in order to open default browser. 79: 80: Revision 1.156 2014/08/25 20:10:10 brouard 81: *** empty log message *** 82: 83: Revision 1.155 2014/08/25 18:32:34 brouard 84: Summary: New compile, minor changes 85: Author: Brouard 86: 87: Revision 1.154 2014/06/20 17:32:08 brouard 88: Summary: Outputs now all graphs of convergence to period prevalence 89: 90: Revision 1.153 2014/06/20 16:45:46 brouard 91: Summary: If 3 live state, convergence to period prevalence on same graph 92: Author: Brouard 93: 94: Revision 1.152 2014/06/18 17:54:09 brouard 95: Summary: open browser, use gnuplot on same dir than imach if not found in the path 96: 97: Revision 1.151 2014/06/18 16:43:30 brouard 98: *** empty log message *** 99: 100: Revision 1.150 2014/06/18 16:42:35 brouard 101: Summary: If gnuplot is not in the path try on same directory than imach binary (OSX) 102: Author: brouard 103: 104: Revision 1.149 2014/06/18 15:51:14 brouard 105: Summary: Some fixes in parameter files errors 106: Author: Nicolas Brouard 107: 108: Revision 1.148 2014/06/17 17:38:48 brouard 109: Summary: Nothing new 110: Author: Brouard 111: 112: Just a new packaging for OS/X version 0.98nS 113: 114: Revision 1.147 2014/06/16 10:33:11 brouard 115: *** empty log message *** 116: 117: Revision 1.146 2014/06/16 10:20:28 brouard 118: Summary: Merge 119: Author: Brouard 120: 121: Merge, before building revised version. 122: 123: Revision 1.145 2014/06/10 21:23:15 brouard 124: Summary: Debugging with valgrind 125: Author: Nicolas Brouard 126: 127: Lot of changes in order to output the results with some covariates 128: After the Edimburgh REVES conference 2014, it seems mandatory to 129: improve the code. 130: No more memory valgrind error but a lot has to be done in order to 131: continue the work of splitting the code into subroutines. 132: Also, decodemodel has been improved. Tricode is still not 133: optimal. nbcode should be improved. Documentation has been added in 134: the source code. 135: 136: Revision 1.143 2014/01/26 09:45:38 brouard 137: Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising 138: 139: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested... 140: (Module): Version 0.98nR Running ok, but output format still only works for three covariates. 141: 142: Revision 1.142 2014/01/26 03:57:36 brouard 143: Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2 144: 145: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested... 146: 147: Revision 1.141 2014/01/26 02:42:01 brouard 148: * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested... 149: 150: Revision 1.140 2011/09/02 10:37:54 brouard 151: Summary: times.h is ok with mingw32 now. 152: 153: Revision 1.139 2010/06/14 07:50:17 brouard 154: After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree. 155: I remember having already fixed agemin agemax which are pointers now but not cvs saved. 156: 157: Revision 1.138 2010/04/30 18:19:40 brouard 158: *** empty log message *** 159: 160: Revision 1.137 2010/04/29 18:11:38 brouard 161: (Module): Checking covariates for more complex models 162: than V1+V2. A lot of change to be done. Unstable. 163: 164: Revision 1.136 2010/04/26 20:30:53 brouard 165: (Module): merging some libgsl code. Fixing computation 166: of likelione (using inter/intrapolation if mle = 0) in order to 167: get same likelihood as if mle=1. 168: Some cleaning of code and comments added. 169: 170: Revision 1.135 2009/10/29 15:33:14 brouard 171: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code. 172: 173: Revision 1.134 2009/10/29 13:18:53 brouard 174: (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code. 175: 176: Revision 1.133 2009/07/06 10:21:25 brouard 177: just nforces 178: 179: Revision 1.132 2009/07/06 08:22:05 brouard 180: Many tings 181: 182: Revision 1.131 2009/06/20 16:22:47 brouard 183: Some dimensions resccaled 184: 185: Revision 1.130 2009/05/26 06:44:34 brouard 186: (Module): Max Covariate is now set to 20 instead of 8. A 187: lot of cleaning with variables initialized to 0. Trying to make 188: V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better. 189: 190: Revision 1.129 2007/08/31 13:49:27 lievre 191: Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting 192: 193: Revision 1.128 2006/06/30 13:02:05 brouard 194: (Module): Clarifications on computing e.j 195: 196: Revision 1.127 2006/04/28 18:11:50 brouard 197: (Module): Yes the sum of survivors was wrong since 198: imach-114 because nhstepm was no more computed in the age 199: loop. Now we define nhstepma in the age loop. 200: (Module): In order to speed up (in case of numerous covariates) we 201: compute health expectancies (without variances) in a first step 202: and then all the health expectancies with variances or standard 203: deviation (needs data from the Hessian matrices) which slows the 204: computation. 205: In the future we should be able to stop the program is only health 206: expectancies and graph are needed without standard deviations. 207: 208: Revision 1.126 2006/04/28 17:23:28 brouard 209: (Module): Yes the sum of survivors was wrong since 210: imach-114 because nhstepm was no more computed in the age 211: loop. Now we define nhstepma in the age loop. 212: Version 0.98h 213: 214: Revision 1.125 2006/04/04 15:20:31 lievre 215: Errors in calculation of health expectancies. Age was not initialized. 216: Forecasting file added. 217: 218: Revision 1.124 2006/03/22 17:13:53 lievre 219: Parameters are printed with %lf instead of %f (more numbers after the comma). 220: The log-likelihood is printed in the log file 221: 222: Revision 1.123 2006/03/20 10:52:43 brouard 223: * imach.c (Module): <title> changed, corresponds to .htm file 224: name. <head> headers where missing. 225: 226: * imach.c (Module): Weights can have a decimal point as for 227: English (a comma might work with a correct LC_NUMERIC environment, 228: otherwise the weight is truncated). 229: Modification of warning when the covariates values are not 0 or 230: 1. 231: Version 0.98g 232: 233: Revision 1.122 2006/03/20 09:45:41 brouard 234: (Module): Weights can have a decimal point as for 235: English (a comma might work with a correct LC_NUMERIC environment, 236: otherwise the weight is truncated). 237: Modification of warning when the covariates values are not 0 or 238: 1. 239: Version 0.98g 240: 241: Revision 1.121 2006/03/16 17:45:01 lievre 242: * imach.c (Module): Comments concerning covariates added 243: 244: * imach.c (Module): refinements in the computation of lli if 245: status=-2 in order to have more reliable computation if stepm is 246: not 1 month. Version 0.98f 247: 248: Revision 1.120 2006/03/16 15:10:38 lievre 249: (Module): refinements in the computation of lli if 250: status=-2 in order to have more reliable computation if stepm is 251: not 1 month. Version 0.98f 252: 253: Revision 1.119 2006/03/15 17:42:26 brouard 254: (Module): Bug if status = -2, the loglikelihood was 255: computed as likelihood omitting the logarithm. Version O.98e 256: 257: Revision 1.118 2006/03/14 18:20:07 brouard 258: (Module): varevsij Comments added explaining the second 259: table of variances if popbased=1 . 260: (Module): Covariances of eij, ekl added, graphs fixed, new html link. 261: (Module): Function pstamp added 262: (Module): Version 0.98d 263: 264: Revision 1.117 2006/03/14 17:16:22 brouard 265: (Module): varevsij Comments added explaining the second 266: table of variances if popbased=1 . 267: (Module): Covariances of eij, ekl added, graphs fixed, new html link. 268: (Module): Function pstamp added 269: (Module): Version 0.98d 270: 271: Revision 1.116 2006/03/06 10:29:27 brouard 272: (Module): Variance-covariance wrong links and 273: varian-covariance of ej. is needed (Saito). 274: 275: Revision 1.115 2006/02/27 12:17:45 brouard 276: (Module): One freematrix added in mlikeli! 0.98c 277: 278: Revision 1.114 2006/02/26 12:57:58 brouard 279: (Module): Some improvements in processing parameter 280: filename with strsep. 281: 282: Revision 1.113 2006/02/24 14:20:24 brouard 283: (Module): Memory leaks checks with valgrind and: 284: datafile was not closed, some imatrix were not freed and on matrix 285: allocation too. 286: 287: Revision 1.112 2006/01/30 09:55:26 brouard 288: (Module): Back to gnuplot.exe instead of wgnuplot.exe 289: 290: Revision 1.111 2006/01/25 20:38:18 brouard 291: (Module): Lots of cleaning and bugs added (Gompertz) 292: (Module): Comments can be added in data file. Missing date values 293: can be a simple dot '.'. 294: 295: Revision 1.110 2006/01/25 00:51:50 brouard 296: (Module): Lots of cleaning and bugs added (Gompertz) 297: 298: Revision 1.109 2006/01/24 19:37:15 brouard 299: (Module): Comments (lines starting with a #) are allowed in data. 300: 301: Revision 1.108 2006/01/19 18:05:42 lievre 302: Gnuplot problem appeared... 303: To be fixed 304: 305: Revision 1.107 2006/01/19 16:20:37 brouard 306: Test existence of gnuplot in imach path 307: 308: Revision 1.106 2006/01/19 13:24:36 brouard 309: Some cleaning and links added in html output 310: 311: Revision 1.105 2006/01/05 20:23:19 lievre 312: *** empty log message *** 313: 314: Revision 1.104 2005/09/30 16:11:43 lievre 315: (Module): sump fixed, loop imx fixed, and simplifications. 316: (Module): If the status is missing at the last wave but we know 317: that the person is alive, then we can code his/her status as -2 318: (instead of missing=-1 in earlier versions) and his/her 319: contributions to the likelihood is 1 - Prob of dying from last 320: health status (= 1-p13= p11+p12 in the easiest case of somebody in 321: the healthy state at last known wave). Version is 0.98 322: 323: Revision 1.103 2005/09/30 15:54:49 lievre 324: (Module): sump fixed, loop imx fixed, and simplifications. 325: 326: Revision 1.102 2004/09/15 17:31:30 brouard 327: Add the possibility to read data file including tab characters. 328: 329: Revision 1.101 2004/09/15 10:38:38 brouard 330: Fix on curr_time 331: 332: Revision 1.100 2004/07/12 18:29:06 brouard 333: Add version for Mac OS X. Just define UNIX in Makefile 334: 335: Revision 1.99 2004/06/05 08:57:40 brouard 336: *** empty log message *** 337: 338: Revision 1.98 2004/05/16 15:05:56 brouard 339: New version 0.97 . First attempt to estimate force of mortality 340: directly from the data i.e. without the need of knowing the health 341: state at each age, but using a Gompertz model: log u =a + b*age . 342: This is the basic analysis of mortality and should be done before any 343: other analysis, in order to test if the mortality estimated from the 344: cross-longitudinal survey is different from the mortality estimated 345: from other sources like vital statistic data. 346: 347: The same imach parameter file can be used but the option for mle should be -3. 348: 349: Agnès, who wrote this part of the code, tried to keep most of the 350: former routines in order to include the new code within the former code. 351: 352: The output is very simple: only an estimate of the intercept and of 353: the slope with 95% confident intervals. 354: 355: Current limitations: 356: A) Even if you enter covariates, i.e. with the 357: model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates. 358: B) There is no computation of Life Expectancy nor Life Table. 359: 360: Revision 1.97 2004/02/20 13:25:42 lievre 361: Version 0.96d. Population forecasting command line is (temporarily) 362: suppressed. 363: 364: Revision 1.96 2003/07/15 15:38:55 brouard 365: * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is 366: rewritten within the same printf. Workaround: many printfs. 367: 368: Revision 1.95 2003/07/08 07:54:34 brouard 369: * imach.c (Repository): 370: (Repository): Using imachwizard code to output a more meaningful covariance 371: matrix (cov(a12,c31) instead of numbers. 372: 373: Revision 1.94 2003/06/27 13:00:02 brouard 374: Just cleaning 375: 376: Revision 1.93 2003/06/25 16:33:55 brouard 377: (Module): On windows (cygwin) function asctime_r doesn't 378: exist so I changed back to asctime which exists. 379: (Module): Version 0.96b 380: 381: Revision 1.92 2003/06/25 16:30:45 brouard 382: (Module): On windows (cygwin) function asctime_r doesn't 383: exist so I changed back to asctime which exists. 384: 385: Revision 1.91 2003/06/25 15:30:29 brouard 386: * imach.c (Repository): Duplicated warning errors corrected. 387: (Repository): Elapsed time after each iteration is now output. It 388: helps to forecast when convergence will be reached. Elapsed time 389: is stamped in powell. We created a new html file for the graphs 390: concerning matrix of covariance. It has extension -cov.htm. 391: 392: Revision 1.90 2003/06/24 12:34:15 brouard 393: (Module): Some bugs corrected for windows. Also, when 394: mle=-1 a template is output in file "or"mypar.txt with the design 395: of the covariance matrix to be input. 396: 397: Revision 1.89 2003/06/24 12:30:52 brouard 398: (Module): Some bugs corrected for windows. Also, when 399: mle=-1 a template is output in file "or"mypar.txt with the design 400: of the covariance matrix to be input. 401: 402: Revision 1.88 2003/06/23 17:54:56 brouard 403: * 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. 404: 405: Revision 1.87 2003/06/18 12:26:01 brouard 406: Version 0.96 407: 408: Revision 1.86 2003/06/17 20:04:08 brouard 409: (Module): Change position of html and gnuplot routines and added 410: routine fileappend. 411: 412: Revision 1.85 2003/06/17 13:12:43 brouard 413: * imach.c (Repository): Check when date of death was earlier that 414: current date of interview. It may happen when the death was just 415: prior to the death. In this case, dh was negative and likelihood 416: was wrong (infinity). We still send an "Error" but patch by 417: assuming that the date of death was just one stepm after the 418: interview. 419: (Repository): Because some people have very long ID (first column) 420: we changed int to long in num[] and we added a new lvector for 421: memory allocation. But we also truncated to 8 characters (left 422: truncation) 423: (Repository): No more line truncation errors. 424: 425: Revision 1.84 2003/06/13 21:44:43 brouard 426: * imach.c (Repository): Replace "freqsummary" at a correct 427: place. It differs from routine "prevalence" which may be called 428: many times. Probs is memory consuming and must be used with 429: parcimony. 430: Version 0.95a3 (should output exactly the same maximization than 0.8a2) 431: 432: Revision 1.83 2003/06/10 13:39:11 lievre 433: *** empty log message *** 434: 435: Revision 1.82 2003/06/05 15:57:20 brouard 436: Add log in imach.c and fullversion number is now printed. 437: 438: */ 439: /* 440: Interpolated Markov Chain 441: 442: Short summary of the programme: 443: 444: This program computes Healthy Life Expectancies from 445: cross-longitudinal data. Cross-longitudinal data consist in: -1- a 446: first survey ("cross") where individuals from different ages are 447: interviewed on their health status or degree of disability (in the 448: case of a health survey which is our main interest) -2- at least a 449: second wave of interviews ("longitudinal") which measure each change 450: (if any) in individual health status. Health expectancies are 451: computed from the time spent in each health state according to a 452: model. More health states you consider, more time is necessary to reach the 453: Maximum Likelihood of the parameters involved in the model. The 454: simplest model is the multinomial logistic model where pij is the 455: probability to be observed in state j at the second wave 456: conditional to be observed in state i at the first wave. Therefore 457: the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where 458: 'age' is age and 'sex' is a covariate. If you want to have a more 459: complex model than "constant and age", you should modify the program 460: where the markup *Covariates have to be included here again* invites 461: you to do it. More covariates you add, slower the 462: convergence. 463: 464: The advantage of this computer programme, compared to a simple 465: multinomial logistic model, is clear when the delay between waves is not 466: identical for each individual. Also, if a individual missed an 467: intermediate interview, the information is lost, but taken into 468: account using an interpolation or extrapolation. 469: 470: hPijx is the probability to be observed in state i at age x+h 471: conditional to the observed state i at age x. The delay 'h' can be 472: split into an exact number (nh*stepm) of unobserved intermediate 473: states. This elementary transition (by month, quarter, 474: semester or year) is modelled as a multinomial logistic. The hPx 475: matrix is simply the matrix product of nh*stepm elementary matrices 476: and the contribution of each individual to the likelihood is simply 477: hPijx. 478: 479: Also this programme outputs the covariance matrix of the parameters but also 480: of the life expectancies. It also computes the period (stable) prevalence. 481: 482: Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr). 483: Institut national d'études démographiques, Paris. 484: This software have been partly granted by Euro-REVES, a concerted action 485: from the European Union. 486: It is copyrighted identically to a GNU software product, ie programme and 487: software can be distributed freely for non commercial use. Latest version 488: can be accessed at http://euroreves.ined.fr/imach . 489: 490: Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach 491: or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so 492: 493: **********************************************************************/ 494: /* 495: main 496: read parameterfile 497: read datafile 498: concatwav 499: freqsummary 500: if (mle >= 1) 501: mlikeli 502: print results files 503: if mle==1 504: computes hessian 505: read end of parameter file: agemin, agemax, bage, fage, estepm 506: begin-prev-date,... 507: open gnuplot file 508: open html file 509: period (stable) prevalence | pl_nom 1-1 2-2 etc by covariate 510: for age prevalim() | #****** V1=0 V2=1 V3=1 V4=0 ****** 511: | 65 1 0 2 1 3 1 4 0 0.96326 0.03674 512: freexexit2 possible for memory heap. 513: 514: h Pij x | pij_nom ficrestpij 515: # Cov Agex agex+h hpijx with i,j= 1-1 1-2 1-3 2-1 2-2 2-3 516: 1 85 85 1.00000 0.00000 0.00000 0.00000 1.00000 0.00000 517: 1 85 86 0.68299 0.22291 0.09410 0.71093 0.00000 0.28907 518: 519: 1 65 99 0.00364 0.00322 0.99314 0.00350 0.00310 0.99340 520: 1 65 100 0.00214 0.00204 0.99581 0.00206 0.00196 0.99597 521: variance of p one-step probabilities varprob | prob_nom ficresprob #One-step probabilities and stand. devi in () 522: Standard deviation of one-step probabilities | probcor_nom ficresprobcor #One-step probabilities and correlation matrix 523: Matrix of variance covariance of one-step probabilities | probcov_nom ficresprobcov #One-step probabilities and covariance matrix 524: 525: forecasting if prevfcast==1 prevforecast call prevalence() 526: health expectancies 527: Variance-covariance of DFLE 528: prevalence() 529: movingaverage() 530: varevsij() 531: if popbased==1 varevsij(,popbased) 532: total life expectancies 533: Variance of period (stable) prevalence 534: end 535: */ 536: 537: #define POWELL /* Instead of NLOPT */ 538: 539: #include <math.h> 540: #include <stdio.h> 541: #include <stdlib.h> 542: #include <string.h> 543: 544: #ifdef _WIN32 545: #include <io.h> 546: #include <windows.h> 547: #include <tchar.h> 548: #else 549: #include <unistd.h> 550: #endif 551: 552: #include <limits.h> 553: #include <sys/types.h> 554: 555: #if defined(__GNUC__) 556: #include <sys/utsname.h> /* Doesn't work on Windows */ 557: #endif 558: 559: #include <sys/stat.h> 560: #include <errno.h> 561: /* extern int errno; */ 562: 563: /* #ifdef LINUX */ 564: /* #include <time.h> */ 565: /* #include "timeval.h" */ 566: /* #else */ 567: /* #include <sys/time.h> */ 568: /* #endif */ 569: 570: #include <time.h> 571: 572: #ifdef GSL 573: #include <gsl/gsl_errno.h> 574: #include <gsl/gsl_multimin.h> 575: #endif 576: 577: 578: #ifdef NLOPT 579: #include <nlopt.h> 580: typedef struct { 581: double (* function)(double [] ); 582: } myfunc_data ; 583: #endif 584: 585: /* #include <libintl.h> */ 586: /* #define _(String) gettext (String) */ 587: 588: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */ 589: 590: #define GNUPLOTPROGRAM "gnuplot" 591: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/ 592: #define FILENAMELENGTH 132 593: 594: #define GLOCK_ERROR_NOPATH -1 /* empty path */ 595: #define GLOCK_ERROR_GETCWD -2 /* cannot get cwd */ 596: 597: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */ 598: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */ 599: 600: #define NINTERVMAX 8 601: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */ 602: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */ 603: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */ 604: #define codtabm(h,k) 1 & (h-1) >> (k-1) ; 605: #define MAXN 20000 606: #define YEARM 12. /**< Number of months per year */ 607: #define AGESUP 130 608: #define AGEBASE 40 609: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */ 610: #ifdef _WIN32 611: #define DIRSEPARATOR '\\' 612: #define CHARSEPARATOR "\\" 613: #define ODIRSEPARATOR '/' 614: #else 615: #define DIRSEPARATOR '/' 616: #define CHARSEPARATOR "/" 617: #define ODIRSEPARATOR '\\' 618: #endif 619: 620: /* $Id: imach.c,v 1.173 2015/01/03 12:06:26 brouard Exp $ */ 621: /* $State: Exp $ */ 622: 623: char version[]="Imach version 0.98p, December 2014,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015"; 624: char fullversion[]="$Revision: 1.173 $ $Date: 2015/01/03 12:06:26 $"; 625: char strstart[80]; 626: char optionfilext[10], optionfilefiname[FILENAMELENGTH]; 627: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings */ 628: int nvar=0, nforce=0; /* Number of variables, number of forces */ 629: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */ 630: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */ 631: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */ 632: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */ 633: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */ 634: int cptcovprodnoage=0; /**< Number of covariate products without age */ 635: int cptcoveff=0; /* Total number of covariates to vary for printing results */ 636: int cptcov=0; /* Working variable */ 637: int npar=NPARMAX; 638: int nlstate=2; /* Number of live states */ 639: int ndeath=1; /* Number of dead states */ 640: int ncovmodel=0, ncovcol=0; /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */ 641: int popbased=0; 642: 643: int *wav; /* Number of waves for this individuual 0 is possible */ 644: int maxwav=0; /* Maxim number of waves */ 645: int jmin=0, jmax=0; /* min, max spacing between 2 waves */ 646: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 647: int gipmx=0, gsw=0; /* Global variables on the number of contributions 648: to the likelihood and the sum of weights (done by funcone)*/ 649: int mle=1, weightopt=0; 650: int **mw; /* mw[mi][i] is number of the mi wave for this individual */ 651: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */ 652: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between 653: * wave mi and wave mi+1 is not an exact multiple of stepm. */ 654: int countcallfunc=0; /* Count the number of calls to func */ 655: double jmean=1; /* Mean space between 2 waves */ 656: double **matprod2(); /* test */ 657: double **oldm, **newm, **savm; /* Working pointers to matrices */ 658: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */ 659: /*FILE *fic ; */ /* Used in readdata only */ 660: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop; 661: FILE *ficlog, *ficrespow; 662: int globpr=0; /* Global variable for printing or not */ 663: double fretone; /* Only one call to likelihood */ 664: long ipmx=0; /* Number of contributions */ 665: double sw; /* Sum of weights */ 666: char filerespow[FILENAMELENGTH]; 667: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */ 668: FILE *ficresilk; 669: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor; 670: FILE *ficresprobmorprev; 671: FILE *fichtm, *fichtmcov; /* Html File */ 672: FILE *ficreseij; 673: char filerese[FILENAMELENGTH]; 674: FILE *ficresstdeij; 675: char fileresstde[FILENAMELENGTH]; 676: FILE *ficrescveij; 677: char filerescve[FILENAMELENGTH]; 678: FILE *ficresvij; 679: char fileresv[FILENAMELENGTH]; 680: FILE *ficresvpl; 681: char fileresvpl[FILENAMELENGTH]; 682: char title[MAXLINE]; 683: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH], filerespl[FILENAMELENGTH]; 684: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH]; 685: char tmpout[FILENAMELENGTH], tmpout2[FILENAMELENGTH]; 686: char command[FILENAMELENGTH]; 687: int outcmd=0; 688: 689: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH]; 690: 691: char filelog[FILENAMELENGTH]; /* Log file */ 692: char filerest[FILENAMELENGTH]; 693: char fileregp[FILENAMELENGTH]; 694: char popfile[FILENAMELENGTH]; 695: 696: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ; 697: 698: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */ 699: /* struct timezone tzp; */ 700: /* extern int gettimeofday(); */ 701: struct tm tml, *gmtime(), *localtime(); 702: 703: extern time_t time(); 704: 705: struct tm start_time, end_time, curr_time, last_time, forecast_time; 706: time_t rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */ 707: struct tm tm; 708: 709: char strcurr[80], strfor[80]; 710: 711: char *endptr; 712: long lval; 713: double dval; 714: 715: #define NR_END 1 716: #define FREE_ARG char* 717: #define FTOL 1.0e-10 718: 719: #define NRANSI 720: #define ITMAX 200 721: 722: #define TOL 2.0e-4 723: 724: #define CGOLD 0.3819660 725: #define ZEPS 1.0e-10 726: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 727: 728: #define GOLD 1.618034 729: #define GLIMIT 100.0 730: #define TINY 1.0e-20 731: 732: static double maxarg1,maxarg2; 733: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2)) 734: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2)) 735: 736: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a)) 737: #define rint(a) floor(a+0.5) 738: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */ 739: /* #define mytinydouble 1.0e-16 */ 740: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */ 741: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */ 742: /* static double dsqrarg; */ 743: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */ 744: static double sqrarg; 745: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg) 746: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 747: int agegomp= AGEGOMP; 748: 749: int imx; 750: int stepm=1; 751: /* Stepm, step in month: minimum step interpolation*/ 752: 753: int estepm; 754: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/ 755: 756: int m,nb; 757: long *num; 758: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens; 759: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint; 760: double **pmmij, ***probs; 761: double *ageexmed,*agecens; 762: double dateintmean=0; 763: 764: double *weight; 765: int **s; /* Status */ 766: double *agedc; 767: double **covar; /**< covar[j,i], value of jth covariate for individual i, 768: * covar=matrix(0,NCOVMAX,1,n); 769: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; */ 770: double idx; 771: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */ 772: int *Ndum; /** Freq of modality (tricode */ 773: int **codtab; /**< codtab=imatrix(1,100,1,10); */ 774: int **Tvard, *Tprod, cptcovprod, *Tvaraff; 775: double *lsurv, *lpop, *tpop; 776: 777: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */ 778: double ftolhess; /**< Tolerance for computing hessian */ 779: 780: /**************** split *************************/ 781: static int split( char *path, char *dirc, char *name, char *ext, char *finame ) 782: { 783: /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc) 784: the name of the file (name), its extension only (ext) and its first part of the name (finame) 785: */ 786: char *ss; /* pointer */ 787: int l1, l2; /* length counters */ 788: 789: l1 = strlen(path ); /* length of path */ 790: if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH ); 791: ss= strrchr( path, DIRSEPARATOR ); /* find last / */ 792: if ( ss == NULL ) { /* no directory, so determine current directory */ 793: strcpy( name, path ); /* we got the fullname name because no directory */ 794: /*if(strrchr(path, ODIRSEPARATOR )==NULL) 795: printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/ 796: /* get current working directory */ 797: /* extern char* getcwd ( char *buf , int len);*/ 798: if ( getcwd( dirc, FILENAME_MAX ) == NULL ) { 799: return( GLOCK_ERROR_GETCWD ); 800: } 801: /* got dirc from getcwd*/ 802: printf(" DIRC = %s \n",dirc); 803: } else { /* strip direcotry from path */ 804: ss++; /* after this, the filename */ 805: l2 = strlen( ss ); /* length of filename */ 806: if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH ); 807: strcpy( name, ss ); /* save file name */ 808: strncpy( dirc, path, l1 - l2 ); /* now the directory */ 809: dirc[l1-l2] = 0; /* add zero */ 810: printf(" DIRC2 = %s \n",dirc); 811: } 812: /* We add a separator at the end of dirc if not exists */ 813: l1 = strlen( dirc ); /* length of directory */ 814: if( dirc[l1-1] != DIRSEPARATOR ){ 815: dirc[l1] = DIRSEPARATOR; 816: dirc[l1+1] = 0; 817: printf(" DIRC3 = %s \n",dirc); 818: } 819: ss = strrchr( name, '.' ); /* find last / */ 820: if (ss >0){ 821: ss++; 822: strcpy(ext,ss); /* save extension */ 823: l1= strlen( name); 824: l2= strlen(ss)+1; 825: strncpy( finame, name, l1-l2); 826: finame[l1-l2]= 0; 827: } 828: 829: return( 0 ); /* we're done */ 830: } 831: 832: 833: /******************************************/ 834: 835: void replace_back_to_slash(char *s, char*t) 836: { 837: int i; 838: int lg=0; 839: i=0; 840: lg=strlen(t); 841: for(i=0; i<= lg; i++) { 842: (s[i] = t[i]); 843: if (t[i]== '\\') s[i]='/'; 844: } 845: } 846: 847: char *trimbb(char *out, char *in) 848: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */ 849: char *s; 850: s=out; 851: while (*in != '\0'){ 852: while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/ 853: in++; 854: } 855: *out++ = *in++; 856: } 857: *out='\0'; 858: return s; 859: } 860: 861: char *cutl(char *blocc, char *alocc, char *in, char occ) 862: { 863: /* cuts string in into blocc and alocc where blocc ends before first occurence of char 'occ' 864: and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2') 865: gives blocc="abcdef2ghi" and alocc="j". 866: If occ is not found blocc is null and alocc is equal to in. Returns blocc 867: */ 868: char *s, *t; 869: t=in;s=in; 870: while ((*in != occ) && (*in != '\0')){ 871: *alocc++ = *in++; 872: } 873: if( *in == occ){ 874: *(alocc)='\0'; 875: s=++in; 876: } 877: 878: if (s == t) {/* occ not found */ 879: *(alocc-(in-s))='\0'; 880: in=s; 881: } 882: while ( *in != '\0'){ 883: *blocc++ = *in++; 884: } 885: 886: *blocc='\0'; 887: return t; 888: } 889: char *cutv(char *blocc, char *alocc, char *in, char occ) 890: { 891: /* cuts string in into blocc and alocc where blocc ends before last occurence of char 'occ' 892: and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2') 893: gives blocc="abcdef2ghi" and alocc="j". 894: If occ is not found blocc is null and alocc is equal to in. Returns alocc 895: */ 896: char *s, *t; 897: t=in;s=in; 898: while (*in != '\0'){ 899: while( *in == occ){ 900: *blocc++ = *in++; 901: s=in; 902: } 903: *blocc++ = *in++; 904: } 905: if (s == t) /* occ not found */ 906: *(blocc-(in-s))='\0'; 907: else 908: *(blocc-(in-s)-1)='\0'; 909: in=s; 910: while ( *in != '\0'){ 911: *alocc++ = *in++; 912: } 913: 914: *alocc='\0'; 915: return s; 916: } 917: 918: int nbocc(char *s, char occ) 919: { 920: int i,j=0; 921: int lg=20; 922: i=0; 923: lg=strlen(s); 924: for(i=0; i<= lg; i++) { 925: if (s[i] == occ ) j++; 926: } 927: return j; 928: } 929: 930: /* void cutv(char *u,char *v, char*t, char occ) */ 931: /* { */ 932: /* /\* cuts string t into u and v where u ends before last occurence of char 'occ' */ 933: /* and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */ 934: /* gives u="abcdef2ghi" and v="j" *\/ */ 935: /* int i,lg,j,p=0; */ 936: /* i=0; */ 937: /* lg=strlen(t); */ 938: /* for(j=0; j<=lg-1; j++) { */ 939: /* if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */ 940: /* } */ 941: 942: /* for(j=0; j<p; j++) { */ 943: /* (u[j] = t[j]); */ 944: /* } */ 945: /* u[p]='\0'; */ 946: 947: /* for(j=0; j<= lg; j++) { */ 948: /* if (j>=(p+1))(v[j-p-1] = t[j]); */ 949: /* } */ 950: /* } */ 951: 952: #ifdef _WIN32 953: char * strsep(char **pp, const char *delim) 954: { 955: char *p, *q; 956: 957: if ((p = *pp) == NULL) 958: return 0; 959: if ((q = strpbrk (p, delim)) != NULL) 960: { 961: *pp = q + 1; 962: *q = '\0'; 963: } 964: else 965: *pp = 0; 966: return p; 967: } 968: #endif 969: 970: /********************** nrerror ********************/ 971: 972: void nrerror(char error_text[]) 973: { 974: fprintf(stderr,"ERREUR ...\n"); 975: fprintf(stderr,"%s\n",error_text); 976: exit(EXIT_FAILURE); 977: } 978: /*********************** vector *******************/ 979: double *vector(int nl, int nh) 980: { 981: double *v; 982: v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double))); 983: if (!v) nrerror("allocation failure in vector"); 984: return v-nl+NR_END; 985: } 986: 987: /************************ free vector ******************/ 988: void free_vector(double*v, int nl, int nh) 989: { 990: free((FREE_ARG)(v+nl-NR_END)); 991: } 992: 993: /************************ivector *******************************/ 994: int *ivector(long nl,long nh) 995: { 996: int *v; 997: v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int))); 998: if (!v) nrerror("allocation failure in ivector"); 999: return v-nl+NR_END; 1000: } 1001: 1002: /******************free ivector **************************/ 1003: void free_ivector(int *v, long nl, long nh) 1004: { 1005: free((FREE_ARG)(v+nl-NR_END)); 1006: } 1007: 1008: /************************lvector *******************************/ 1009: long *lvector(long nl,long nh) 1010: { 1011: long *v; 1012: v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long))); 1013: if (!v) nrerror("allocation failure in ivector"); 1014: return v-nl+NR_END; 1015: } 1016: 1017: /******************free lvector **************************/ 1018: void free_lvector(long *v, long nl, long nh) 1019: { 1020: free((FREE_ARG)(v+nl-NR_END)); 1021: } 1022: 1023: /******************* imatrix *******************************/ 1024: int **imatrix(long nrl, long nrh, long ncl, long nch) 1025: /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 1026: { 1027: long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 1028: int **m; 1029: 1030: /* allocate pointers to rows */ 1031: m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 1032: if (!m) nrerror("allocation failure 1 in matrix()"); 1033: m += NR_END; 1034: m -= nrl; 1035: 1036: 1037: /* allocate rows and set pointers to them */ 1038: m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 1039: if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 1040: m[nrl] += NR_END; 1041: m[nrl] -= ncl; 1042: 1043: for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 1044: 1045: /* return pointer to array of pointers to rows */ 1046: return m; 1047: } 1048: 1049: /****************** free_imatrix *************************/ 1050: void free_imatrix(m,nrl,nrh,ncl,nch) 1051: int **m; 1052: long nch,ncl,nrh,nrl; 1053: /* free an int matrix allocated by imatrix() */ 1054: { 1055: free((FREE_ARG) (m[nrl]+ncl-NR_END)); 1056: free((FREE_ARG) (m+nrl-NR_END)); 1057: } 1058: 1059: /******************* matrix *******************************/ 1060: double **matrix(long nrl, long nrh, long ncl, long nch) 1061: { 1062: long i, nrow=nrh-nrl+1, ncol=nch-ncl+1; 1063: double **m; 1064: 1065: m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*))); 1066: if (!m) nrerror("allocation failure 1 in matrix()"); 1067: m += NR_END; 1068: m -= nrl; 1069: 1070: m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double))); 1071: if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 1072: m[nrl] += NR_END; 1073: m[nrl] -= ncl; 1074: 1075: for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol; 1076: return m; 1077: /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0]) 1078: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress 1079: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized. 1080: */ 1081: } 1082: 1083: /*************************free matrix ************************/ 1084: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch) 1085: { 1086: free((FREE_ARG)(m[nrl]+ncl-NR_END)); 1087: free((FREE_ARG)(m+nrl-NR_END)); 1088: } 1089: 1090: /******************* ma3x *******************************/ 1091: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh) 1092: { 1093: long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+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: 1108: m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double))); 1109: if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()"); 1110: m[nrl][ncl] += NR_END; 1111: m[nrl][ncl] -= nll; 1112: for (j=ncl+1; j<=nch; j++) 1113: m[nrl][j]=m[nrl][j-1]+nlay; 1114: 1115: for (i=nrl+1; i<=nrh; i++) { 1116: m[i][ncl]=m[i-1l][ncl]+ncol*nlay; 1117: for (j=ncl+1; j<=nch; j++) 1118: m[i][j]=m[i][j-1]+nlay; 1119: } 1120: return m; 1121: /* gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1]) 1122: &(m[i][j][k]) <=> *((*(m+i) + j)+k) 1123: */ 1124: } 1125: 1126: /*************************free ma3x ************************/ 1127: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh) 1128: { 1129: free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END)); 1130: free((FREE_ARG)(m[nrl]+ncl-NR_END)); 1131: free((FREE_ARG)(m+nrl-NR_END)); 1132: } 1133: 1134: /*************** function subdirf ***********/ 1135: char *subdirf(char fileres[]) 1136: { 1137: /* Caution optionfilefiname is hidden */ 1138: strcpy(tmpout,optionfilefiname); 1139: strcat(tmpout,"/"); /* Add to the right */ 1140: strcat(tmpout,fileres); 1141: return tmpout; 1142: } 1143: 1144: /*************** function subdirf2 ***********/ 1145: char *subdirf2(char fileres[], char *preop) 1146: { 1147: 1148: /* Caution optionfilefiname is hidden */ 1149: strcpy(tmpout,optionfilefiname); 1150: strcat(tmpout,"/"); 1151: strcat(tmpout,preop); 1152: strcat(tmpout,fileres); 1153: return tmpout; 1154: } 1155: 1156: /*************** function subdirf3 ***********/ 1157: char *subdirf3(char fileres[], char *preop, char *preop2) 1158: { 1159: 1160: /* Caution optionfilefiname is hidden */ 1161: strcpy(tmpout,optionfilefiname); 1162: strcat(tmpout,"/"); 1163: strcat(tmpout,preop); 1164: strcat(tmpout,preop2); 1165: strcat(tmpout,fileres); 1166: return tmpout; 1167: } 1168: 1169: char *asc_diff_time(long time_sec, char ascdiff[]) 1170: { 1171: long sec_left, days, hours, minutes; 1172: days = (time_sec) / (60*60*24); 1173: sec_left = (time_sec) % (60*60*24); 1174: hours = (sec_left) / (60*60) ; 1175: sec_left = (sec_left) %(60*60); 1176: minutes = (sec_left) /60; 1177: sec_left = (sec_left) % (60); 1178: sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left); 1179: return ascdiff; 1180: } 1181: 1182: /***************** f1dim *************************/ 1183: extern int ncom; 1184: extern double *pcom,*xicom; 1185: extern double (*nrfunc)(double []); 1186: 1187: double f1dim(double x) 1188: { 1189: int j; 1190: double f; 1191: double *xt; 1192: 1193: xt=vector(1,ncom); 1194: for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 1195: f=(*nrfunc)(xt); 1196: free_vector(xt,1,ncom); 1197: return f; 1198: } 1199: 1200: /*****************brent *************************/ 1201: double brent(double ax, double bx, double cx, double (*f)(double), double tol, double *xmin) 1202: { 1203: int iter; 1204: double a,b,d,etemp; 1205: double fu=0,fv,fw,fx; 1206: double ftemp=0.; 1207: double p,q,r,tol1,tol2,u,v,w,x,xm; 1208: double e=0.0; 1209: 1210: a=(ax < cx ? ax : cx); 1211: b=(ax > cx ? ax : cx); 1212: x=w=v=bx; 1213: fw=fv=fx=(*f)(x); 1214: for (iter=1;iter<=ITMAX;iter++) { 1215: xm=0.5*(a+b); 1216: tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 1217: /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/ 1218: printf(".");fflush(stdout); 1219: fprintf(ficlog,".");fflush(ficlog); 1220: #ifdef DEBUGBRENT 1221: 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); 1222: 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); 1223: /* if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */ 1224: #endif 1225: if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 1226: *xmin=x; 1227: return fx; 1228: } 1229: ftemp=fu; 1230: if (fabs(e) > tol1) { 1231: r=(x-w)*(fx-fv); 1232: q=(x-v)*(fx-fw); 1233: p=(x-v)*q-(x-w)*r; 1234: q=2.0*(q-r); 1235: if (q > 0.0) p = -p; 1236: q=fabs(q); 1237: etemp=e; 1238: e=d; 1239: if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 1240: d=CGOLD*(e=(x >= xm ? a-x : b-x)); 1241: else { 1242: d=p/q; 1243: u=x+d; 1244: if (u-a < tol2 || b-u < tol2) 1245: d=SIGN(tol1,xm-x); 1246: } 1247: } else { 1248: d=CGOLD*(e=(x >= xm ? a-x : b-x)); 1249: } 1250: u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 1251: fu=(*f)(u); 1252: if (fu <= fx) { 1253: if (u >= x) a=x; else b=x; 1254: SHFT(v,w,x,u) 1255: SHFT(fv,fw,fx,fu) 1256: } else { 1257: if (u < x) a=u; else b=u; 1258: if (fu <= fw || w == x) { 1259: v=w; 1260: w=u; 1261: fv=fw; 1262: fw=fu; 1263: } else if (fu <= fv || v == x || v == w) { 1264: v=u; 1265: fv=fu; 1266: } 1267: } 1268: } 1269: nrerror("Too many iterations in brent"); 1270: *xmin=x; 1271: return fx; 1272: } 1273: 1274: /****************** mnbrak ***********************/ 1275: 1276: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 1277: double (*func)(double)) 1278: { 1279: double ulim,u,r,q, dum; 1280: double fu; 1281: 1282: *fa=(*func)(*ax); 1283: *fb=(*func)(*bx); 1284: if (*fb > *fa) { 1285: SHFT(dum,*ax,*bx,dum) 1286: SHFT(dum,*fb,*fa,dum) 1287: } 1288: *cx=(*bx)+GOLD*(*bx-*ax); 1289: *fc=(*func)(*cx); 1290: while (*fb > *fc) { /* Declining fa, fb, fc */ 1291: r=(*bx-*ax)*(*fb-*fc); 1292: q=(*bx-*cx)*(*fb-*fa); 1293: u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 1294: (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscisse of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */ 1295: ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscisse where function can be evaluated */ 1296: if ((*bx-u)*(u-*cx) > 0.0) { /* if u between b and c */ 1297: fu=(*func)(u); 1298: #ifdef DEBUG 1299: /* f(x)=A(x-u)**2+f(u) */ 1300: double A, fparabu; 1301: A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u); 1302: fparabu= *fa - A*(*ax-u)*(*ax-u); 1303: 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); 1304: 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); 1305: #endif 1306: } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */ 1307: fu=(*func)(u); 1308: if (fu < *fc) { 1309: SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 1310: SHFT(*fb,*fc,fu,(*func)(u)) 1311: } 1312: } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */ 1313: u=ulim; 1314: fu=(*func)(u); 1315: } else { 1316: u=(*cx)+GOLD*(*cx-*bx); 1317: fu=(*func)(u); 1318: } 1319: SHFT(*ax,*bx,*cx,u) 1320: SHFT(*fa,*fb,*fc,fu) 1321: } 1322: } 1323: 1324: /*************** linmin ************************/ 1325: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and 1326: resets p to where the function func(p) takes on a minimum along the direction xi from p , 1327: and replaces xi by the actual vector displacement that p was moved. Also returns as fret 1328: the value of func at the returned location p . This is actually all accomplished by calling the 1329: routines mnbrak and brent .*/ 1330: int ncom; 1331: double *pcom,*xicom; 1332: double (*nrfunc)(double []); 1333: 1334: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 1335: { 1336: double brent(double ax, double bx, double cx, 1337: double (*f)(double), double tol, double *xmin); 1338: double f1dim(double x); 1339: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 1340: double *fc, double (*func)(double)); 1341: int j; 1342: double xx,xmin,bx,ax; 1343: double fx,fb,fa; 1344: 1345: ncom=n; 1346: pcom=vector(1,n); 1347: xicom=vector(1,n); 1348: nrfunc=func; 1349: for (j=1;j<=n;j++) { 1350: pcom[j]=p[j]; 1351: xicom[j]=xi[j]; 1352: } 1353: ax=0.0; 1354: xx=1.0; 1355: mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Find a bracket a,x,b in direction n=xi ie xicom */ 1356: *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Find a minimum P+lambda n in that direction (lambdamin), with TOL between abscisses */ 1357: #ifdef DEBUG 1358: printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin); 1359: fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin); 1360: #endif 1361: for (j=1;j<=n;j++) { 1362: xi[j] *= xmin; 1363: p[j] += xi[j]; 1364: } 1365: free_vector(xicom,1,n); 1366: free_vector(pcom,1,n); 1367: } 1368: 1369: 1370: /*************** powell ************************/ 1371: /* 1372: Minimization of a function func of n variables. Input consists of an initial starting point 1373: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di- 1374: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value 1375: such that failure to decrease by more than this amount on one iteration signals doneness. On 1376: output, p is set to the best point found, xi is the then-current direction set, fret is the returned 1377: function value at p , and iter is the number of iterations taken. The routine linmin is used. 1378: */ 1379: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 1380: double (*func)(double [])) 1381: { 1382: void linmin(double p[], double xi[], int n, double *fret, 1383: double (*func)(double [])); 1384: int i,ibig,j; 1385: double del,t,*pt,*ptt,*xit; 1386: double fp,fptt; 1387: double *xits; 1388: int niterf, itmp; 1389: 1390: pt=vector(1,n); 1391: ptt=vector(1,n); 1392: xit=vector(1,n); 1393: xits=vector(1,n); 1394: *fret=(*func)(p); 1395: for (j=1;j<=n;j++) pt[j]=p[j]; 1396: rcurr_time = time(NULL); 1397: for (*iter=1;;++(*iter)) { 1398: fp=(*fret); 1399: ibig=0; 1400: del=0.0; 1401: rlast_time=rcurr_time; 1402: /* (void) gettimeofday(&curr_time,&tzp); */ 1403: rcurr_time = time(NULL); 1404: curr_time = *localtime(&rcurr_time); 1405: printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout); 1406: fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog); 1407: /* fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */ 1408: for (i=1;i<=n;i++) { 1409: printf(" %d %.12f",i, p[i]); 1410: fprintf(ficlog," %d %.12lf",i, p[i]); 1411: fprintf(ficrespow," %.12lf", p[i]); 1412: } 1413: printf("\n"); 1414: fprintf(ficlog,"\n"); 1415: fprintf(ficrespow,"\n");fflush(ficrespow); 1416: if(*iter <=3){ 1417: tml = *localtime(&rcurr_time); 1418: strcpy(strcurr,asctime(&tml)); 1419: rforecast_time=rcurr_time; 1420: itmp = strlen(strcurr); 1421: if(strcurr[itmp-1]=='\n') /* Windows outputs with a new line */ 1422: strcurr[itmp-1]='\0'; 1423: printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time); 1424: fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time); 1425: for(niterf=10;niterf<=30;niterf+=10){ 1426: rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time); 1427: forecast_time = *localtime(&rforecast_time); 1428: strcpy(strfor,asctime(&forecast_time)); 1429: itmp = strlen(strfor); 1430: if(strfor[itmp-1]=='\n') 1431: strfor[itmp-1]='\0'; 1432: 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); 1433: 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); 1434: } 1435: } 1436: for (i=1;i<=n;i++) { 1437: for (j=1;j<=n;j++) xit[j]=xi[j][i]; 1438: fptt=(*fret); 1439: #ifdef DEBUG 1440: printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret); 1441: fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret); 1442: #endif 1443: printf("%d",i);fflush(stdout); 1444: fprintf(ficlog,"%d",i);fflush(ficlog); 1445: linmin(p,xit,n,fret,func); 1446: if (fabs(fptt-(*fret)) > del) { 1447: del=fabs(fptt-(*fret)); 1448: ibig=i; 1449: } 1450: #ifdef DEBUG 1451: printf("%d %.12e",i,(*fret)); 1452: fprintf(ficlog,"%d %.12e",i,(*fret)); 1453: for (j=1;j<=n;j++) { 1454: xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5); 1455: printf(" x(%d)=%.12e",j,xit[j]); 1456: fprintf(ficlog," x(%d)=%.12e",j,xit[j]); 1457: } 1458: for(j=1;j<=n;j++) { 1459: printf(" p(%d)=%.12e",j,p[j]); 1460: fprintf(ficlog," p(%d)=%.12e",j,p[j]); 1461: } 1462: printf("\n"); 1463: fprintf(ficlog,"\n"); 1464: #endif 1465: } /* end i */ 1466: if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { 1467: #ifdef DEBUG 1468: int k[2],l; 1469: k[0]=1; 1470: k[1]=-1; 1471: printf("Max: %.12e",(*func)(p)); 1472: fprintf(ficlog,"Max: %.12e",(*func)(p)); 1473: for (j=1;j<=n;j++) { 1474: printf(" %.12e",p[j]); 1475: fprintf(ficlog," %.12e",p[j]); 1476: } 1477: printf("\n"); 1478: fprintf(ficlog,"\n"); 1479: for(l=0;l<=1;l++) { 1480: for (j=1;j<=n;j++) { 1481: ptt[j]=p[j]+(p[j]-pt[j])*k[l]; 1482: printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]); 1483: fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]); 1484: } 1485: printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p))); 1486: fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p))); 1487: } 1488: #endif 1489: 1490: 1491: free_vector(xit,1,n); 1492: free_vector(xits,1,n); 1493: free_vector(ptt,1,n); 1494: free_vector(pt,1,n); 1495: return; 1496: } 1497: if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 1498: for (j=1;j<=n;j++) { /* Computes an extrapolated point */ 1499: ptt[j]=2.0*p[j]-pt[j]; 1500: xit[j]=p[j]-pt[j]; 1501: pt[j]=p[j]; 1502: } 1503: fptt=(*func)(ptt); 1504: if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */ 1505: /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */ 1506: /* From x1 (P0) distance of x2 is at h and x3 is 2h */ 1507: /* Let f"(x2) be the 2nd derivative equal everywhere. */ 1508: /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */ 1509: /* will reach at f3 = fm + h^2/2 f"m ; f" = (f1 -2f2 +f3 ) / h**2 */ 1510: /* f1-f3 = delta(2h) = 2 h**2 f'' = 2(f1- 2f2 +f3) */ 1511: /* Thus we compare delta(2h) with observed f1-f3 */ 1512: /* or best gain on one ancient line 'del' with total */ 1513: /* gain f1-f2 = f1 - f2 - 'del' with del */ 1514: /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */ 1515: 1516: t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del); 1517: t= t- del*SQR(fp-fptt); 1518: printf("t1= %.12lf, t2= %.12lf, t=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t); 1519: fprintf(ficlog,"t1= %.12lf, t2= %.12lf, t=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t); 1520: #ifdef DEBUG 1521: printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt), 1522: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt)); 1523: fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt), 1524: (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt)); 1525: 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); 1526: 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); 1527: #endif 1528: if (t < 0.0) { /* Then we use it for last direction */ 1529: linmin(p,xit,n,fret,func); /* computes mean on the extrapolated direction.*/ 1530: for (j=1;j<=n;j++) { 1531: xi[j][ibig]=xi[j][n]; /* Replace the direction with biggest decrease by n */ 1532: xi[j][n]=xit[j]; /* and nth direction by the extrapolated */ 1533: } 1534: printf("Gaining to use average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig); 1535: fprintf(ficlog,"Gaining to use average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig); 1536: 1537: #ifdef DEBUG 1538: printf("Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig); 1539: fprintf(ficlog,"Direction changed last moved %d in place of ibig=%d, new last is the average:\n",n,ibig); 1540: for(j=1;j<=n;j++){ 1541: printf(" %.12e",xit[j]); 1542: fprintf(ficlog," %.12e",xit[j]); 1543: } 1544: printf("\n"); 1545: fprintf(ficlog,"\n"); 1546: #endif 1547: } /* end of t negative */ 1548: } /* end if (fptt < fp) */ 1549: } 1550: } 1551: 1552: /**** Prevalence limit (stable or period prevalence) ****************/ 1553: 1554: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij) 1555: { 1556: /* Computes the prevalence limit in each live state at age x by left multiplying the unit 1557: matrix by transitions matrix until convergence is reached */ 1558: 1559: int i, ii,j,k; 1560: double min, max, maxmin, maxmax,sumnew=0.; 1561: /* double **matprod2(); */ /* test */ 1562: double **out, cov[NCOVMAX+1], **pmij(); 1563: double **newm; 1564: double agefin, delaymax=50 ; /* Max number of years to converge */ 1565: 1566: for (ii=1;ii<=nlstate+ndeath;ii++) 1567: for (j=1;j<=nlstate+ndeath;j++){ 1568: oldm[ii][j]=(ii==j ? 1.0 : 0.0); 1569: } 1570: 1571: cov[1]=1.; 1572: 1573: /* Even if hstepm = 1, at least one multiplication by the unit matrix */ 1574: for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){ 1575: newm=savm; 1576: /* Covariates have to be included here again */ 1577: cov[2]=agefin; 1578: 1579: for (k=1; k<=cptcovn;k++) { 1580: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; 1581: /*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]]);*/ 1582: } 1583: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */ 1584: /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */ 1585: /* cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]] * nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]]; */ 1586: 1587: /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/ 1588: /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/ 1589: /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/ 1590: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */ 1591: /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */ 1592: out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */ 1593: 1594: savm=oldm; 1595: oldm=newm; 1596: maxmax=0.; 1597: for(j=1;j<=nlstate;j++){ 1598: min=1.; 1599: max=0.; 1600: for(i=1; i<=nlstate; i++) { 1601: sumnew=0; 1602: for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k]; 1603: prlim[i][j]= newm[i][j]/(1-sumnew); 1604: /*printf(" prevalim i=%d, j=%d, prmlim[%d][%d]=%f, agefin=%d \n", i, j, i, j, prlim[i][j],(int)agefin);*/ 1605: max=FMAX(max,prlim[i][j]); 1606: min=FMIN(min,prlim[i][j]); 1607: } 1608: maxmin=max-min; 1609: maxmax=FMAX(maxmax,maxmin); 1610: } /* j loop */ 1611: if(maxmax < ftolpl){ 1612: return prlim; 1613: } 1614: } /* age loop */ 1615: return prlim; /* should not reach here */ 1616: } 1617: 1618: /*************** transition probabilities ***************/ 1619: 1620: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate ) 1621: { 1622: /* According to parameters values stored in x and the covariate's values stored in cov, 1623: computes the probability to be observed in state j being in state i by appying the 1624: model to the ncovmodel covariates (including constant and age). 1625: lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc] 1626: and, according on how parameters are entered, the position of the coefficient xij(nc) of the 1627: ncth covariate in the global vector x is given by the formula: 1628: j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel 1629: j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel 1630: Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation, 1631: sums on j different of i to get 1-pii/pii, deduces pii, and then all pij. 1632: Outputs ps[i][j] the probability to be observed in j being in j according to 1633: the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij] 1634: */ 1635: double s1, lnpijopii; 1636: /*double t34;*/ 1637: int i,j, nc, ii, jj; 1638: 1639: for(i=1; i<= nlstate; i++){ 1640: for(j=1; j<i;j++){ 1641: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){ 1642: /*lnpijopii += param[i][j][nc]*cov[nc];*/ 1643: lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc]; 1644: /* printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */ 1645: } 1646: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */ 1647: /* printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */ 1648: } 1649: for(j=i+1; j<=nlstate+ndeath;j++){ 1650: for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){ 1651: /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/ 1652: lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc]; 1653: /* printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */ 1654: } 1655: ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */ 1656: } 1657: } 1658: 1659: for(i=1; i<= nlstate; i++){ 1660: s1=0; 1661: for(j=1; j<i; j++){ 1662: s1+=exp(ps[i][j]); /* In fact sums pij/pii */ 1663: /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */ 1664: } 1665: for(j=i+1; j<=nlstate+ndeath; j++){ 1666: s1+=exp(ps[i][j]); /* In fact sums pij/pii */ 1667: /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */ 1668: } 1669: /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */ 1670: ps[i][i]=1./(s1+1.); 1671: /* Computing other pijs */ 1672: for(j=1; j<i; j++) 1673: ps[i][j]= exp(ps[i][j])*ps[i][i]; 1674: for(j=i+1; j<=nlstate+ndeath; j++) 1675: ps[i][j]= exp(ps[i][j])*ps[i][i]; 1676: /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */ 1677: } /* end i */ 1678: 1679: for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){ 1680: for(jj=1; jj<= nlstate+ndeath; jj++){ 1681: ps[ii][jj]=0; 1682: ps[ii][ii]=1; 1683: } 1684: } 1685: 1686: 1687: /* for(ii=1; ii<= nlstate+ndeath; ii++){ */ 1688: /* for(jj=1; jj<= nlstate+ndeath; jj++){ */ 1689: /* printf(" pmij ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */ 1690: /* } */ 1691: /* printf("\n "); */ 1692: /* } */ 1693: /* printf("\n ");printf("%lf ",cov[2]);*/ 1694: /* 1695: for(i=1; i<= npar; i++) printf("%f ",x[i]); 1696: goto end;*/ 1697: return ps; 1698: } 1699: 1700: /**************** Product of 2 matrices ******************/ 1701: 1702: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b) 1703: { 1704: /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times 1705: b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */ 1706: /* in, b, out are matrice of pointers which should have been initialized 1707: before: only the contents of out is modified. The function returns 1708: a pointer to pointers identical to out */ 1709: int i, j, k; 1710: for(i=nrl; i<= nrh; i++) 1711: for(k=ncolol; k<=ncoloh; k++){ 1712: out[i][k]=0.; 1713: for(j=ncl; j<=nch; j++) 1714: out[i][k] +=in[i][j]*b[j][k]; 1715: } 1716: return out; 1717: } 1718: 1719: 1720: /************* Higher Matrix Product ***************/ 1721: 1722: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij ) 1723: { 1724: /* Computes the transition matrix starting at age 'age' over 1725: 'nhstepm*hstepm*stepm' months (i.e. until 1726: age (in years) age+nhstepm*hstepm*stepm/12) by multiplying 1727: nhstepm*hstepm matrices. 1728: Output is stored in matrix po[i][j][h] for h every 'hstepm' step 1729: (typically every 2 years instead of every month which is too big 1730: for the memory). 1731: Model is determined by parameters x and covariates have to be 1732: included manually here. 1733: 1734: */ 1735: 1736: int i, j, d, h, k; 1737: double **out, cov[NCOVMAX+1]; 1738: double **newm; 1739: 1740: /* Hstepm could be zero and should return the unit matrix */ 1741: for (i=1;i<=nlstate+ndeath;i++) 1742: for (j=1;j<=nlstate+ndeath;j++){ 1743: oldm[i][j]=(i==j ? 1.0 : 0.0); 1744: po[i][j][0]=(i==j ? 1.0 : 0.0); 1745: } 1746: /* Even if hstepm = 1, at least one multiplication by the unit matrix */ 1747: for(h=1; h <=nhstepm; h++){ 1748: for(d=1; d <=hstepm; d++){ 1749: newm=savm; 1750: /* Covariates have to be included here again */ 1751: cov[1]=1.; 1752: cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM; 1753: for (k=1; k<=cptcovn;k++) 1754: cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; 1755: for (k=1; k<=cptcovage;k++) 1756: cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; 1757: for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */ 1758: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]]; 1759: 1760: 1761: /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/ 1762: /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/ 1763: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 1764: pmij(pmmij,cov,ncovmodel,x,nlstate)); 1765: savm=oldm; 1766: oldm=newm; 1767: } 1768: for(i=1; i<=nlstate+ndeath; i++) 1769: for(j=1;j<=nlstate+ndeath;j++) { 1770: po[i][j][h]=newm[i][j]; 1771: /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/ 1772: } 1773: /*printf("h=%d ",h);*/ 1774: } /* end h */ 1775: /* printf("\n H=%d \n",h); */ 1776: return po; 1777: } 1778: 1779: #ifdef NLOPT 1780: double myfunc(unsigned n, const double *p1, double *grad, void *pd){ 1781: double fret; 1782: double *xt; 1783: int j; 1784: myfunc_data *d2 = (myfunc_data *) pd; 1785: /* xt = (p1-1); */ 1786: xt=vector(1,n); 1787: for (j=1;j<=n;j++) xt[j]=p1[j-1]; /* xt[1]=p1[0] */ 1788: 1789: fret=(d2->function)(xt); /* p xt[1]@8 is fine */ 1790: /* fret=(*func)(xt); /\* p xt[1]@8 is fine *\/ */ 1791: printf("Function = %.12lf ",fret); 1792: for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 1793: printf("\n"); 1794: free_vector(xt,1,n); 1795: return fret; 1796: } 1797: #endif 1798: 1799: /*************** log-likelihood *************/ 1800: double func( double *x) 1801: { 1802: int i, ii, j, k, mi, d, kk; 1803: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1]; 1804: double **out; 1805: double sw; /* Sum of weights */ 1806: double lli; /* Individual log likelihood */ 1807: int s1, s2; 1808: double bbh, survp; 1809: long ipmx; 1810: /*extern weight */ 1811: /* We are differentiating ll according to initial status */ 1812: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/ 1813: /*for(i=1;i<imx;i++) 1814: printf(" %d\n",s[4][i]); 1815: */ 1816: 1817: ++countcallfunc; 1818: 1819: cov[1]=1.; 1820: 1821: for(k=1; k<=nlstate; k++) ll[k]=0.; 1822: 1823: if(mle==1){ 1824: for (i=1,ipmx=0, sw=0.; i<=imx; i++){ 1825: /* Computes the values of the ncovmodel covariates of the model 1826: depending if the covariates are fixed or variying (age dependent) and stores them in cov[] 1827: Then computes with function pmij which return a matrix p[i][j] giving the elementary probability 1828: to be observed in j being in i according to the model. 1829: */ 1830: for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */ 1831: cov[2+k]=covar[Tvar[k]][i]; 1832: } 1833: /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 1834: is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 1835: has been calculated etc */ 1836: for(mi=1; mi<= wav[i]-1; mi++){ 1837: for (ii=1;ii<=nlstate+ndeath;ii++) 1838: for (j=1;j<=nlstate+ndeath;j++){ 1839: oldm[ii][j]=(ii==j ? 1.0 : 0.0); 1840: savm[ii][j]=(ii==j ? 1.0 : 0.0); 1841: } 1842: for(d=0; d<dh[mi][i]; d++){ 1843: newm=savm; 1844: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM; 1845: for (kk=1; kk<=cptcovage;kk++) { 1846: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; /* Tage[kk] gives the data-covariate associated with age */ 1847: } 1848: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, 1849: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); 1850: savm=oldm; 1851: oldm=newm; 1852: } /* end mult */ 1853: 1854: /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */ 1855: /* But now since version 0.9 we anticipate for bias at large stepm. 1856: * If stepm is larger than one month (smallest stepm) and if the exact delay 1857: * (in months) between two waves is not a multiple of stepm, we rounded to 1858: * the nearest (and in case of equal distance, to the lowest) interval but now 1859: * we keep into memory the bias bh[mi][i] and also the previous matrix product 1860: * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the 1861: * probability in order to take into account the bias as a fraction of the way 1862: * from savm to out if bh is negative or even beyond if bh is positive. bh varies 1863: * -stepm/2 to stepm/2 . 1864: * For stepm=1 the results are the same as for previous versions of Imach. 1865: * For stepm > 1 the results are less biased than in previous versions. 1866: */ 1867: s1=s[mw[mi][i]][i]; 1868: s2=s[mw[mi+1][i]][i]; 1869: bbh=(double)bh[mi][i]/(double)stepm; 1870: /* bias bh is positive if real duration 1871: * is higher than the multiple of stepm and negative otherwise. 1872: */ 1873: /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/ 1874: if( s2 > nlstate){ 1875: /* i.e. if s2 is a death state and if the date of death is known 1876: then the contribution to the likelihood is the probability to 1877: die between last step unit time and current step unit time, 1878: which is also equal to probability to die before dh 1879: minus probability to die before dh-stepm . 1880: In version up to 0.92 likelihood was computed 1881: as if date of death was unknown. Death was treated as any other 1882: health state: the date of the interview describes the actual state 1883: and not the date of a change in health state. The former idea was 1884: to consider that at each interview the state was recorded 1885: (healthy, disable or death) and IMaCh was corrected; but when we 1886: introduced the exact date of death then we should have modified 1887: the contribution of an exact death to the likelihood. This new 1888: contribution is smaller and very dependent of the step unit 1889: stepm. It is no more the probability to die between last interview 1890: and month of death but the probability to survive from last 1891: interview up to one month before death multiplied by the 1892: probability to die within a month. Thanks to Chris 1893: Jackson for correcting this bug. Former versions increased 1894: mortality artificially. The bad side is that we add another loop 1895: which slows down the processing. The difference can be up to 10% 1896: lower mortality. 1897: */ 1898: lli=log(out[s1][s2] - savm[s1][s2]); 1899: 1900: 1901: } else if (s2==-2) { 1902: for (j=1,survp=0. ; j<=nlstate; j++) 1903: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; 1904: /*survp += out[s1][j]; */ 1905: lli= log(survp); 1906: } 1907: 1908: else if (s2==-4) { 1909: for (j=3,survp=0. ; j<=nlstate; j++) 1910: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; 1911: lli= log(survp); 1912: } 1913: 1914: else if (s2==-5) { 1915: for (j=1,survp=0. ; j<=2; j++) 1916: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; 1917: lli= log(survp); 1918: } 1919: 1920: else{ 1921: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */ 1922: /* 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 */ 1923: } 1924: /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/ 1925: /*if(lli ==000.0)*/ 1926: /*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); */ 1927: ipmx +=1; 1928: sw += weight[i]; 1929: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli; 1930: } /* end of wave */ 1931: } /* end of individual */ 1932: } else if(mle==2){ 1933: for (i=1,ipmx=0, sw=0.; i<=imx; i++){ 1934: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i]; 1935: for(mi=1; mi<= wav[i]-1; mi++){ 1936: for (ii=1;ii<=nlstate+ndeath;ii++) 1937: for (j=1;j<=nlstate+ndeath;j++){ 1938: oldm[ii][j]=(ii==j ? 1.0 : 0.0); 1939: savm[ii][j]=(ii==j ? 1.0 : 0.0); 1940: } 1941: for(d=0; d<=dh[mi][i]; d++){ 1942: newm=savm; 1943: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM; 1944: for (kk=1; kk<=cptcovage;kk++) { 1945: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; 1946: } 1947: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, 1948: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); 1949: savm=oldm; 1950: oldm=newm; 1951: } /* end mult */ 1952: 1953: s1=s[mw[mi][i]][i]; 1954: s2=s[mw[mi+1][i]][i]; 1955: bbh=(double)bh[mi][i]/(double)stepm; 1956: 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 */ 1957: ipmx +=1; 1958: sw += weight[i]; 1959: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli; 1960: } /* end of wave */ 1961: } /* end of individual */ 1962: } else if(mle==3){ /* exponential inter-extrapolation */ 1963: for (i=1,ipmx=0, sw=0.; i<=imx; i++){ 1964: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i]; 1965: for(mi=1; mi<= wav[i]-1; mi++){ 1966: for (ii=1;ii<=nlstate+ndeath;ii++) 1967: for (j=1;j<=nlstate+ndeath;j++){ 1968: oldm[ii][j]=(ii==j ? 1.0 : 0.0); 1969: savm[ii][j]=(ii==j ? 1.0 : 0.0); 1970: } 1971: for(d=0; d<dh[mi][i]; d++){ 1972: newm=savm; 1973: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM; 1974: for (kk=1; kk<=cptcovage;kk++) { 1975: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; 1976: } 1977: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, 1978: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); 1979: savm=oldm; 1980: oldm=newm; 1981: } /* end mult */ 1982: 1983: s1=s[mw[mi][i]][i]; 1984: s2=s[mw[mi+1][i]][i]; 1985: bbh=(double)bh[mi][i]/(double)stepm; 1986: 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 */ 1987: ipmx +=1; 1988: sw += weight[i]; 1989: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli; 1990: } /* end of wave */ 1991: } /* end of individual */ 1992: }else if (mle==4){ /* ml=4 no inter-extrapolation */ 1993: for (i=1,ipmx=0, sw=0.; i<=imx; i++){ 1994: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i]; 1995: for(mi=1; mi<= wav[i]-1; mi++){ 1996: for (ii=1;ii<=nlstate+ndeath;ii++) 1997: for (j=1;j<=nlstate+ndeath;j++){ 1998: oldm[ii][j]=(ii==j ? 1.0 : 0.0); 1999: savm[ii][j]=(ii==j ? 1.0 : 0.0); 2000: } 2001: for(d=0; d<dh[mi][i]; d++){ 2002: newm=savm; 2003: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM; 2004: for (kk=1; kk<=cptcovage;kk++) { 2005: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; 2006: } 2007: 2008: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, 2009: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); 2010: savm=oldm; 2011: oldm=newm; 2012: } /* end mult */ 2013: 2014: s1=s[mw[mi][i]][i]; 2015: s2=s[mw[mi+1][i]][i]; 2016: if( s2 > nlstate){ 2017: lli=log(out[s1][s2] - savm[s1][s2]); 2018: }else{ 2019: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */ 2020: } 2021: ipmx +=1; 2022: sw += weight[i]; 2023: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli; 2024: /* 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]); */ 2025: } /* end of wave */ 2026: } /* end of individual */ 2027: }else{ /* ml=5 no inter-extrapolation no jackson =0.8a */ 2028: for (i=1,ipmx=0, sw=0.; i<=imx; i++){ 2029: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i]; 2030: for(mi=1; mi<= wav[i]-1; mi++){ 2031: for (ii=1;ii<=nlstate+ndeath;ii++) 2032: for (j=1;j<=nlstate+ndeath;j++){ 2033: oldm[ii][j]=(ii==j ? 1.0 : 0.0); 2034: savm[ii][j]=(ii==j ? 1.0 : 0.0); 2035: } 2036: for(d=0; d<dh[mi][i]; d++){ 2037: newm=savm; 2038: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM; 2039: for (kk=1; kk<=cptcovage;kk++) { 2040: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; 2041: } 2042: 2043: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, 2044: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); 2045: savm=oldm; 2046: oldm=newm; 2047: } /* end mult */ 2048: 2049: s1=s[mw[mi][i]][i]; 2050: s2=s[mw[mi+1][i]][i]; 2051: lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */ 2052: ipmx +=1; 2053: sw += weight[i]; 2054: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli; 2055: /*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]);*/ 2056: } /* end of wave */ 2057: } /* end of individual */ 2058: } /* End of if */ 2059: for(k=1,l=0.; k<=nlstate; k++) l += ll[k]; 2060: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */ 2061: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */ 2062: return -l; 2063: } 2064: 2065: /*************** log-likelihood *************/ 2066: double funcone( double *x) 2067: { 2068: /* Same as likeli but slower because of a lot of printf and if */ 2069: int i, ii, j, k, mi, d, kk; 2070: double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1]; 2071: double **out; 2072: double lli; /* Individual log likelihood */ 2073: double llt; 2074: int s1, s2; 2075: double bbh, survp; 2076: /*extern weight */ 2077: /* We are differentiating ll according to initial status */ 2078: /* for (i=1;i<=npar;i++) printf("%f ", x[i]);*/ 2079: /*for(i=1;i<imx;i++) 2080: printf(" %d\n",s[4][i]); 2081: */ 2082: cov[1]=1.; 2083: 2084: for(k=1; k<=nlstate; k++) ll[k]=0.; 2085: 2086: for (i=1,ipmx=0, sw=0.; i<=imx; i++){ 2087: for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i]; 2088: for(mi=1; mi<= wav[i]-1; mi++){ 2089: for (ii=1;ii<=nlstate+ndeath;ii++) 2090: for (j=1;j<=nlstate+ndeath;j++){ 2091: oldm[ii][j]=(ii==j ? 1.0 : 0.0); 2092: savm[ii][j]=(ii==j ? 1.0 : 0.0); 2093: } 2094: for(d=0; d<dh[mi][i]; d++){ 2095: newm=savm; 2096: cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM; 2097: for (kk=1; kk<=cptcovage;kk++) { 2098: cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; 2099: } 2100: /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */ 2101: out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, 2102: 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); 2103: /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */ 2104: /* 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */ 2105: savm=oldm; 2106: oldm=newm; 2107: } /* end mult */ 2108: 2109: s1=s[mw[mi][i]][i]; 2110: s2=s[mw[mi+1][i]][i]; 2111: bbh=(double)bh[mi][i]/(double)stepm; 2112: /* bias is positive if real duration 2113: * is higher than the multiple of stepm and negative otherwise. 2114: */ 2115: if( s2 > nlstate && (mle <5) ){ /* Jackson */ 2116: lli=log(out[s1][s2] - savm[s1][s2]); 2117: } else if (s2==-2) { 2118: for (j=1,survp=0. ; j<=nlstate; j++) 2119: survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; 2120: lli= log(survp); 2121: }else if (mle==1){ 2122: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */ 2123: } else if(mle==2){ 2124: 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 */ 2125: } else if(mle==3){ /* exponential inter-extrapolation */ 2126: 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 */ 2127: } else if (mle==4){ /* mle=4 no inter-extrapolation */ 2128: lli=log(out[s1][s2]); /* Original formula */ 2129: } else{ /* mle=0 back to 1 */ 2130: lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */ 2131: /*lli=log(out[s1][s2]); */ /* Original formula */ 2132: } /* End of if */ 2133: ipmx +=1; 2134: sw += weight[i]; 2135: ll[s[mw[mi][i]][i]] += 2*weight[i]*lli; 2136: /*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]); */ 2137: if(globpr){ 2138: fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\ 2139: %11.6f %11.6f %11.6f ", \ 2140: num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i], 2141: 2*weight[i]*lli,out[s1][s2],savm[s1][s2]); 2142: for(k=1,llt=0.,l=0.; k<=nlstate; k++){ 2143: llt +=ll[k]*gipmx/gsw; 2144: fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw); 2145: } 2146: fprintf(ficresilk," %10.6f\n", -llt); 2147: } 2148: } /* end of wave */ 2149: } /* end of individual */ 2150: for(k=1,l=0.; k<=nlstate; k++) l += ll[k]; 2151: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */ 2152: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */ 2153: if(globpr==0){ /* First time we count the contributions and weights */ 2154: gipmx=ipmx; 2155: gsw=sw; 2156: } 2157: return -l; 2158: } 2159: 2160: 2161: /*************** function likelione ***********/ 2162: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double [])) 2163: { 2164: /* This routine should help understanding what is done with 2165: the selection of individuals/waves and 2166: to check the exact contribution to the likelihood. 2167: Plotting could be done. 2168: */ 2169: int k; 2170: 2171: if(*globpri !=0){ /* Just counts and sums, no printings */ 2172: strcpy(fileresilk,"ilk"); 2173: strcat(fileresilk,fileres); 2174: if((ficresilk=fopen(fileresilk,"w"))==NULL) { 2175: printf("Problem with resultfile: %s\n", fileresilk); 2176: fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk); 2177: } 2178: 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"); 2179: fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav "); 2180: /* i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */ 2181: for(k=1; k<=nlstate; k++) 2182: fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k); 2183: fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n"); 2184: } 2185: 2186: *fretone=(*funcone)(p); 2187: if(*globpri !=0){ 2188: fclose(ficresilk); 2189: fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk)); 2190: fflush(fichtm); 2191: } 2192: return; 2193: } 2194: 2195: 2196: /*********** Maximum Likelihood Estimation ***************/ 2197: 2198: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double [])) 2199: { 2200: int i,j, iter=0; 2201: double **xi; 2202: double fret; 2203: double fretone; /* Only one call to likelihood */ 2204: /* char filerespow[FILENAMELENGTH];*/ 2205: 2206: #ifdef NLOPT 2207: int creturn; 2208: nlopt_opt opt; 2209: /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */ 2210: double *lb; 2211: double minf; /* the minimum objective value, upon return */ 2212: double * p1; /* Shifted parameters from 0 instead of 1 */ 2213: myfunc_data dinst, *d = &dinst; 2214: #endif 2215: 2216: 2217: xi=matrix(1,npar,1,npar); 2218: for (i=1;i<=npar;i++) 2219: for (j=1;j<=npar;j++) 2220: xi[i][j]=(i==j ? 1.0 : 0.0); 2221: printf("Powell\n"); fprintf(ficlog,"Powell\n"); 2222: strcpy(filerespow,"pow"); 2223: strcat(filerespow,fileres); 2224: if((ficrespow=fopen(filerespow,"w"))==NULL) { 2225: printf("Problem with resultfile: %s\n", filerespow); 2226: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow); 2227: } 2228: fprintf(ficrespow,"# Powell\n# iter -2*LL"); 2229: for (i=1;i<=nlstate;i++) 2230: for(j=1;j<=nlstate+ndeath;j++) 2231: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j); 2232: fprintf(ficrespow,"\n"); 2233: #ifdef POWELL 2234: powell(p,xi,npar,ftol,&iter,&fret,func); 2235: #endif 2236: 2237: #ifdef NLOPT 2238: #ifdef NEWUOA 2239: opt = nlopt_create(NLOPT_LN_NEWUOA,npar); 2240: #else 2241: opt = nlopt_create(NLOPT_LN_BOBYQA,npar); 2242: #endif 2243: lb=vector(0,npar-1); 2244: for (i=0;i<npar;i++) lb[i]= -HUGE_VAL; 2245: nlopt_set_lower_bounds(opt, lb); 2246: nlopt_set_initial_step1(opt, 0.1); 2247: 2248: p1= (p+1); /* p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */ 2249: d->function = func; 2250: printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d)); 2251: nlopt_set_min_objective(opt, myfunc, d); 2252: nlopt_set_xtol_rel(opt, ftol); 2253: if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) { 2254: printf("nlopt failed! %d\n",creturn); 2255: } 2256: else { 2257: printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT); 2258: printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf); 2259: iter=1; /* not equal */ 2260: } 2261: nlopt_destroy(opt); 2262: #endif 2263: free_matrix(xi,1,npar,1,npar); 2264: fclose(ficrespow); 2265: printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p)); 2266: fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p)); 2267: fprintf(ficres,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p)); 2268: 2269: } 2270: 2271: /**** Computes Hessian and covariance matrix ***/ 2272: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double [])) 2273: { 2274: double **a,**y,*x,pd; 2275: double **hess; 2276: int i, j; 2277: int *indx; 2278: 2279: double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar); 2280: double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar); 2281: void lubksb(double **a, int npar, int *indx, double b[]) ; 2282: void ludcmp(double **a, int npar, int *indx, double *d) ; 2283: double gompertz(double p[]); 2284: hess=matrix(1,npar,1,npar); 2285: 2286: printf("\nCalculation of the hessian matrix. Wait...\n"); 2287: fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n"); 2288: for (i=1;i<=npar;i++){ 2289: printf("%d",i);fflush(stdout); 2290: fprintf(ficlog,"%d",i);fflush(ficlog); 2291: 2292: hess[i][i]=hessii(p,ftolhess,i,delti,func,npar); 2293: 2294: /* printf(" %f ",p[i]); 2295: printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/ 2296: } 2297: 2298: for (i=1;i<=npar;i++) { 2299: for (j=1;j<=npar;j++) { 2300: if (j>i) { 2301: printf(".%d%d",i,j);fflush(stdout); 2302: fprintf(ficlog,".%d%d",i,j);fflush(ficlog); 2303: hess[i][j]=hessij(p,delti,i,j,func,npar); 2304: 2305: hess[j][i]=hess[i][j]; 2306: /*printf(" %lf ",hess[i][j]);*/ 2307: } 2308: } 2309: } 2310: printf("\n"); 2311: fprintf(ficlog,"\n"); 2312: 2313: printf("\nInverting the hessian to get the covariance matrix. Wait...\n"); 2314: fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n"); 2315: 2316: a=matrix(1,npar,1,npar); 2317: y=matrix(1,npar,1,npar); 2318: x=vector(1,npar); 2319: indx=ivector(1,npar); 2320: for (i=1;i<=npar;i++) 2321: for (j=1;j<=npar;j++) a[i][j]=hess[i][j]; 2322: ludcmp(a,npar,indx,&pd); 2323: 2324: for (j=1;j<=npar;j++) { 2325: for (i=1;i<=npar;i++) x[i]=0; 2326: x[j]=1; 2327: lubksb(a,npar,indx,x); 2328: for (i=1;i<=npar;i++){ 2329: matcov[i][j]=x[i]; 2330: } 2331: } 2332: 2333: printf("\n#Hessian matrix#\n"); 2334: fprintf(ficlog,"\n#Hessian matrix#\n"); 2335: for (i=1;i<=npar;i++) { 2336: for (j=1;j<=npar;j++) { 2337: printf("%.3e ",hess[i][j]); 2338: fprintf(ficlog,"%.3e ",hess[i][j]); 2339: } 2340: printf("\n"); 2341: fprintf(ficlog,"\n"); 2342: } 2343: 2344: /* Recompute Inverse */ 2345: for (i=1;i<=npar;i++) 2346: for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; 2347: ludcmp(a,npar,indx,&pd); 2348: 2349: /* printf("\n#Hessian matrix recomputed#\n"); 2350: 2351: for (j=1;j<=npar;j++) { 2352: for (i=1;i<=npar;i++) x[i]=0; 2353: x[j]=1; 2354: lubksb(a,npar,indx,x); 2355: for (i=1;i<=npar;i++){ 2356: y[i][j]=x[i]; 2357: printf("%.3e ",y[i][j]); 2358: fprintf(ficlog,"%.3e ",y[i][j]); 2359: } 2360: printf("\n"); 2361: fprintf(ficlog,"\n"); 2362: } 2363: */ 2364: 2365: free_matrix(a,1,npar,1,npar); 2366: free_matrix(y,1,npar,1,npar); 2367: free_vector(x,1,npar); 2368: free_ivector(indx,1,npar); 2369: free_matrix(hess,1,npar,1,npar); 2370: 2371: 2372: } 2373: 2374: /*************** hessian matrix ****************/ 2375: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar) 2376: { 2377: int i; 2378: int l=1, lmax=20; 2379: double k1,k2; 2380: double p2[MAXPARM+1]; /* identical to x */ 2381: double res; 2382: double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; 2383: double fx; 2384: int k=0,kmax=10; 2385: double l1; 2386: 2387: fx=func(x); 2388: for (i=1;i<=npar;i++) p2[i]=x[i]; 2389: for(l=0 ; l <=lmax; l++){ /* Enlarging the zone around the Maximum */ 2390: l1=pow(10,l); 2391: delts=delt; 2392: for(k=1 ; k <kmax; k=k+1){ 2393: delt = delta*(l1*k); 2394: p2[theta]=x[theta] +delt; 2395: k1=func(p2)-fx; /* Might be negative if too close to the theoretical maximum */ 2396: p2[theta]=x[theta]-delt; 2397: k2=func(p2)-fx; 2398: /*res= (k1-2.0*fx+k2)/delt/delt; */ 2399: res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */ 2400: 2401: #ifdef DEBUGHESS 2402: 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); 2403: 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); 2404: #endif 2405: /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */ 2406: if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){ 2407: k=kmax; 2408: } 2409: else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */ 2410: k=kmax; l=lmax*10; 2411: } 2412: else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 2413: delts=delt; 2414: } 2415: } 2416: } 2417: delti[theta]=delts; 2418: return res; 2419: 2420: } 2421: 2422: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) 2423: { 2424: int i; 2425: int l=1, lmax=20; 2426: double k1,k2,k3,k4,res,fx; 2427: double p2[MAXPARM+1]; 2428: int k; 2429: 2430: fx=func(x); 2431: for (k=1; k<=2; k++) { 2432: for (i=1;i<=npar;i++) p2[i]=x[i]; 2433: p2[thetai]=x[thetai]+delti[thetai]/k; 2434: p2[thetaj]=x[thetaj]+delti[thetaj]/k; 2435: k1=func(p2)-fx; 2436: 2437: p2[thetai]=x[thetai]+delti[thetai]/k; 2438: p2[thetaj]=x[thetaj]-delti[thetaj]/k; 2439: k2=func(p2)-fx; 2440: 2441: p2[thetai]=x[thetai]-delti[thetai]/k; 2442: p2[thetaj]=x[thetaj]+delti[thetaj]/k; 2443: k3=func(p2)-fx; 2444: 2445: p2[thetai]=x[thetai]-delti[thetai]/k; 2446: p2[thetaj]=x[thetaj]-delti[thetaj]/k; 2447: k4=func(p2)-fx; 2448: res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */ 2449: #ifdef DEBUG 2450: 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); 2451: 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); 2452: #endif 2453: } 2454: return res; 2455: } 2456: 2457: /************** Inverse of matrix **************/ 2458: void ludcmp(double **a, int n, int *indx, double *d) 2459: { 2460: int i,imax,j,k; 2461: double big,dum,sum,temp; 2462: double *vv; 2463: 2464: vv=vector(1,n); 2465: *d=1.0; 2466: for (i=1;i<=n;i++) { 2467: big=0.0; 2468: for (j=1;j<=n;j++) 2469: if ((temp=fabs(a[i][j])) > big) big=temp; 2470: if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 2471: vv[i]=1.0/big; 2472: } 2473: for (j=1;j<=n;j++) { 2474: for (i=1;i<j;i++) { 2475: sum=a[i][j]; 2476: for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 2477: a[i][j]=sum; 2478: } 2479: big=0.0; 2480: for (i=j;i<=n;i++) { 2481: sum=a[i][j]; 2482: for (k=1;k<j;k++) 2483: sum -= a[i][k]*a[k][j]; 2484: a[i][j]=sum; 2485: if ( (dum=vv[i]*fabs(sum)) >= big) { 2486: big=dum; 2487: imax=i; 2488: } 2489: } 2490: if (j != imax) { 2491: for (k=1;k<=n;k++) { 2492: dum=a[imax][k]; 2493: a[imax][k]=a[j][k]; 2494: a[j][k]=dum; 2495: } 2496: *d = -(*d); 2497: vv[imax]=vv[j]; 2498: } 2499: indx[j]=imax; 2500: if (a[j][j] == 0.0) a[j][j]=TINY; 2501: if (j != n) { 2502: dum=1.0/(a[j][j]); 2503: for (i=j+1;i<=n;i++) a[i][j] *= dum; 2504: } 2505: } 2506: free_vector(vv,1,n); /* Doesn't work */ 2507: ; 2508: } 2509: 2510: void lubksb(double **a, int n, int *indx, double b[]) 2511: { 2512: int i,ii=0,ip,j; 2513: double sum; 2514: 2515: for (i=1;i<=n;i++) { 2516: ip=indx[i]; 2517: sum=b[ip]; 2518: b[ip]=b[i]; 2519: if (ii) 2520: for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 2521: else if (sum) ii=i; 2522: b[i]=sum; 2523: } 2524: for (i=n;i>=1;i--) { 2525: sum=b[i]; 2526: for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 2527: b[i]=sum/a[i][i]; 2528: } 2529: } 2530: 2531: void pstamp(FILE *fichier) 2532: { 2533: fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart); 2534: } 2535: 2536: /************ Frequencies ********************/ 2537: 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[]) 2538: { /* Some frequencies */ 2539: 2540: int i, m, jk, j1, bool, z1,j; 2541: int first; 2542: double ***freq; /* Frequencies */ 2543: double *pp, **prop; 2544: double pos,posprop, k2, dateintsum=0,k2cpt=0; 2545: char fileresp[FILENAMELENGTH]; 2546: 2547: pp=vector(1,nlstate); 2548: prop=matrix(1,nlstate,iagemin,iagemax+3); 2549: strcpy(fileresp,"p"); 2550: strcat(fileresp,fileres); 2551: if((ficresp=fopen(fileresp,"w"))==NULL) { 2552: printf("Problem with prevalence resultfile: %s\n", fileresp); 2553: fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp); 2554: exit(0); 2555: } 2556: freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3); 2557: j1=0; 2558: 2559: j=cptcoveff; 2560: if (cptcovn<1) {j=1;ncodemax[1]=1;} 2561: 2562: first=1; 2563: 2564: /* for(k1=1; k1<=j ; k1++){ */ /* Loop on covariates */ 2565: /* for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */ 2566: /* j1++; */ 2567: for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){ 2568: /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]); 2569: scanf("%d", i);*/ 2570: for (i=-5; i<=nlstate+ndeath; i++) 2571: for (jk=-5; jk<=nlstate+ndeath; jk++) 2572: for(m=iagemin; m <= iagemax+3; m++) 2573: freq[i][jk][m]=0; 2574: 2575: for (i=1; i<=nlstate; i++) 2576: for(m=iagemin; m <= iagemax+3; m++) 2577: prop[i][m]=0; 2578: 2579: dateintsum=0; 2580: k2cpt=0; 2581: for (i=1; i<=imx; i++) { 2582: bool=1; 2583: if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */ 2584: for (z1=1; z1<=cptcoveff; z1++) 2585: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){ 2586: /* Tests if the value of each of the covariates of i is equal to filter j1 */ 2587: bool=0; 2588: /* 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", 2589: bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1], 2590: j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/ 2591: /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/ 2592: } 2593: } 2594: 2595: if (bool==1){ 2596: for(m=firstpass; m<=lastpass; m++){ 2597: k2=anint[m][i]+(mint[m][i]/12.); 2598: /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/ 2599: if(agev[m][i]==0) agev[m][i]=iagemax+1; 2600: if(agev[m][i]==1) agev[m][i]=iagemax+2; 2601: if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i]; 2602: if (m<lastpass) { 2603: freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i]; 2604: freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i]; 2605: } 2606: 2607: if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) { 2608: dateintsum=dateintsum+k2; 2609: k2cpt++; 2610: } 2611: /*}*/ 2612: } 2613: } 2614: } /* end i */ 2615: 2616: /* fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/ 2617: pstamp(ficresp); 2618: if (cptcovn>0) { 2619: fprintf(ficresp, "\n#********** Variable "); 2620: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]); 2621: fprintf(ficresp, "**********\n#"); 2622: fprintf(ficlog, "\n#********** Variable "); 2623: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]); 2624: fprintf(ficlog, "**********\n#"); 2625: } 2626: for(i=1; i<=nlstate;i++) 2627: fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i); 2628: fprintf(ficresp, "\n"); 2629: 2630: for(i=iagemin; i <= iagemax+3; i++){ 2631: if(i==iagemax+3){ 2632: fprintf(ficlog,"Total"); 2633: }else{ 2634: if(first==1){ 2635: first=0; 2636: printf("See log file for details...\n"); 2637: } 2638: fprintf(ficlog,"Age %d", i); 2639: } 2640: for(jk=1; jk <=nlstate ; jk++){ 2641: for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++) 2642: pp[jk] += freq[jk][m][i]; 2643: } 2644: for(jk=1; jk <=nlstate ; jk++){ 2645: for(m=-1, pos=0; m <=0 ; m++) 2646: pos += freq[jk][m][i]; 2647: if(pp[jk]>=1.e-10){ 2648: if(first==1){ 2649: printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]); 2650: } 2651: fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]); 2652: }else{ 2653: if(first==1) 2654: printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk); 2655: fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk); 2656: } 2657: } 2658: 2659: for(jk=1; jk <=nlstate ; jk++){ 2660: for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++) 2661: pp[jk] += freq[jk][m][i]; 2662: } 2663: for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){ 2664: pos += pp[jk]; 2665: posprop += prop[jk][i]; 2666: } 2667: for(jk=1; jk <=nlstate ; jk++){ 2668: if(pos>=1.e-5){ 2669: if(first==1) 2670: printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos); 2671: fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos); 2672: }else{ 2673: if(first==1) 2674: printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk); 2675: fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk); 2676: } 2677: if( i <= iagemax){ 2678: if(pos>=1.e-5){ 2679: fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop); 2680: /*probs[i][jk][j1]= pp[jk]/pos;*/ 2681: /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/ 2682: } 2683: else 2684: fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop); 2685: } 2686: } 2687: 2688: for(jk=-1; jk <=nlstate+ndeath; jk++) 2689: for(m=-1; m <=nlstate+ndeath; m++) 2690: if(freq[jk][m][i] !=0 ) { 2691: if(first==1) 2692: printf(" %d%d=%.0f",jk,m,freq[jk][m][i]); 2693: fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]); 2694: } 2695: if(i <= iagemax) 2696: fprintf(ficresp,"\n"); 2697: if(first==1) 2698: printf("Others in log...\n"); 2699: fprintf(ficlog,"\n"); 2700: } 2701: /*}*/ 2702: } 2703: dateintmean=dateintsum/k2cpt; 2704: 2705: fclose(ficresp); 2706: free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3); 2707: free_vector(pp,1,nlstate); 2708: free_matrix(prop,1,nlstate,iagemin, iagemax+3); 2709: /* End of Freq */ 2710: } 2711: 2712: /************ Prevalence ********************/ 2713: 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) 2714: { 2715: /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people 2716: in each health status at the date of interview (if between dateprev1 and dateprev2). 2717: We still use firstpass and lastpass as another selection. 2718: */ 2719: 2720: int i, m, jk, j1, bool, z1,j; 2721: 2722: double **prop; 2723: double posprop; 2724: double y2; /* in fractional years */ 2725: int iagemin, iagemax; 2726: int first; /** to stop verbosity which is redirected to log file */ 2727: 2728: iagemin= (int) agemin; 2729: iagemax= (int) agemax; 2730: /*pp=vector(1,nlstate);*/ 2731: prop=matrix(1,nlstate,iagemin,iagemax+3); 2732: /* freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/ 2733: j1=0; 2734: 2735: /*j=cptcoveff;*/ 2736: if (cptcovn<1) {j=1;ncodemax[1]=1;} 2737: 2738: first=1; 2739: for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ 2740: /*for(i1=1; i1<=ncodemax[k1];i1++){ 2741: j1++;*/ 2742: 2743: for (i=1; i<=nlstate; i++) 2744: for(m=iagemin; m <= iagemax+3; m++) 2745: prop[i][m]=0.0; 2746: 2747: for (i=1; i<=imx; i++) { /* Each individual */ 2748: bool=1; 2749: if (cptcovn>0) { 2750: for (z1=1; z1<=cptcoveff; z1++) 2751: if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]) 2752: bool=0; 2753: } 2754: if (bool==1) { 2755: for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/ 2756: y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */ 2757: if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */ 2758: if(agev[m][i]==0) agev[m][i]=iagemax+1; 2759: if(agev[m][i]==1) agev[m][i]=iagemax+2; 2760: 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); 2761: if (s[m][i]>0 && s[m][i]<=nlstate) { 2762: /*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]]);*/ 2763: prop[s[m][i]][(int)agev[m][i]] += weight[i]; 2764: prop[s[m][i]][iagemax+3] += weight[i]; 2765: } 2766: } 2767: } /* end selection of waves */ 2768: } 2769: } 2770: for(i=iagemin; i <= iagemax+3; i++){ 2771: for(jk=1,posprop=0; jk <=nlstate ; jk++) { 2772: posprop += prop[jk][i]; 2773: } 2774: 2775: for(jk=1; jk <=nlstate ; jk++){ 2776: if( i <= iagemax){ 2777: if(posprop>=1.e-5){ 2778: probs[i][jk][j1]= prop[jk][i]/posprop; 2779: } else{ 2780: if(first==1){ 2781: first=0; 2782: 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]); 2783: } 2784: } 2785: } 2786: }/* end jk */ 2787: }/* end i */ 2788: /*} *//* end i1 */ 2789: } /* end j1 */ 2790: 2791: /* free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/ 2792: /*free_vector(pp,1,nlstate);*/ 2793: free_matrix(prop,1,nlstate, iagemin,iagemax+3); 2794: } /* End of prevalence */ 2795: 2796: /************* Waves Concatenation ***************/ 2797: 2798: 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) 2799: { 2800: /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i. 2801: Death is a valid wave (if date is known). 2802: mw[mi][i] is the mi (mi=1 to wav[i]) effective wave of individual i 2803: dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i] 2804: and mw[mi+1][i]. dh depends on stepm. 2805: */ 2806: 2807: int i, mi, m; 2808: /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1; 2809: double sum=0., jmean=0.;*/ 2810: int first; 2811: int j, k=0,jk, ju, jl; 2812: double sum=0.; 2813: first=0; 2814: jmin=100000; 2815: jmax=-1; 2816: jmean=0.; 2817: for(i=1; i<=imx; i++){ 2818: mi=0; 2819: m=firstpass; 2820: while(s[m][i] <= nlstate){ 2821: if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5) 2822: mw[++mi][i]=m; 2823: if(m >=lastpass) 2824: break; 2825: else 2826: m++; 2827: }/* end while */ 2828: if (s[m][i] > nlstate){ 2829: mi++; /* Death is another wave */ 2830: /* if(mi==0) never been interviewed correctly before death */ 2831: /* Only death is a correct wave */ 2832: mw[mi][i]=m; 2833: } 2834: 2835: wav[i]=mi; 2836: if(mi==0){ 2837: nbwarn++; 2838: if(first==0){ 2839: printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i); 2840: first=1; 2841: } 2842: if(first==1){ 2843: fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i); 2844: } 2845: } /* end mi==0 */ 2846: } /* End individuals */ 2847: 2848: for(i=1; i<=imx; i++){ 2849: for(mi=1; mi<wav[i];mi++){ 2850: if (stepm <=0) 2851: dh[mi][i]=1; 2852: else{ 2853: if (s[mw[mi+1][i]][i] > nlstate) { /* A death */ 2854: if (agedc[i] < 2*AGESUP) { 2855: j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 2856: if(j==0) j=1; /* Survives at least one month after exam */ 2857: else if(j<0){ 2858: nberr++; 2859: 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]); 2860: j=1; /* Temporary Dangerous patch */ 2861: 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); 2862: 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]); 2863: 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); 2864: } 2865: k=k+1; 2866: if (j >= jmax){ 2867: jmax=j; 2868: ijmax=i; 2869: } 2870: if (j <= jmin){ 2871: jmin=j; 2872: ijmin=i; 2873: } 2874: sum=sum+j; 2875: /*if (j<0) printf("j=%d num=%d \n",j,i);*/ 2876: /* printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/ 2877: } 2878: } 2879: else{ 2880: j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12)); 2881: /* 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]); */ 2882: 2883: k=k+1; 2884: if (j >= jmax) { 2885: jmax=j; 2886: ijmax=i; 2887: } 2888: else if (j <= jmin){ 2889: jmin=j; 2890: ijmin=i; 2891: } 2892: /* if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */ 2893: /*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]);*/ 2894: if(j<0){ 2895: nberr++; 2896: 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]); 2897: 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]); 2898: } 2899: sum=sum+j; 2900: } 2901: jk= j/stepm; 2902: jl= j -jk*stepm; 2903: ju= j -(jk+1)*stepm; 2904: if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */ 2905: if(jl==0){ 2906: dh[mi][i]=jk; 2907: bh[mi][i]=0; 2908: }else{ /* We want a negative bias in order to only have interpolation ie 2909: * to avoid the price of an extra matrix product in likelihood */ 2910: dh[mi][i]=jk+1; 2911: bh[mi][i]=ju; 2912: } 2913: }else{ 2914: if(jl <= -ju){ 2915: dh[mi][i]=jk; 2916: bh[mi][i]=jl; /* bias is positive if real duration 2917: * is higher than the multiple of stepm and negative otherwise. 2918: */ 2919: } 2920: else{ 2921: dh[mi][i]=jk+1; 2922: bh[mi][i]=ju; 2923: } 2924: if(dh[mi][i]==0){ 2925: dh[mi][i]=1; /* At least one step */ 2926: bh[mi][i]=ju; /* At least one step */ 2927: /* 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);*/ 2928: } 2929: } /* end if mle */ 2930: } 2931: } /* end wave */ 2932: } 2933: jmean=sum/k; 2934: 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); 2935: 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); 2936: } 2937: 2938: /*********** Tricode ****************************/ 2939: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum) 2940: { 2941: /**< Uses cptcovn+2*cptcovprod as the number of covariates */ 2942: /* Tvar[i]=atoi(stre); find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 2943: * Boring subroutine which should only output nbcode[Tvar[j]][k] 2944: * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2) 2945: * nbcode[Tvar[j]][1]= 2946: */ 2947: 2948: int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX; 2949: int modmaxcovj=0; /* Modality max of covariates j */ 2950: int cptcode=0; /* Modality max of covariates j */ 2951: int modmincovj=0; /* Modality min of covariates j */ 2952: 2953: 2954: cptcoveff=0; 2955: 2956: for (k=-1; k < maxncov; k++) Ndum[k]=0; 2957: for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */ 2958: 2959: /* Loop on covariates without age and products */ 2960: for (j=1; j<=(cptcovs); j++) { /* model V1 + V2*age+ V3 + V3*V4 : V1 + V3 = 2 only */ 2961: for (i=1; i<=imx; i++) { /* Lopp on individuals: reads the data file to get the maximum value of the 2962: modality of this covariate Vj*/ 2963: ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i 2964: * If product of Vn*Vm, still boolean *: 2965: * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables 2966: * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0 */ 2967: /* Finds for covariate j, n=Tvar[j] of Vn . ij is the 2968: modality of the nth covariate of individual i. */ 2969: if (ij > modmaxcovj) 2970: modmaxcovj=ij; 2971: else if (ij < modmincovj) 2972: modmincovj=ij; 2973: if ((ij < -1) && (ij > NCOVMAX)){ 2974: printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX ); 2975: exit(1); 2976: }else 2977: Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/ 2978: /* If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */ 2979: /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/ 2980: /* getting the maximum value of the modality of the covariate 2981: (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and 2982: female is 1, then modmaxcovj=1.*/ 2983: } 2984: printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj); 2985: cptcode=modmaxcovj; 2986: /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */ 2987: /*for (i=0; i<=cptcode; i++) {*/ 2988: for (i=modmincovj; i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */ 2989: printf("Frequencies of covariates %d V%d %d\n", j, Tvar[j], Ndum[i]); 2990: if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */ 2991: ncodemax[j]++; /* ncodemax[j]= Number of non-null modalities of the j th covariate. */ 2992: } 2993: /* In fact ncodemax[j]=2 (dichotom. variables only) but it could be more for 2994: historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */ 2995: } /* Ndum[-1] number of undefined modalities */ 2996: 2997: /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */ 2998: /* For covariate j, modalities could be 1, 2, 3, 4. If Ndum[2]=0 ncodemax[j] is not 4 but 3 */ 2999: /* If Ndum[3}= 635; Ndum[4]=0; Ndum[5]=0; Ndum[6]=27; Ndum[7]=125; 3000: modmincovj=3; modmaxcovj = 7; 3001: There are only 3 modalities non empty (or 2 if 27 is too few) : ncodemax[j]=3; 3002: which will be coded 0, 1, 2 which in binary on 3-1 digits are 0=00 1=01, 2=10; defining two dummy 3003: variables V1_1 and V1_2. 3004: nbcode[Tvar[j]][ij]=k; 3005: nbcode[Tvar[j]][1]=0; 3006: nbcode[Tvar[j]][2]=1; 3007: nbcode[Tvar[j]][3]=2; 3008: */ 3009: ij=1; /* ij is similar to i but can jumps over null modalities */ 3010: for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */ 3011: for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */ 3012: /*recode from 0 */ 3013: if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */ 3014: nbcode[Tvar[j]][ij]=k; /* stores the modality in an array nbcode. 3015: k is a modality. If we have model=V1+V1*sex 3016: then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */ 3017: ij++; 3018: } 3019: if (ij > ncodemax[j]) break; 3020: } /* end of loop on */ 3021: } /* end of loop on modality */ 3022: } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/ 3023: 3024: for (k=-1; k< maxncov; k++) Ndum[k]=0; 3025: 3026: for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */ 3027: /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 3028: ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 3029: Ndum[ij]++; 3030: } 3031: 3032: ij=1; 3033: for (i=0; i<= maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */ 3034: /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/ 3035: if((Ndum[i]!=0) && (i<=ncovcol)){ 3036: /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/ 3037: Tvaraff[ij]=i; /*For printing (unclear) */ 3038: ij++; 3039: }else 3040: Tvaraff[ij]=0; 3041: } 3042: ij--; 3043: cptcoveff=ij; /*Number of total covariates*/ 3044: 3045: } 3046: 3047: 3048: /*********** Health Expectancies ****************/ 3049: 3050: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] ) 3051: 3052: { 3053: /* Health expectancies, no variances */ 3054: int i, j, nhstepm, hstepm, h, nstepm; 3055: int nhstepma, nstepma; /* Decreasing with age */ 3056: double age, agelim, hf; 3057: double ***p3mat; 3058: double eip; 3059: 3060: pstamp(ficreseij); 3061: fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n"); 3062: fprintf(ficreseij,"# Age"); 3063: for(i=1; i<=nlstate;i++){ 3064: for(j=1; j<=nlstate;j++){ 3065: fprintf(ficreseij," e%1d%1d ",i,j); 3066: } 3067: fprintf(ficreseij," e%1d. ",i); 3068: } 3069: fprintf(ficreseij,"\n"); 3070: 3071: 3072: if(estepm < stepm){ 3073: printf ("Problem %d lower than %d\n",estepm, stepm); 3074: } 3075: else hstepm=estepm; 3076: /* We compute the life expectancy from trapezoids spaced every estepm months 3077: * This is mainly to measure the difference between two models: for example 3078: * if stepm=24 months pijx are given only every 2 years and by summing them 3079: * we are calculating an estimate of the Life Expectancy assuming a linear 3080: * progression in between and thus overestimating or underestimating according 3081: * to the curvature of the survival function. If, for the same date, we 3082: * estimate the model with stepm=1 month, we can keep estepm to 24 months 3083: * to compare the new estimate of Life expectancy with the same linear 3084: * hypothesis. A more precise result, taking into account a more precise 3085: * curvature will be obtained if estepm is as small as stepm. */ 3086: 3087: /* For example we decided to compute the life expectancy with the smallest unit */ 3088: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 3089: nhstepm is the number of hstepm from age to agelim 3090: nstepm is the number of stepm from age to agelin. 3091: Look at hpijx to understand the reason of that which relies in memory size 3092: and note for a fixed period like estepm months */ 3093: /* We decided (b) to get a life expectancy respecting the most precise curvature of the 3094: survival function given by stepm (the optimization length). Unfortunately it 3095: means that if the survival funtion is printed only each two years of age and if 3096: you sum them up and add 1 year (area under the trapezoids) you won't get the same 3097: results. So we changed our mind and took the option of the best precision. 3098: */ 3099: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 3100: 3101: agelim=AGESUP; 3102: /* If stepm=6 months */ 3103: /* Computed by stepm unit matrices, product of hstepm matrices, stored 3104: in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */ 3105: 3106: /* nhstepm age range expressed in number of stepm */ 3107: nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */ 3108: /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 3109: /* if (stepm >= YEARM) hstepm=1;*/ 3110: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */ 3111: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); 3112: 3113: for (age=bage; age<=fage; age ++){ 3114: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */ 3115: /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 3116: /* if (stepm >= YEARM) hstepm=1;*/ 3117: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */ 3118: 3119: /* If stepm=6 months */ 3120: /* Computed by stepm unit matrices, product of hstepma matrices, stored 3121: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */ 3122: 3123: hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij); 3124: 3125: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */ 3126: 3127: printf("%d|",(int)age);fflush(stdout); 3128: fprintf(ficlog,"%d|",(int)age);fflush(ficlog); 3129: 3130: /* Computing expectancies */ 3131: for(i=1; i<=nlstate;i++) 3132: for(j=1; j<=nlstate;j++) 3133: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){ 3134: eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf; 3135: 3136: /* 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]);*/ 3137: 3138: } 3139: 3140: fprintf(ficreseij,"%3.0f",age ); 3141: for(i=1; i<=nlstate;i++){ 3142: eip=0; 3143: for(j=1; j<=nlstate;j++){ 3144: eip +=eij[i][j][(int)age]; 3145: fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] ); 3146: } 3147: fprintf(ficreseij,"%9.4f", eip ); 3148: } 3149: fprintf(ficreseij,"\n"); 3150: 3151: } 3152: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); 3153: printf("\n"); 3154: fprintf(ficlog,"\n"); 3155: 3156: } 3157: 3158: 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[] ) 3159: 3160: { 3161: /* Covariances of health expectancies eij and of total life expectancies according 3162: to initial status i, ei. . 3163: */ 3164: int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji; 3165: int nhstepma, nstepma; /* Decreasing with age */ 3166: double age, agelim, hf; 3167: double ***p3matp, ***p3matm, ***varhe; 3168: double **dnewm,**doldm; 3169: double *xp, *xm; 3170: double **gp, **gm; 3171: double ***gradg, ***trgradg; 3172: int theta; 3173: 3174: double eip, vip; 3175: 3176: varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage); 3177: xp=vector(1,npar); 3178: xm=vector(1,npar); 3179: dnewm=matrix(1,nlstate*nlstate,1,npar); 3180: doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate); 3181: 3182: pstamp(ficresstdeij); 3183: fprintf(ficresstdeij,"# Health expectancies with standard errors\n"); 3184: fprintf(ficresstdeij,"# Age"); 3185: for(i=1; i<=nlstate;i++){ 3186: for(j=1; j<=nlstate;j++) 3187: fprintf(ficresstdeij," e%1d%1d (SE)",i,j); 3188: fprintf(ficresstdeij," e%1d. ",i); 3189: } 3190: fprintf(ficresstdeij,"\n"); 3191: 3192: pstamp(ficrescveij); 3193: fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n"); 3194: fprintf(ficrescveij,"# Age"); 3195: for(i=1; i<=nlstate;i++) 3196: for(j=1; j<=nlstate;j++){ 3197: cptj= (j-1)*nlstate+i; 3198: for(i2=1; i2<=nlstate;i2++) 3199: for(j2=1; j2<=nlstate;j2++){ 3200: cptj2= (j2-1)*nlstate+i2; 3201: if(cptj2 <= cptj) 3202: fprintf(ficrescveij," %1d%1d,%1d%1d",i,j,i2,j2); 3203: } 3204: } 3205: fprintf(ficrescveij,"\n"); 3206: 3207: if(estepm < stepm){ 3208: printf ("Problem %d lower than %d\n",estepm, stepm); 3209: } 3210: else hstepm=estepm; 3211: /* We compute the life expectancy from trapezoids spaced every estepm months 3212: * This is mainly to measure the difference between two models: for example 3213: * if stepm=24 months pijx are given only every 2 years and by summing them 3214: * we are calculating an estimate of the Life Expectancy assuming a linear 3215: * progression in between and thus overestimating or underestimating according 3216: * to the curvature of the survival function. If, for the same date, we 3217: * estimate the model with stepm=1 month, we can keep estepm to 24 months 3218: * to compare the new estimate of Life expectancy with the same linear 3219: * hypothesis. A more precise result, taking into account a more precise 3220: * curvature will be obtained if estepm is as small as stepm. */ 3221: 3222: /* For example we decided to compute the life expectancy with the smallest unit */ 3223: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 3224: nhstepm is the number of hstepm from age to agelim 3225: nstepm is the number of stepm from age to agelin. 3226: Look at hpijx to understand the reason of that which relies in memory size 3227: and note for a fixed period like estepm months */ 3228: /* We decided (b) to get a life expectancy respecting the most precise curvature of the 3229: survival function given by stepm (the optimization length). Unfortunately it 3230: means that if the survival funtion is printed only each two years of age and if 3231: you sum them up and add 1 year (area under the trapezoids) you won't get the same 3232: results. So we changed our mind and took the option of the best precision. 3233: */ 3234: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 3235: 3236: /* If stepm=6 months */ 3237: /* nhstepm age range expressed in number of stepm */ 3238: agelim=AGESUP; 3239: nstepm=(int) rint((agelim-bage)*YEARM/stepm); 3240: /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 3241: /* if (stepm >= YEARM) hstepm=1;*/ 3242: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */ 3243: 3244: p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); 3245: p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); 3246: gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate); 3247: trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar); 3248: gp=matrix(0,nhstepm,1,nlstate*nlstate); 3249: gm=matrix(0,nhstepm,1,nlstate*nlstate); 3250: 3251: for (age=bage; age<=fage; age ++){ 3252: nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */ 3253: /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 3254: /* if (stepm >= YEARM) hstepm=1;*/ 3255: nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */ 3256: 3257: /* If stepm=6 months */ 3258: /* Computed by stepm unit matrices, product of hstepma matrices, stored 3259: in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */ 3260: 3261: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */ 3262: 3263: /* Computing Variances of health expectancies */ 3264: /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to 3265: decrease memory allocation */ 3266: for(theta=1; theta <=npar; theta++){ 3267: for(i=1; i<=npar; i++){ 3268: xp[i] = x[i] + (i==theta ?delti[theta]:0); 3269: xm[i] = x[i] - (i==theta ?delti[theta]:0); 3270: } 3271: hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij); 3272: hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij); 3273: 3274: for(j=1; j<= nlstate; j++){ 3275: for(i=1; i<=nlstate; i++){ 3276: for(h=0; h<=nhstepm-1; h++){ 3277: gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.; 3278: gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.; 3279: } 3280: } 3281: } 3282: 3283: for(ij=1; ij<= nlstate*nlstate; ij++) 3284: for(h=0; h<=nhstepm-1; h++){ 3285: gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta]; 3286: } 3287: }/* End theta */ 3288: 3289: 3290: for(h=0; h<=nhstepm-1; h++) 3291: for(j=1; j<=nlstate*nlstate;j++) 3292: for(theta=1; theta <=npar; theta++) 3293: trgradg[h][j][theta]=gradg[h][theta][j]; 3294: 3295: 3296: for(ij=1;ij<=nlstate*nlstate;ij++) 3297: for(ji=1;ji<=nlstate*nlstate;ji++) 3298: varhe[ij][ji][(int)age] =0.; 3299: 3300: printf("%d|",(int)age);fflush(stdout); 3301: fprintf(ficlog,"%d|",(int)age);fflush(ficlog); 3302: for(h=0;h<=nhstepm-1;h++){ 3303: for(k=0;k<=nhstepm-1;k++){ 3304: matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov); 3305: matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]); 3306: for(ij=1;ij<=nlstate*nlstate;ij++) 3307: for(ji=1;ji<=nlstate*nlstate;ji++) 3308: varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf; 3309: } 3310: } 3311: 3312: /* Computing expectancies */ 3313: hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij); 3314: for(i=1; i<=nlstate;i++) 3315: for(j=1; j<=nlstate;j++) 3316: for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){ 3317: eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf; 3318: 3319: /* 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]);*/ 3320: 3321: } 3322: 3323: fprintf(ficresstdeij,"%3.0f",age ); 3324: for(i=1; i<=nlstate;i++){ 3325: eip=0.; 3326: vip=0.; 3327: for(j=1; j<=nlstate;j++){ 3328: eip += eij[i][j][(int)age]; 3329: for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */ 3330: vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age]; 3331: fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) ); 3332: } 3333: fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip)); 3334: } 3335: fprintf(ficresstdeij,"\n"); 3336: 3337: fprintf(ficrescveij,"%3.0f",age ); 3338: for(i=1; i<=nlstate;i++) 3339: for(j=1; j<=nlstate;j++){ 3340: cptj= (j-1)*nlstate+i; 3341: for(i2=1; i2<=nlstate;i2++) 3342: for(j2=1; j2<=nlstate;j2++){ 3343: cptj2= (j2-1)*nlstate+i2; 3344: if(cptj2 <= cptj) 3345: fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]); 3346: } 3347: } 3348: fprintf(ficrescveij,"\n"); 3349: 3350: } 3351: free_matrix(gm,0,nhstepm,1,nlstate*nlstate); 3352: free_matrix(gp,0,nhstepm,1,nlstate*nlstate); 3353: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate); 3354: free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar); 3355: free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); 3356: free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); 3357: printf("\n"); 3358: fprintf(ficlog,"\n"); 3359: 3360: free_vector(xm,1,npar); 3361: free_vector(xp,1,npar); 3362: free_matrix(dnewm,1,nlstate*nlstate,1,npar); 3363: free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate); 3364: free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage); 3365: } 3366: 3367: /************ Variance ******************/ 3368: 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[]) 3369: { 3370: /* Variance of health expectancies */ 3371: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/ 3372: /* double **newm;*/ 3373: /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/ 3374: 3375: int movingaverage(); 3376: double **dnewm,**doldm; 3377: double **dnewmp,**doldmp; 3378: int i, j, nhstepm, hstepm, h, nstepm ; 3379: int k; 3380: double *xp; 3381: double **gp, **gm; /* for var eij */ 3382: double ***gradg, ***trgradg; /*for var eij */ 3383: double **gradgp, **trgradgp; /* for var p point j */ 3384: double *gpp, *gmp; /* for var p point j */ 3385: double **varppt; /* for var p point j nlstate to nlstate+ndeath */ 3386: double ***p3mat; 3387: double age,agelim, hf; 3388: double ***mobaverage; 3389: int theta; 3390: char digit[4]; 3391: char digitp[25]; 3392: 3393: char fileresprobmorprev[FILENAMELENGTH]; 3394: 3395: if(popbased==1){ 3396: if(mobilav!=0) 3397: strcpy(digitp,"-populbased-mobilav-"); 3398: else strcpy(digitp,"-populbased-nomobil-"); 3399: } 3400: else 3401: strcpy(digitp,"-stablbased-"); 3402: 3403: if (mobilav!=0) { 3404: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); 3405: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ 3406: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); 3407: printf(" Error in movingaverage mobilav=%d\n",mobilav); 3408: } 3409: } 3410: 3411: strcpy(fileresprobmorprev,"prmorprev"); 3412: sprintf(digit,"%-d",ij); 3413: /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/ 3414: strcat(fileresprobmorprev,digit); /* Tvar to be done */ 3415: strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */ 3416: strcat(fileresprobmorprev,fileres); 3417: if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) { 3418: printf("Problem with resultfile: %s\n", fileresprobmorprev); 3419: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev); 3420: } 3421: printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev); 3422: 3423: fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev); 3424: pstamp(ficresprobmorprev); 3425: 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); 3426: fprintf(ficresprobmorprev,"# Age cov=%-d",ij); 3427: for(j=nlstate+1; j<=(nlstate+ndeath);j++){ 3428: fprintf(ficresprobmorprev," p.%-d SE",j); 3429: for(i=1; i<=nlstate;i++) 3430: fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j); 3431: } 3432: fprintf(ficresprobmorprev,"\n"); 3433: fprintf(ficgp,"\n# Routine varevsij"); 3434: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/ 3435: 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"); 3436: fprintf(fichtm,"\n<br>%s <br>\n",digitp); 3437: /* } */ 3438: varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath); 3439: pstamp(ficresvij); 3440: fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n# (weighted average of eij where weights are "); 3441: if(popbased==1) 3442: 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); 3443: else 3444: fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n"); 3445: fprintf(ficresvij,"# Age"); 3446: for(i=1; i<=nlstate;i++) 3447: for(j=1; j<=nlstate;j++) 3448: fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j); 3449: fprintf(ficresvij,"\n"); 3450: 3451: xp=vector(1,npar); 3452: dnewm=matrix(1,nlstate,1,npar); 3453: doldm=matrix(1,nlstate,1,nlstate); 3454: dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar); 3455: doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath); 3456: 3457: gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath); 3458: gpp=vector(nlstate+1,nlstate+ndeath); 3459: gmp=vector(nlstate+1,nlstate+ndeath); 3460: trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/ 3461: 3462: if(estepm < stepm){ 3463: printf ("Problem %d lower than %d\n",estepm, stepm); 3464: } 3465: else hstepm=estepm; 3466: /* For example we decided to compute the life expectancy with the smallest unit */ 3467: /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 3468: nhstepm is the number of hstepm from age to agelim 3469: nstepm is the number of stepm from age to agelin. 3470: Look at function hpijx to understand why (it is linked to memory size questions) */ 3471: /* We decided (b) to get a life expectancy respecting the most precise curvature of the 3472: survival function given by stepm (the optimization length). Unfortunately it 3473: means that if the survival funtion is printed every two years of age and if 3474: you sum them up and add 1 year (area under the trapezoids) you won't get the same 3475: results. So we changed our mind and took the option of the best precision. 3476: */ 3477: hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 3478: agelim = AGESUP; 3479: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */ 3480: nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 3481: nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */ 3482: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); 3483: gradg=ma3x(0,nhstepm,1,npar,1,nlstate); 3484: gp=matrix(0,nhstepm,1,nlstate); 3485: gm=matrix(0,nhstepm,1,nlstate); 3486: 3487: 3488: for(theta=1; theta <=npar; theta++){ 3489: for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/ 3490: xp[i] = x[i] + (i==theta ?delti[theta]:0); 3491: } 3492: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij); 3493: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij); 3494: 3495: if (popbased==1) { 3496: if(mobilav ==0){ 3497: for(i=1; i<=nlstate;i++) 3498: prlim[i][i]=probs[(int)age][i][ij]; 3499: }else{ /* mobilav */ 3500: for(i=1; i<=nlstate;i++) 3501: prlim[i][i]=mobaverage[(int)age][i][ij]; 3502: } 3503: } 3504: 3505: for(j=1; j<= nlstate; j++){ 3506: for(h=0; h<=nhstepm; h++){ 3507: for(i=1, gp[h][j]=0.;i<=nlstate;i++) 3508: gp[h][j] += prlim[i][i]*p3mat[i][j][h]; 3509: } 3510: } 3511: /* This for computing probability of death (h=1 means 3512: computed over hstepm matrices product = hstepm*stepm months) 3513: as a weighted average of prlim. 3514: */ 3515: for(j=nlstate+1;j<=nlstate+ndeath;j++){ 3516: for(i=1,gpp[j]=0.; i<= nlstate; i++) 3517: gpp[j] += prlim[i][i]*p3mat[i][j][1]; 3518: } 3519: /* end probability of death */ 3520: 3521: for(i=1; i<=npar; i++) /* Computes gradient x - delta */ 3522: xp[i] = x[i] - (i==theta ?delti[theta]:0); 3523: hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij); 3524: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij); 3525: 3526: if (popbased==1) { 3527: if(mobilav ==0){ 3528: for(i=1; i<=nlstate;i++) 3529: prlim[i][i]=probs[(int)age][i][ij]; 3530: }else{ /* mobilav */ 3531: for(i=1; i<=nlstate;i++) 3532: prlim[i][i]=mobaverage[(int)age][i][ij]; 3533: } 3534: } 3535: 3536: for(j=1; j<= nlstate; j++){ /* Sum of wi * eij = e.j */ 3537: for(h=0; h<=nhstepm; h++){ 3538: for(i=1, gm[h][j]=0.;i<=nlstate;i++) 3539: gm[h][j] += prlim[i][i]*p3mat[i][j][h]; 3540: } 3541: } 3542: /* This for computing probability of death (h=1 means 3543: computed over hstepm matrices product = hstepm*stepm months) 3544: as a weighted average of prlim. 3545: */ 3546: for(j=nlstate+1;j<=nlstate+ndeath;j++){ 3547: for(i=1,gmp[j]=0.; i<= nlstate; i++) 3548: gmp[j] += prlim[i][i]*p3mat[i][j][1]; 3549: } 3550: /* end probability of death */ 3551: 3552: for(j=1; j<= nlstate; j++) /* vareij */ 3553: for(h=0; h<=nhstepm; h++){ 3554: gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta]; 3555: } 3556: 3557: for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */ 3558: gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta]; 3559: } 3560: 3561: } /* End theta */ 3562: 3563: trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */ 3564: 3565: for(h=0; h<=nhstepm; h++) /* veij */ 3566: for(j=1; j<=nlstate;j++) 3567: for(theta=1; theta <=npar; theta++) 3568: trgradg[h][j][theta]=gradg[h][theta][j]; 3569: 3570: for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */ 3571: for(theta=1; theta <=npar; theta++) 3572: trgradgp[j][theta]=gradgp[theta][j]; 3573: 3574: 3575: hf=hstepm*stepm/YEARM; /* Duration of hstepm expressed in year unit. */ 3576: for(i=1;i<=nlstate;i++) 3577: for(j=1;j<=nlstate;j++) 3578: vareij[i][j][(int)age] =0.; 3579: 3580: for(h=0;h<=nhstepm;h++){ 3581: for(k=0;k<=nhstepm;k++){ 3582: matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov); 3583: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]); 3584: for(i=1;i<=nlstate;i++) 3585: for(j=1;j<=nlstate;j++) 3586: vareij[i][j][(int)age] += doldm[i][j]*hf*hf; 3587: } 3588: } 3589: 3590: /* pptj */ 3591: matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov); 3592: matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp); 3593: for(j=nlstate+1;j<=nlstate+ndeath;j++) 3594: for(i=nlstate+1;i<=nlstate+ndeath;i++) 3595: varppt[j][i]=doldmp[j][i]; 3596: /* end ppptj */ 3597: /* x centered again */ 3598: hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij); 3599: prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij); 3600: 3601: if (popbased==1) { 3602: if(mobilav ==0){ 3603: for(i=1; i<=nlstate;i++) 3604: prlim[i][i]=probs[(int)age][i][ij]; 3605: }else{ /* mobilav */ 3606: for(i=1; i<=nlstate;i++) 3607: prlim[i][i]=mobaverage[(int)age][i][ij]; 3608: } 3609: } 3610: 3611: /* This for computing probability of death (h=1 means 3612: computed over hstepm (estepm) matrices product = hstepm*stepm months) 3613: as a weighted average of prlim. 3614: */ 3615: for(j=nlstate+1;j<=nlstate+ndeath;j++){ 3616: for(i=1,gmp[j]=0.;i<= nlstate; i++) 3617: gmp[j] += prlim[i][i]*p3mat[i][j][1]; 3618: } 3619: /* end probability of death */ 3620: 3621: fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij); 3622: for(j=nlstate+1; j<=(nlstate+ndeath);j++){ 3623: fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j])); 3624: for(i=1; i<=nlstate;i++){ 3625: fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]); 3626: } 3627: } 3628: fprintf(ficresprobmorprev,"\n"); 3629: 3630: fprintf(ficresvij,"%.0f ",age ); 3631: for(i=1; i<=nlstate;i++) 3632: for(j=1; j<=nlstate;j++){ 3633: fprintf(ficresvij," %.4f", vareij[i][j][(int)age]); 3634: } 3635: fprintf(ficresvij,"\n"); 3636: free_matrix(gp,0,nhstepm,1,nlstate); 3637: free_matrix(gm,0,nhstepm,1,nlstate); 3638: free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate); 3639: free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar); 3640: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); 3641: } /* End age */ 3642: free_vector(gpp,nlstate+1,nlstate+ndeath); 3643: free_vector(gmp,nlstate+1,nlstate+ndeath); 3644: free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath); 3645: free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/ 3646: fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); 3647: /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */ 3648: fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";"); 3649: /* fprintf(ficgp,"\n plot \"%s\" u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */ 3650: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */ 3651: /* fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */ 3652: fprintf(ficgp,"\n plot \"%s\" u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev)); 3653: fprintf(ficgp,"\n replot \"%s\" u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev)); 3654: fprintf(ficgp,"\n replot \"%s\" u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev)); 3655: fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev)); 3656: 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); 3657: /* 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); 3658: */ 3659: /* fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */ 3660: fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit); 3661: 3662: free_vector(xp,1,npar); 3663: free_matrix(doldm,1,nlstate,1,nlstate); 3664: free_matrix(dnewm,1,nlstate,1,npar); 3665: free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath); 3666: free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar); 3667: free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath); 3668: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); 3669: fclose(ficresprobmorprev); 3670: fflush(ficgp); 3671: fflush(fichtm); 3672: } /* end varevsij */ 3673: 3674: /************ Variance of prevlim ******************/ 3675: 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[]) 3676: { 3677: /* Variance of prevalence limit */ 3678: /* double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/ 3679: 3680: double **dnewm,**doldm; 3681: int i, j, nhstepm, hstepm; 3682: double *xp; 3683: double *gp, *gm; 3684: double **gradg, **trgradg; 3685: double age,agelim; 3686: int theta; 3687: 3688: pstamp(ficresvpl); 3689: fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n"); 3690: fprintf(ficresvpl,"# Age"); 3691: for(i=1; i<=nlstate;i++) 3692: fprintf(ficresvpl," %1d-%1d",i,i); 3693: fprintf(ficresvpl,"\n"); 3694: 3695: xp=vector(1,npar); 3696: dnewm=matrix(1,nlstate,1,npar); 3697: doldm=matrix(1,nlstate,1,nlstate); 3698: 3699: hstepm=1*YEARM; /* Every year of age */ 3700: hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 3701: agelim = AGESUP; 3702: for (age=bage; age<=fage; age ++){ /* If stepm=6 months */ 3703: nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 3704: if (stepm >= YEARM) hstepm=1; 3705: nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */ 3706: gradg=matrix(1,npar,1,nlstate); 3707: gp=vector(1,nlstate); 3708: gm=vector(1,nlstate); 3709: 3710: for(theta=1; theta <=npar; theta++){ 3711: for(i=1; i<=npar; i++){ /* Computes gradient */ 3712: xp[i] = x[i] + (i==theta ?delti[theta]:0); 3713: } 3714: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij); 3715: for(i=1;i<=nlstate;i++) 3716: gp[i] = prlim[i][i]; 3717: 3718: for(i=1; i<=npar; i++) /* Computes gradient */ 3719: xp[i] = x[i] - (i==theta ?delti[theta]:0); 3720: prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij); 3721: for(i=1;i<=nlstate;i++) 3722: gm[i] = prlim[i][i]; 3723: 3724: for(i=1;i<=nlstate;i++) 3725: gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta]; 3726: } /* End theta */ 3727: 3728: trgradg =matrix(1,nlstate,1,npar); 3729: 3730: for(j=1; j<=nlstate;j++) 3731: for(theta=1; theta <=npar; theta++) 3732: trgradg[j][theta]=gradg[theta][j]; 3733: 3734: for(i=1;i<=nlstate;i++) 3735: varpl[i][(int)age] =0.; 3736: matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov); 3737: matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg); 3738: for(i=1;i<=nlstate;i++) 3739: varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */ 3740: 3741: fprintf(ficresvpl,"%.0f ",age ); 3742: for(i=1; i<=nlstate;i++) 3743: fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age])); 3744: fprintf(ficresvpl,"\n"); 3745: free_vector(gp,1,nlstate); 3746: free_vector(gm,1,nlstate); 3747: free_matrix(gradg,1,npar,1,nlstate); 3748: free_matrix(trgradg,1,nlstate,1,npar); 3749: } /* End age */ 3750: 3751: free_vector(xp,1,npar); 3752: free_matrix(doldm,1,nlstate,1,npar); 3753: free_matrix(dnewm,1,nlstate,1,nlstate); 3754: 3755: } 3756: 3757: /************ Variance of one-step probabilities ******************/ 3758: 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[]) 3759: { 3760: int i, j=0, k1, l1, tj; 3761: int k2, l2, j1, z1; 3762: int k=0, l; 3763: int first=1, first1, first2; 3764: double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp; 3765: double **dnewm,**doldm; 3766: double *xp; 3767: double *gp, *gm; 3768: double **gradg, **trgradg; 3769: double **mu; 3770: double age, cov[NCOVMAX+1]; 3771: double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */ 3772: int theta; 3773: char fileresprob[FILENAMELENGTH]; 3774: char fileresprobcov[FILENAMELENGTH]; 3775: char fileresprobcor[FILENAMELENGTH]; 3776: double ***varpij; 3777: 3778: strcpy(fileresprob,"prob"); 3779: strcat(fileresprob,fileres); 3780: if((ficresprob=fopen(fileresprob,"w"))==NULL) { 3781: printf("Problem with resultfile: %s\n", fileresprob); 3782: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob); 3783: } 3784: strcpy(fileresprobcov,"probcov"); 3785: strcat(fileresprobcov,fileres); 3786: if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) { 3787: printf("Problem with resultfile: %s\n", fileresprobcov); 3788: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov); 3789: } 3790: strcpy(fileresprobcor,"probcor"); 3791: strcat(fileresprobcor,fileres); 3792: if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) { 3793: printf("Problem with resultfile: %s\n", fileresprobcor); 3794: fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor); 3795: } 3796: printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob); 3797: fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob); 3798: printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov); 3799: fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov); 3800: printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor); 3801: fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor); 3802: pstamp(ficresprob); 3803: fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n"); 3804: fprintf(ficresprob,"# Age"); 3805: pstamp(ficresprobcov); 3806: fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n"); 3807: fprintf(ficresprobcov,"# Age"); 3808: pstamp(ficresprobcor); 3809: fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n"); 3810: fprintf(ficresprobcor,"# Age"); 3811: 3812: 3813: for(i=1; i<=nlstate;i++) 3814: for(j=1; j<=(nlstate+ndeath);j++){ 3815: fprintf(ficresprob," p%1d-%1d (SE)",i,j); 3816: fprintf(ficresprobcov," p%1d-%1d ",i,j); 3817: fprintf(ficresprobcor," p%1d-%1d ",i,j); 3818: } 3819: /* fprintf(ficresprob,"\n"); 3820: fprintf(ficresprobcov,"\n"); 3821: fprintf(ficresprobcor,"\n"); 3822: */ 3823: xp=vector(1,npar); 3824: dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar); 3825: doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath)); 3826: mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage); 3827: varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage); 3828: first=1; 3829: fprintf(ficgp,"\n# Routine varprob"); 3830: fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n"); 3831: fprintf(fichtm,"\n"); 3832: 3833: fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov); 3834: fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\ 3835: file %s<br>\n",optionfilehtmcov); 3836: fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\ 3837: and drawn. It helps understanding how is the covariance between two incidences.\ 3838: They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n"); 3839: 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. \ 3840: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \ 3841: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \ 3842: standard deviations wide on each axis. <br>\ 3843: Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\ 3844: and made the appropriate rotation to look at the uncorrelated principal directions.<br>\ 3845: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n"); 3846: 3847: cov[1]=1; 3848: /* tj=cptcoveff; */ 3849: tj = (int) pow(2,cptcoveff); 3850: if (cptcovn<1) {tj=1;ncodemax[1]=1;} 3851: j1=0; 3852: for(j1=1; j1<=tj;j1++){ 3853: /*for(i1=1; i1<=ncodemax[t];i1++){ */ 3854: /*j1++;*/ 3855: if (cptcovn>0) { 3856: fprintf(ficresprob, "\n#********** Variable "); 3857: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]); 3858: fprintf(ficresprob, "**********\n#\n"); 3859: fprintf(ficresprobcov, "\n#********** Variable "); 3860: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]); 3861: fprintf(ficresprobcov, "**********\n#\n"); 3862: 3863: fprintf(ficgp, "\n#********** Variable "); 3864: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]); 3865: fprintf(ficgp, "**********\n#\n"); 3866: 3867: 3868: fprintf(fichtmcov, "\n<hr size=\"2\" color=\"#EC5E5E\">********** Variable "); 3869: for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]); 3870: fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">"); 3871: 3872: fprintf(ficresprobcor, "\n#********** Variable "); 3873: for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]); 3874: fprintf(ficresprobcor, "**********\n#"); 3875: } 3876: 3877: gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath)); 3878: trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar); 3879: gp=vector(1,(nlstate)*(nlstate+ndeath)); 3880: gm=vector(1,(nlstate)*(nlstate+ndeath)); 3881: for (age=bage; age<=fage; age ++){ 3882: cov[2]=age; 3883: for (k=1; k<=cptcovn;k++) { 3884: cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4 3885: * 1 1 1 1 1 3886: * 2 2 1 1 1 3887: * 3 1 2 1 1 3888: */ 3889: /* nbcode[1][1]=0 nbcode[1][2]=1;*/ 3890: } 3891: for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; 3892: for (k=1; k<=cptcovprod;k++) 3893: cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]]; 3894: 3895: 3896: for(theta=1; theta <=npar; theta++){ 3897: for(i=1; i<=npar; i++) 3898: xp[i] = x[i] + (i==theta ?delti[theta]:(double)0); 3899: 3900: pmij(pmmij,cov,ncovmodel,xp,nlstate); 3901: 3902: k=0; 3903: for(i=1; i<= (nlstate); i++){ 3904: for(j=1; j<=(nlstate+ndeath);j++){ 3905: k=k+1; 3906: gp[k]=pmmij[i][j]; 3907: } 3908: } 3909: 3910: for(i=1; i<=npar; i++) 3911: xp[i] = x[i] - (i==theta ?delti[theta]:(double)0); 3912: 3913: pmij(pmmij,cov,ncovmodel,xp,nlstate); 3914: k=0; 3915: for(i=1; i<=(nlstate); i++){ 3916: for(j=1; j<=(nlstate+ndeath);j++){ 3917: k=k+1; 3918: gm[k]=pmmij[i][j]; 3919: } 3920: } 3921: 3922: for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 3923: gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta]; 3924: } 3925: 3926: for(j=1; j<=(nlstate)*(nlstate+ndeath);j++) 3927: for(theta=1; theta <=npar; theta++) 3928: trgradg[j][theta]=gradg[theta][j]; 3929: 3930: matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 3931: matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg); 3932: 3933: pmij(pmmij,cov,ncovmodel,x,nlstate); 3934: 3935: k=0; 3936: for(i=1; i<=(nlstate); i++){ 3937: for(j=1; j<=(nlstate+ndeath);j++){ 3938: k=k+1; 3939: mu[k][(int) age]=pmmij[i][j]; 3940: } 3941: } 3942: for(i=1;i<=(nlstate)*(nlstate+ndeath);i++) 3943: for(j=1;j<=(nlstate)*(nlstate+ndeath);j++) 3944: varpij[i][j][(int)age] = doldm[i][j]; 3945: 3946: /*printf("\n%d ",(int)age); 3947: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){ 3948: printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i])); 3949: fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i])); 3950: }*/ 3951: 3952: fprintf(ficresprob,"\n%d ",(int)age); 3953: fprintf(ficresprobcov,"\n%d ",(int)age); 3954: fprintf(ficresprobcor,"\n%d ",(int)age); 3955: 3956: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++) 3957: fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age])); 3958: for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){ 3959: fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]); 3960: fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]); 3961: } 3962: i=0; 3963: for (k=1; k<=(nlstate);k++){ 3964: for (l=1; l<=(nlstate+ndeath);l++){ 3965: i++; 3966: fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l); 3967: fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l); 3968: for (j=1; j<=i;j++){ 3969: /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */ 3970: fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]); 3971: fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age])); 3972: } 3973: } 3974: }/* end of loop for state */ 3975: } /* end of loop for age */ 3976: free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath)); 3977: free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath)); 3978: free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar); 3979: free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar); 3980: 3981: /* Confidence intervalle of pij */ 3982: /* 3983: fprintf(ficgp,"\nunset parametric;unset label"); 3984: fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\""); 3985: fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65"); 3986: 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); 3987: fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname); 3988: fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname); 3989: fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob); 3990: */ 3991: 3992: /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/ 3993: first1=1;first2=2; 3994: for (k2=1; k2<=(nlstate);k2++){ 3995: for (l2=1; l2<=(nlstate+ndeath);l2++){ 3996: if(l2==k2) continue; 3997: j=(k2-1)*(nlstate+ndeath)+l2; 3998: for (k1=1; k1<=(nlstate);k1++){ 3999: for (l1=1; l1<=(nlstate+ndeath);l1++){ 4000: if(l1==k1) continue; 4001: i=(k1-1)*(nlstate+ndeath)+l1; 4002: if(i<=j) continue; 4003: for (age=bage; age<=fage; age ++){ 4004: if ((int)age %5==0){ 4005: v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM; 4006: v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM; 4007: cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM; 4008: mu1=mu[i][(int) age]/stepm*YEARM ; 4009: mu2=mu[j][(int) age]/stepm*YEARM; 4010: c12=cv12/sqrt(v1*v2); 4011: /* Computing eigen value of matrix of covariance */ 4012: lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.; 4013: lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.; 4014: if ((lc2 <0) || (lc1 <0) ){ 4015: if(first2==1){ 4016: first1=0; 4017: 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); 4018: } 4019: 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); 4020: /* lc1=fabs(lc1); */ /* If we want to have them positive */ 4021: /* lc2=fabs(lc2); */ 4022: } 4023: 4024: /* Eigen vectors */ 4025: v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12)); 4026: /*v21=sqrt(1.-v11*v11); *//* error */ 4027: v21=(lc1-v1)/cv12*v11; 4028: v12=-v21; 4029: v22=v11; 4030: tnalp=v21/v11; 4031: if(first1==1){ 4032: first1=0; 4033: 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); 4034: } 4035: 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); 4036: /*printf(fignu*/ 4037: /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */ 4038: /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */ 4039: if(first==1){ 4040: first=0; 4041: fprintf(ficgp,"\nset parametric;unset label"); 4042: 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); 4043: fprintf(ficgp,"\nset ter png small size 320, 240"); 4044: fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\ 4045: :<a href=\"%s%d%1d%1d-%1d%1d.png\">\ 4046: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\ 4047: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\ 4048: subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2); 4049: fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2); 4050: fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12); 4051: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2); 4052: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2); 4053: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2); 4054: 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",\ 4055: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\ 4056: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2)); 4057: }else{ 4058: first=0; 4059: fprintf(fichtmcov," %d (%.3f),",(int) age, c12); 4060: fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2); 4061: fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2); 4062: 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",\ 4063: mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\ 4064: mu2,std,v21,sqrt(lc1),v22,sqrt(lc2)); 4065: }/* if first */ 4066: } /* age mod 5 */ 4067: } /* end loop age */ 4068: fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2); 4069: first=1; 4070: } /*l12 */ 4071: } /* k12 */ 4072: } /*l1 */ 4073: }/* k1 */ 4074: /* } */ /* loop covariates */ 4075: } 4076: free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage); 4077: free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage); 4078: free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath)); 4079: free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar); 4080: free_vector(xp,1,npar); 4081: fclose(ficresprob); 4082: fclose(ficresprobcov); 4083: fclose(ficresprobcor); 4084: fflush(ficgp); 4085: fflush(fichtmcov); 4086: } 4087: 4088: 4089: /******************* Printing html file ***********/ 4090: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \ 4091: int lastpass, int stepm, int weightopt, char model[],\ 4092: int imx,int jmin, int jmax, double jmeanint,char rfileres[],\ 4093: int popforecast, int estepm ,\ 4094: double jprev1, double mprev1,double anprev1, \ 4095: double jprev2, double mprev2,double anprev2){ 4096: int jj1, k1, i1, cpt; 4097: 4098: fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \ 4099: <li><a href='#secondorder'>Result files (second order (variance)</a>\n \ 4100: </ul>"); 4101: fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \ 4102: - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ", 4103: jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p")); 4104: fprintf(fichtm,"\ 4105: - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ", 4106: stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij")); 4107: fprintf(fichtm,"\ 4108: - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n", 4109: subdirf2(fileres,"pl"),subdirf2(fileres,"pl")); 4110: fprintf(fichtm,"\ 4111: - (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): \ 4112: <a href=\"%s\">%s</a> <br>\n", 4113: estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e")); 4114: fprintf(fichtm,"\ 4115: - Population projections by age and states: \ 4116: <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f")); 4117: 4118: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>"); 4119: 4120: m=pow(2,cptcoveff); 4121: if (cptcovn < 1) {m=1;ncodemax[1]=1;} 4122: 4123: jj1=0; 4124: for(k1=1; k1<=m;k1++){ 4125: for(i1=1; i1<=ncodemax[k1];i1++){ 4126: jj1++; 4127: if (cptcovn > 0) { 4128: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates"); 4129: for (cpt=1; cpt<=cptcoveff;cpt++) 4130: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]); 4131: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">"); 4132: } 4133: /* Pij */ 4134: 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> \ 4135: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1); 4136: /* Quasi-incidences */ 4137: fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\ 4138: 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> \ 4139: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1); 4140: /* Period (stable) prevalence in each health state */ 4141: for(cpt=1; cpt<=nlstate;cpt++){ 4142: 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> \ 4143: <img src=\"%s%d_%d.png\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1); 4144: } 4145: for(cpt=1; cpt<=nlstate;cpt++) { 4146: 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> \ 4147: <img src=\"%s%d%d.png\">",cpt,nlstate,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1); 4148: } 4149: } /* end i1 */ 4150: }/* End k1 */ 4151: fprintf(fichtm,"</ul>"); 4152: 4153: 4154: fprintf(fichtm,"\ 4155: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\ 4156: - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres); 4157: 4158: fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n", 4159: subdirf2(fileres,"prob"),subdirf2(fileres,"prob")); 4160: fprintf(fichtm,"\ 4161: - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n", 4162: subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov")); 4163: 4164: fprintf(fichtm,"\ 4165: - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n", 4166: subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor")); 4167: fprintf(fichtm,"\ 4168: - 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): \ 4169: <a href=\"%s\">%s</a> <br>\n</li>", 4170: estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve")); 4171: fprintf(fichtm,"\ 4172: - (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): \ 4173: <a href=\"%s\">%s</a> <br>\n</li>", 4174: estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde")); 4175: fprintf(fichtm,"\ 4176: - 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", 4177: estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v")); 4178: fprintf(fichtm,"\ 4179: - 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", 4180: estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t")); 4181: fprintf(fichtm,"\ 4182: - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\ 4183: subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl")); 4184: 4185: /* if(popforecast==1) fprintf(fichtm,"\n */ 4186: /* - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */ 4187: /* - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */ 4188: /* <br>",fileres,fileres,fileres,fileres); */ 4189: /* else */ 4190: /* 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); */ 4191: fflush(fichtm); 4192: fprintf(fichtm," <ul><li><b>Graphs</b></li><p>"); 4193: 4194: m=pow(2,cptcoveff); 4195: if (cptcovn < 1) {m=1;ncodemax[1]=1;} 4196: 4197: jj1=0; 4198: for(k1=1; k1<=m;k1++){ 4199: for(i1=1; i1<=ncodemax[k1];i1++){ 4200: jj1++; 4201: if (cptcovn > 0) { 4202: fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\">************ Results for covariates"); 4203: for (cpt=1; cpt<=cptcoveff;cpt++) 4204: fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]); 4205: fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">"); 4206: } 4207: for(cpt=1; cpt<=nlstate;cpt++) { 4208: fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \ 4209: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\ 4210: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1); 4211: } 4212: fprintf(fichtm,"\n<br>- Total life expectancy by age and \ 4213: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \ 4214: true period expectancies (those weighted with period prevalences are also\ 4215: drawn in addition to the population based expectancies computed using\ 4216: observed and cahotic prevalences: %s%d.png<br>\ 4217: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1); 4218: } /* end i1 */ 4219: }/* End k1 */ 4220: fprintf(fichtm,"</ul>"); 4221: fflush(fichtm); 4222: } 4223: 4224: /******************* Gnuplot file **************/ 4225: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){ 4226: 4227: char dirfileres[132],optfileres[132]; 4228: int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0; 4229: int ng=0; 4230: /* if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */ 4231: /* printf("Problem with file %s",optionfilegnuplot); */ 4232: /* fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */ 4233: /* } */ 4234: 4235: /*#ifdef windows */ 4236: fprintf(ficgp,"cd \"%s\" \n",pathc); 4237: /*#endif */ 4238: m=pow(2,cptcoveff); 4239: 4240: strcpy(dirfileres,optionfilefiname); 4241: strcpy(optfileres,"vpl"); 4242: /* 1eme*/ 4243: fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n"); 4244: for (cpt=1; cpt<= nlstate ; cpt ++) { 4245: for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */ 4246: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1); 4247: fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1); 4248: fprintf(ficgp,"set xlabel \"Age\" \n\ 4249: set ylabel \"Probability\" \n\ 4250: set ter png small size 320, 240\n\ 4251: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1); 4252: 4253: for (i=1; i<= nlstate ; i ++) { 4254: if (i==cpt) fprintf(ficgp," %%lf (%%lf)"); 4255: else fprintf(ficgp," %%*lf (%%*lf)"); 4256: } 4257: 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); 4258: for (i=1; i<= nlstate ; i ++) { 4259: if (i==cpt) fprintf(ficgp," %%lf (%%lf)"); 4260: else fprintf(ficgp," %%*lf (%%*lf)"); 4261: } 4262: 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); 4263: for (i=1; i<= nlstate ; i ++) { 4264: if (i==cpt) fprintf(ficgp," %%lf (%%lf)"); 4265: else fprintf(ficgp," %%*lf (%%*lf)"); 4266: } 4267: 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)); 4268: } 4269: } 4270: /*2 eme*/ 4271: fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n"); 4272: for (k1=1; k1<= m ; k1 ++) { 4273: fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1); 4274: fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage); 4275: 4276: for (i=1; i<= nlstate+1 ; i ++) { 4277: k=2*i; 4278: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1); 4279: for (j=1; j<= nlstate+1 ; j ++) { 4280: if (j==i) fprintf(ficgp," %%lf (%%lf)"); 4281: else fprintf(ficgp," %%*lf (%%*lf)"); 4282: } 4283: if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,"); 4284: else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1); 4285: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1); 4286: for (j=1; j<= nlstate+1 ; j ++) { 4287: if (j==i) fprintf(ficgp," %%lf (%%lf)"); 4288: else fprintf(ficgp," %%*lf (%%*lf)"); 4289: } 4290: fprintf(ficgp,"\" t\"\" w l lt 0,"); 4291: fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1); 4292: for (j=1; j<= nlstate+1 ; j ++) { 4293: if (j==i) fprintf(ficgp," %%lf (%%lf)"); 4294: else fprintf(ficgp," %%*lf (%%*lf)"); 4295: } 4296: if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0"); 4297: else fprintf(ficgp,"\" t\"\" w l lt 0,"); 4298: } 4299: } 4300: 4301: /*3eme*/ 4302: 4303: for (k1=1; k1<= m ; k1 ++) { 4304: for (cpt=1; cpt<= nlstate ; cpt ++) { 4305: /* k=2+nlstate*(2*cpt-2); */ 4306: k=2+(nlstate+1)*(cpt-1); 4307: fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1); 4308: fprintf(ficgp,"set ter png small size 320, 240\n\ 4309: 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); 4310: /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1); 4311: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) "); 4312: fprintf(ficgp,"\" t \"e%d1\" w l",cpt); 4313: fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1); 4314: for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) "); 4315: fprintf(ficgp,"\" t \"e%d1\" w l",cpt); 4316: 4317: */ 4318: for (i=1; i< nlstate ; i ++) { 4319: 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); 4320: /* 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);*/ 4321: 4322: } 4323: fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt); 4324: } 4325: } 4326: 4327: /* CV preval stable (period) */ 4328: for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */ 4329: for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */ 4330: k=3; 4331: fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt); 4332: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1); 4333: fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\ 4334: set ter png small size 320, 240\n\ 4335: unset log y\n\ 4336: plot [%.f:%.f] ", ageminpar, agemaxpar); 4337: for (i=1; i<= nlstate ; i ++){ 4338: if(i==1) 4339: fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij")); 4340: else 4341: fprintf(ficgp,", '' "); 4342: l=(nlstate+ndeath)*(i-1)+1; 4343: fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); 4344: for (j=1; j<= (nlstate-1) ; j ++) 4345: fprintf(ficgp,"+$%d",k+l+j); 4346: fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt); 4347: } /* nlstate */ 4348: fprintf(ficgp,"\n"); 4349: } /* end cpt state*/ 4350: } /* end covariate */ 4351: 4352: /* proba elementaires */ 4353: for(i=1,jk=1; i <=nlstate; i++){ 4354: for(k=1; k <=(nlstate+ndeath); k++){ 4355: if (k != i) { 4356: for(j=1; j <=ncovmodel; j++){ 4357: fprintf(ficgp,"p%d=%f ",jk,p[jk]); 4358: jk++; 4359: fprintf(ficgp,"\n"); 4360: } 4361: } 4362: } 4363: } 4364: /*goto avoid;*/ 4365: for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/ 4366: for(jk=1; jk <=m; jk++) { 4367: fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng); 4368: if (ng==2) 4369: fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n"); 4370: else 4371: fprintf(ficgp,"\nset title \"Probability\"\n"); 4372: fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot [%.f:%.f] ",ageminpar,agemaxpar); 4373: i=1; 4374: for(k2=1; k2<=nlstate; k2++) { 4375: k3=i; 4376: for(k=1; k<=(nlstate+ndeath); k++) { 4377: if (k != k2){ 4378: if(ng==2) 4379: fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1); 4380: else 4381: fprintf(ficgp," exp(p%d+p%d*x",i,i+1); 4382: ij=1;/* To be checked else nbcode[0][0] wrong */ 4383: for(j=3; j <=ncovmodel; j++) { 4384: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /\* Bug valgrind *\/ */ 4385: /* /\*fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);*\/ */ 4386: /* ij++; */ 4387: /* } */ 4388: /* else */ 4389: fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]); 4390: } 4391: fprintf(ficgp,")/(1"); 4392: 4393: for(k1=1; k1 <=nlstate; k1++){ 4394: fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1); 4395: ij=1; 4396: for(j=3; j <=ncovmodel; j++){ 4397: /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { */ 4398: /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]); */ 4399: /* ij++; */ 4400: /* } */ 4401: /* else */ 4402: fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]); 4403: } 4404: fprintf(ficgp,")"); 4405: } 4406: fprintf(ficgp,") t \"p%d%d\" ", k2,k); 4407: if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,","); 4408: i=i+ncovmodel; 4409: } 4410: } /* end k */ 4411: } /* end k2 */ 4412: } /* end jk */ 4413: } /* end ng */ 4414: /* avoid: */ 4415: fflush(ficgp); 4416: } /* end gnuplot */ 4417: 4418: 4419: /*************** Moving average **************/ 4420: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){ 4421: 4422: int i, cpt, cptcod; 4423: int modcovmax =1; 4424: int mobilavrange, mob; 4425: double age; 4426: 4427: modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 4428: a covariate has 2 modalities */ 4429: if (cptcovn<1) modcovmax=1; /* At least 1 pass */ 4430: 4431: if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){ 4432: if(mobilav==1) mobilavrange=5; /* default */ 4433: else mobilavrange=mobilav; 4434: for (age=bage; age<=fage; age++) 4435: for (i=1; i<=nlstate;i++) 4436: for (cptcod=1;cptcod<=modcovmax;cptcod++) 4437: mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod]; 4438: /* We keep the original values on the extreme ages bage, fage and for 4439: fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2 4440: we use a 5 terms etc. until the borders are no more concerned. 4441: */ 4442: for (mob=3;mob <=mobilavrange;mob=mob+2){ 4443: for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ 4444: for (i=1; i<=nlstate;i++){ 4445: for (cptcod=1;cptcod<=modcovmax;cptcod++){ 4446: mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod]; 4447: for (cpt=1;cpt<=(mob-1)/2;cpt++){ 4448: mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod]; 4449: mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod]; 4450: } 4451: mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob; 4452: } 4453: } 4454: }/* end age */ 4455: }/* end mob */ 4456: }else return -1; 4457: return 0; 4458: }/* End movingaverage */ 4459: 4460: 4461: /************** Forecasting ******************/ 4462: 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){ 4463: /* proj1, year, month, day of starting projection 4464: agemin, agemax range of age 4465: dateprev1 dateprev2 range of dates during which prevalence is computed 4466: anproj2 year of en of projection (same day and month as proj1). 4467: */ 4468: int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1; 4469: double agec; /* generic age */ 4470: double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean; 4471: double *popeffectif,*popcount; 4472: double ***p3mat; 4473: double ***mobaverage; 4474: char fileresf[FILENAMELENGTH]; 4475: 4476: agelim=AGESUP; 4477: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); 4478: 4479: strcpy(fileresf,"f"); 4480: strcat(fileresf,fileres); 4481: if((ficresf=fopen(fileresf,"w"))==NULL) { 4482: printf("Problem with forecast resultfile: %s\n", fileresf); 4483: fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf); 4484: } 4485: printf("Computing forecasting: result on file '%s' \n", fileresf); 4486: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf); 4487: 4488: if (cptcoveff==0) ncodemax[cptcoveff]=1; 4489: 4490: if (mobilav!=0) { 4491: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); 4492: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ 4493: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); 4494: printf(" Error in movingaverage mobilav=%d\n",mobilav); 4495: } 4496: } 4497: 4498: stepsize=(int) (stepm+YEARM-1)/YEARM; 4499: if (stepm<=12) stepsize=1; 4500: if(estepm < stepm){ 4501: printf ("Problem %d lower than %d\n",estepm, stepm); 4502: } 4503: else hstepm=estepm; 4504: 4505: hstepm=hstepm/stepm; 4506: yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp and 4507: fractional in yp1 */ 4508: anprojmean=yp; 4509: yp2=modf((yp1*12),&yp); 4510: mprojmean=yp; 4511: yp1=modf((yp2*30.5),&yp); 4512: jprojmean=yp; 4513: if(jprojmean==0) jprojmean=1; 4514: if(mprojmean==0) jprojmean=1; 4515: 4516: i1=cptcoveff; 4517: if (cptcovn < 1){i1=1;} 4518: 4519: fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 4520: 4521: fprintf(ficresf,"#****** Routine prevforecast **\n"); 4522: 4523: /* if (h==(int)(YEARM*yearp)){ */ 4524: for(cptcov=1, k=0;cptcov<=i1;cptcov++){ 4525: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ 4526: k=k+1; 4527: fprintf(ficresf,"\n#******"); 4528: for(j=1;j<=cptcoveff;j++) { 4529: 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]]); 4530: } 4531: fprintf(ficresf,"******\n"); 4532: fprintf(ficresf,"# Covariate valuofcovar yearproj age"); 4533: for(j=1; j<=nlstate+ndeath;j++){ 4534: for(i=1; i<=nlstate;i++) 4535: fprintf(ficresf," p%d%d",i,j); 4536: fprintf(ficresf," p.%d",j); 4537: } 4538: for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 4539: fprintf(ficresf,"\n"); 4540: fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp); 4541: 4542: for (agec=fage; agec>=(ageminpar-1); agec--){ 4543: nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 4544: nhstepm = nhstepm/hstepm; 4545: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); 4546: oldm=oldms;savm=savms; 4547: hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k); 4548: 4549: for (h=0; h<=nhstepm; h++){ 4550: if (h*hstepm/YEARM*stepm ==yearp) { 4551: fprintf(ficresf,"\n"); 4552: for(j=1;j<=cptcoveff;j++) 4553: fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]); 4554: fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm); 4555: } 4556: for(j=1; j<=nlstate+ndeath;j++) { 4557: ppij=0.; 4558: for(i=1; i<=nlstate;i++) { 4559: if (mobilav==1) 4560: ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod]; 4561: else { 4562: ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod]; 4563: } 4564: if (h*hstepm/YEARM*stepm== yearp) { 4565: fprintf(ficresf," %.3f", p3mat[i][j][h]); 4566: } 4567: } /* end i */ 4568: if (h*hstepm/YEARM*stepm==yearp) { 4569: fprintf(ficresf," %.3f", ppij); 4570: } 4571: }/* end j */ 4572: } /* end h */ 4573: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); 4574: } /* end agec */ 4575: } /* end yearp */ 4576: } /* end cptcod */ 4577: } /* end cptcov */ 4578: 4579: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); 4580: 4581: fclose(ficresf); 4582: } 4583: 4584: /************** Forecasting *****not tested NB*************/ 4585: 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){ 4586: 4587: int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; 4588: int *popage; 4589: double calagedatem, agelim, kk1, kk2; 4590: double *popeffectif,*popcount; 4591: double ***p3mat,***tabpop,***tabpopprev; 4592: double ***mobaverage; 4593: char filerespop[FILENAMELENGTH]; 4594: 4595: tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); 4596: tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); 4597: agelim=AGESUP; 4598: calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; 4599: 4600: prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); 4601: 4602: 4603: strcpy(filerespop,"pop"); 4604: strcat(filerespop,fileres); 4605: if((ficrespop=fopen(filerespop,"w"))==NULL) { 4606: printf("Problem with forecast resultfile: %s\n", filerespop); 4607: fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); 4608: } 4609: printf("Computing forecasting: result on file '%s' \n", filerespop); 4610: fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); 4611: 4612: if (cptcoveff==0) ncodemax[cptcoveff]=1; 4613: 4614: if (mobilav!=0) { 4615: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); 4616: if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ 4617: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); 4618: printf(" Error in movingaverage mobilav=%d\n",mobilav); 4619: } 4620: } 4621: 4622: stepsize=(int) (stepm+YEARM-1)/YEARM; 4623: if (stepm<=12) stepsize=1; 4624: 4625: agelim=AGESUP; 4626: 4627: hstepm=1; 4628: hstepm=hstepm/stepm; 4629: 4630: if (popforecast==1) { 4631: if((ficpop=fopen(popfile,"r"))==NULL) { 4632: printf("Problem with population file : %s\n",popfile);exit(0); 4633: fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); 4634: } 4635: popage=ivector(0,AGESUP); 4636: popeffectif=vector(0,AGESUP); 4637: popcount=vector(0,AGESUP); 4638: 4639: i=1; 4640: while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; 4641: 4642: imx=i; 4643: for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; 4644: } 4645: 4646: for(cptcov=1,k=0;cptcov<=i2;cptcov++){ 4647: for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ 4648: k=k+1; 4649: fprintf(ficrespop,"\n#******"); 4650: for(j=1;j<=cptcoveff;j++) { 4651: fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]); 4652: } 4653: fprintf(ficrespop,"******\n"); 4654: fprintf(ficrespop,"# Age"); 4655: for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); 4656: if (popforecast==1) fprintf(ficrespop," [Population]"); 4657: 4658: for (cpt=0; cpt<=0;cpt++) { 4659: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt); 4660: 4661: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 4662: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 4663: nhstepm = nhstepm/hstepm; 4664: 4665: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); 4666: oldm=oldms;savm=savms; 4667: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k); 4668: 4669: for (h=0; h<=nhstepm; h++){ 4670: if (h==(int) (calagedatem+YEARM*cpt)) { 4671: fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); 4672: } 4673: for(j=1; j<=nlstate+ndeath;j++) { 4674: kk1=0.;kk2=0; 4675: for(i=1; i<=nlstate;i++) { 4676: if (mobilav==1) 4677: kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; 4678: else { 4679: kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; 4680: } 4681: } 4682: if (h==(int)(calagedatem+12*cpt)){ 4683: tabpop[(int)(agedeb)][j][cptcod]=kk1; 4684: /*fprintf(ficrespop," %.3f", kk1); 4685: if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/ 4686: } 4687: } 4688: for(i=1; i<=nlstate;i++){ 4689: kk1=0.; 4690: for(j=1; j<=nlstate;j++){ 4691: kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 4692: } 4693: tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; 4694: } 4695: 4696: if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 4697: fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); 4698: } 4699: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); 4700: } 4701: } 4702: 4703: /******/ 4704: 4705: for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 4706: fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt); 4707: for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 4708: nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 4709: nhstepm = nhstepm/hstepm; 4710: 4711: p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); 4712: oldm=oldms;savm=savms; 4713: hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k); 4714: for (h=0; h<=nhstepm; h++){ 4715: if (h==(int) (calagedatem+YEARM*cpt)) { 4716: fprintf(ficresf,"\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: kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod]; 4722: } 4723: if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1); 4724: } 4725: } 4726: free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); 4727: } 4728: } 4729: } 4730: } 4731: 4732: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); 4733: 4734: if (popforecast==1) { 4735: free_ivector(popage,0,AGESUP); 4736: free_vector(popeffectif,0,AGESUP); 4737: free_vector(popcount,0,AGESUP); 4738: } 4739: free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); 4740: free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); 4741: fclose(ficrespop); 4742: } /* End of popforecast */ 4743: 4744: int fileappend(FILE *fichier, char *optionfich) 4745: { 4746: if((fichier=fopen(optionfich,"a"))==NULL) { 4747: printf("Problem with file: %s\n", optionfich); 4748: fprintf(ficlog,"Problem with file: %s\n", optionfich); 4749: return (0); 4750: } 4751: fflush(fichier); 4752: return (1); 4753: } 4754: 4755: 4756: /**************** function prwizard **********************/ 4757: void prwizard(int ncovmodel, int nlstate, int ndeath, char model[], FILE *ficparo) 4758: { 4759: 4760: /* Wizard to print covariance matrix template */ 4761: 4762: char ca[32], cb[32]; 4763: int i,j, k, li, lj, lk, ll, jj, npar, itimes; 4764: int numlinepar; 4765: 4766: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); 4767: fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); 4768: for(i=1; i <=nlstate; i++){ 4769: jj=0; 4770: for(j=1; j <=nlstate+ndeath; j++){ 4771: if(j==i) continue; 4772: jj++; 4773: /*ca[0]= k+'a'-1;ca[1]='\0';*/ 4774: printf("%1d%1d",i,j); 4775: fprintf(ficparo,"%1d%1d",i,j); 4776: for(k=1; k<=ncovmodel;k++){ 4777: /* printf(" %lf",param[i][j][k]); */ 4778: /* fprintf(ficparo," %lf",param[i][j][k]); */ 4779: printf(" 0."); 4780: fprintf(ficparo," 0."); 4781: } 4782: printf("\n"); 4783: fprintf(ficparo,"\n"); 4784: } 4785: } 4786: printf("# Scales (for hessian or gradient estimation)\n"); 4787: fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n"); 4788: npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 4789: for(i=1; i <=nlstate; i++){ 4790: jj=0; 4791: for(j=1; j <=nlstate+ndeath; j++){ 4792: if(j==i) continue; 4793: jj++; 4794: fprintf(ficparo,"%1d%1d",i,j); 4795: printf("%1d%1d",i,j); 4796: fflush(stdout); 4797: for(k=1; k<=ncovmodel;k++){ 4798: /* printf(" %le",delti3[i][j][k]); */ 4799: /* fprintf(ficparo," %le",delti3[i][j][k]); */ 4800: printf(" 0."); 4801: fprintf(ficparo," 0."); 4802: } 4803: numlinepar++; 4804: printf("\n"); 4805: fprintf(ficparo,"\n"); 4806: } 4807: } 4808: printf("# Covariance matrix\n"); 4809: /* # 121 Var(a12)\n\ */ 4810: /* # 122 Cov(b12,a12) Var(b12)\n\ */ 4811: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */ 4812: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */ 4813: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */ 4814: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */ 4815: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */ 4816: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */ 4817: fflush(stdout); 4818: fprintf(ficparo,"# Covariance matrix\n"); 4819: /* # 121 Var(a12)\n\ */ 4820: /* # 122 Cov(b12,a12) Var(b12)\n\ */ 4821: /* # ...\n\ */ 4822: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */ 4823: 4824: for(itimes=1;itimes<=2;itimes++){ 4825: jj=0; 4826: for(i=1; i <=nlstate; i++){ 4827: for(j=1; j <=nlstate+ndeath; j++){ 4828: if(j==i) continue; 4829: for(k=1; k<=ncovmodel;k++){ 4830: jj++; 4831: ca[0]= k+'a'-1;ca[1]='\0'; 4832: if(itimes==1){ 4833: printf("#%1d%1d%d",i,j,k); 4834: fprintf(ficparo,"#%1d%1d%d",i,j,k); 4835: }else{ 4836: printf("%1d%1d%d",i,j,k); 4837: fprintf(ficparo,"%1d%1d%d",i,j,k); 4838: /* printf(" %.5le",matcov[i][j]); */ 4839: } 4840: ll=0; 4841: for(li=1;li <=nlstate; li++){ 4842: for(lj=1;lj <=nlstate+ndeath; lj++){ 4843: if(lj==li) continue; 4844: for(lk=1;lk<=ncovmodel;lk++){ 4845: ll++; 4846: if(ll<=jj){ 4847: cb[0]= lk +'a'-1;cb[1]='\0'; 4848: if(ll<jj){ 4849: if(itimes==1){ 4850: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj); 4851: fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj); 4852: }else{ 4853: printf(" 0."); 4854: fprintf(ficparo," 0."); 4855: } 4856: }else{ 4857: if(itimes==1){ 4858: printf(" Var(%s%1d%1d)",ca,i,j); 4859: fprintf(ficparo," Var(%s%1d%1d)",ca,i,j); 4860: }else{ 4861: printf(" 0."); 4862: fprintf(ficparo," 0."); 4863: } 4864: } 4865: } 4866: } /* end lk */ 4867: } /* end lj */ 4868: } /* end li */ 4869: printf("\n"); 4870: fprintf(ficparo,"\n"); 4871: numlinepar++; 4872: } /* end k*/ 4873: } /*end j */ 4874: } /* end i */ 4875: } /* end itimes */ 4876: 4877: } /* end of prwizard */ 4878: /******************* Gompertz Likelihood ******************************/ 4879: double gompertz(double x[]) 4880: { 4881: double A,B,L=0.0,sump=0.,num=0.; 4882: int i,n=0; /* n is the size of the sample */ 4883: 4884: for (i=0;i<=imx-1 ; i++) { 4885: sump=sump+weight[i]; 4886: /* sump=sump+1;*/ 4887: num=num+1; 4888: } 4889: 4890: 4891: /* for (i=0; i<=imx; i++) 4892: 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]);*/ 4893: 4894: for (i=1;i<=imx ; i++) 4895: { 4896: if (cens[i] == 1 && wav[i]>1) 4897: A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp))); 4898: 4899: if (cens[i] == 0 && wav[i]>1) 4900: A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp))) 4901: +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM); 4902: 4903: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */ 4904: if (wav[i] > 1 ) { /* ??? */ 4905: L=L+A*weight[i]; 4906: /* 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]);*/ 4907: } 4908: } 4909: 4910: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/ 4911: 4912: return -2*L*num/sump; 4913: } 4914: 4915: #ifdef GSL 4916: /******************* Gompertz_f Likelihood ******************************/ 4917: double gompertz_f(const gsl_vector *v, void *params) 4918: { 4919: double A,B,LL=0.0,sump=0.,num=0.; 4920: double *x= (double *) v->data; 4921: int i,n=0; /* n is the size of the sample */ 4922: 4923: for (i=0;i<=imx-1 ; i++) { 4924: sump=sump+weight[i]; 4925: /* sump=sump+1;*/ 4926: num=num+1; 4927: } 4928: 4929: 4930: /* for (i=0; i<=imx; i++) 4931: 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]);*/ 4932: printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]); 4933: for (i=1;i<=imx ; i++) 4934: { 4935: if (cens[i] == 1 && wav[i]>1) 4936: A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp))); 4937: 4938: if (cens[i] == 0 && wav[i]>1) 4939: A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp))) 4940: +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM); 4941: 4942: /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */ 4943: if (wav[i] > 1 ) { /* ??? */ 4944: LL=LL+A*weight[i]; 4945: /* 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]);*/ 4946: } 4947: } 4948: 4949: /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/ 4950: printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump); 4951: 4952: return -2*LL*num/sump; 4953: } 4954: #endif 4955: 4956: /******************* Printing html file ***********/ 4957: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \ 4958: int lastpass, int stepm, int weightopt, char model[],\ 4959: int imx, double p[],double **matcov,double agemortsup){ 4960: int i,k; 4961: 4962: fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>"); 4963: fprintf(fichtm," mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp); 4964: for (i=1;i<=2;i++) 4965: 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])); 4966: fprintf(fichtm,"<br><br><img src=\"graphmort.png\">"); 4967: fprintf(fichtm,"</ul>"); 4968: 4969: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>"); 4970: 4971: 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>"); 4972: 4973: for (k=agegomp;k<(agemortsup-2);k++) 4974: 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]); 4975: 4976: 4977: fflush(fichtm); 4978: } 4979: 4980: /******************* Gnuplot file **************/ 4981: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){ 4982: 4983: char dirfileres[132],optfileres[132]; 4984: 4985: int ng; 4986: 4987: 4988: /*#ifdef windows */ 4989: fprintf(ficgp,"cd \"%s\" \n",pathc); 4990: /*#endif */ 4991: 4992: 4993: strcpy(dirfileres,optionfilefiname); 4994: strcpy(optfileres,"vpl"); 4995: fprintf(ficgp,"set out \"graphmort.png\"\n "); 4996: fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 4997: fprintf(ficgp, "set ter png small size 320, 240\n set log y\n"); 4998: /* fprintf(ficgp, "set size 0.65,0.65\n"); */ 4999: fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp); 5000: 5001: } 5002: 5003: int readdata(char datafile[], int firstobs, int lastobs, int *imax) 5004: { 5005: 5006: /*-------- data file ----------*/ 5007: FILE *fic; 5008: char dummy[]=" "; 5009: int i=0, j=0, n=0; 5010: int linei, month, year,iout; 5011: char line[MAXLINE], linetmp[MAXLINE]; 5012: char stra[MAXLINE], strb[MAXLINE]; 5013: char *stratrunc; 5014: int lstra; 5015: 5016: 5017: if((fic=fopen(datafile,"r"))==NULL) { 5018: printf("Problem while opening datafile: %s\n", datafile);return 1; 5019: fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1; 5020: } 5021: 5022: i=1; 5023: linei=0; 5024: while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) { 5025: linei=linei+1; 5026: for(j=strlen(line); j>=0;j--){ /* Untabifies line */ 5027: if(line[j] == '\t') 5028: line[j] = ' '; 5029: } 5030: for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){ 5031: ; 5032: }; 5033: line[j+1]=0; /* Trims blanks at end of line */ 5034: if(line[0]=='#'){ 5035: fprintf(ficlog,"Comment line\n%s\n",line); 5036: printf("Comment line\n%s\n",line); 5037: continue; 5038: } 5039: trimbb(linetmp,line); /* Trims multiple blanks in line */ 5040: strcpy(line, linetmp); 5041: 5042: 5043: for (j=maxwav;j>=1;j--){ 5044: cutv(stra, strb, line, ' '); 5045: if(strb[0]=='.') { /* Missing status */ 5046: lval=-1; 5047: }else{ 5048: errno=0; 5049: lval=strtol(strb,&endptr,10); 5050: /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/ 5051: if( strb[0]=='\0' || (*endptr != '\0')){ 5052: 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); 5053: 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); 5054: return 1; 5055: } 5056: } 5057: s[j][i]=lval; 5058: 5059: strcpy(line,stra); 5060: cutv(stra, strb,line,' '); 5061: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){ 5062: } 5063: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){ 5064: month=99; 5065: year=9999; 5066: }else{ 5067: 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); 5068: 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); 5069: return 1; 5070: } 5071: anint[j][i]= (double) year; 5072: mint[j][i]= (double)month; 5073: strcpy(line,stra); 5074: } /* ENd Waves */ 5075: 5076: cutv(stra, strb,line,' '); 5077: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){ 5078: } 5079: else if( (iout=sscanf(strb,"%s.",dummy)) != 0){ 5080: month=99; 5081: year=9999; 5082: }else{ 5083: 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); 5084: 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); 5085: return 1; 5086: } 5087: andc[i]=(double) year; 5088: moisdc[i]=(double) month; 5089: strcpy(line,stra); 5090: 5091: cutv(stra, strb,line,' '); 5092: if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){ 5093: } 5094: else if( (iout=sscanf(strb,"%s.", dummy)) != 0){ 5095: month=99; 5096: year=9999; 5097: }else{ 5098: 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); 5099: 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); 5100: return 1; 5101: } 5102: if (year==9999) { 5103: 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); 5104: 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); 5105: return 1; 5106: 5107: } 5108: annais[i]=(double)(year); 5109: moisnais[i]=(double)(month); 5110: strcpy(line,stra); 5111: 5112: cutv(stra, strb,line,' '); 5113: errno=0; 5114: dval=strtod(strb,&endptr); 5115: if( strb[0]=='\0' || (*endptr != '\0')){ 5116: printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight. Exiting.\n",dval, i,line,linei); 5117: 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); 5118: fflush(ficlog); 5119: return 1; 5120: } 5121: weight[i]=dval; 5122: strcpy(line,stra); 5123: 5124: for (j=ncovcol;j>=1;j--){ 5125: cutv(stra, strb,line,' '); 5126: if(strb[0]=='.') { /* Missing status */ 5127: lval=-1; 5128: }else{ 5129: errno=0; 5130: lval=strtol(strb,&endptr,10); 5131: if( strb[0]=='\0' || (*endptr != '\0')){ 5132: 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); 5133: 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); 5134: return 1; 5135: } 5136: } 5137: if(lval <-1 || lval >1){ 5138: printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \ 5139: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \ 5140: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \ 5141: For example, for multinomial values like 1, 2 and 3,\n \ 5142: build V1=0 V2=0 for the reference value (1),\n \ 5143: V1=1 V2=0 for (2) \n \ 5144: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \ 5145: output of IMaCh is often meaningless.\n \ 5146: Exiting.\n",lval,linei, i,line,j); 5147: fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \ 5148: Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \ 5149: for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \ 5150: For example, for multinomial values like 1, 2 and 3,\n \ 5151: build V1=0 V2=0 for the reference value (1),\n \ 5152: V1=1 V2=0 for (2) \n \ 5153: and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \ 5154: output of IMaCh is often meaningless.\n \ 5155: Exiting.\n",lval,linei, i,line,j);fflush(ficlog); 5156: return 1; 5157: } 5158: covar[j][i]=(double)(lval); 5159: strcpy(line,stra); 5160: } 5161: lstra=strlen(stra); 5162: 5163: if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */ 5164: stratrunc = &(stra[lstra-9]); 5165: num[i]=atol(stratrunc); 5166: } 5167: else 5168: num[i]=atol(stra); 5169: /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){ 5170: 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;}*/ 5171: 5172: i=i+1; 5173: } /* End loop reading data */ 5174: 5175: *imax=i-1; /* Number of individuals */ 5176: fclose(fic); 5177: 5178: return (0); 5179: /* endread: */ 5180: printf("Exiting readdata: "); 5181: fclose(fic); 5182: return (1); 5183: 5184: 5185: 5186: } 5187: void removespace(char *str) { 5188: char *p1 = str, *p2 = str; 5189: do 5190: while (*p2 == ' ') 5191: p2++; 5192: while (*p1++ == *p2++); 5193: } 5194: 5195: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns: 5196: * Model V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age 5197: * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 5198: * - cptcovn or number of covariates k of the models excluding age*products =6 5199: * - cptcovage number of covariates with age*products =2 5200: * - cptcovs number of simple covariates 5201: * - 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 5202: * which is a new column after the 9 (ncovcol) variables. 5203: * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual 5204: * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage 5205: * Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6. 5206: * - Tvard[k] p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 . 5207: */ 5208: { 5209: int i, j, k, ks; 5210: int j1, k1, k2; 5211: char modelsav[80]; 5212: char stra[80], strb[80], strc[80], strd[80],stre[80]; 5213: 5214: /*removespace(model);*/ 5215: if (strlen(model) >1){ /* If there is at least 1 covariate */ 5216: j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0; 5217: j=nbocc(model,'+'); /**< j=Number of '+' */ 5218: j1=nbocc(model,'*'); /**< j1=Number of '*' */ 5219: cptcovs=j+1-j1; /**< Number of simple covariates V1+V2*age+V3 +V3*V4=> V1 + V3 =2 */ 5220: cptcovt= j+1; /* Number of total covariates in the model V1 + V2*age+ V3 + V3*V4=> 4*/ 5221: /* including age products which are counted in cptcovage. 5222: * but the covariates which are products must be treated separately: ncovn=4- 2=2 (V1+V3). */ 5223: cptcovprod=j1; /**< Number of products V1*V2 +v3*age = 2 */ 5224: cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1 */ 5225: strcpy(modelsav,model); 5226: if (strstr(model,"AGE") !=0){ 5227: printf("Error. AGE must be in lower case 'age' model=%s ",model); 5228: fprintf(ficlog,"Error. AGE must be in lower case model=%s ",model);fflush(ficlog); 5229: return 1; 5230: } 5231: if (strstr(model,"v") !=0){ 5232: printf("Error. 'v' must be in upper case 'V' model=%s ",model); 5233: fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog); 5234: return 1; 5235: } 5236: 5237: /* Design 5238: * V1 V2 V3 V4 V5 V6 V7 V8 V9 Weight 5239: * < ncovcol=8 > 5240: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 5241: * k= 1 2 3 4 5 6 7 8 5242: * cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8 5243: * covar[k,i], value of kth covariate if not including age for individual i: 5244: * covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8) 5245: * Tvar[k] # of the kth covariate: Tvar[1]=2 Tvar[4]=3 Tvar[8]=8 5246: * if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 5247: * Tage[++cptcovage]=k 5248: * if products, new covar are created after ncovcol with k1 5249: * Tvar[k]=ncovcol+k1; # of the kth covariate product: Tvar[5]=ncovcol+1=10 Tvar[6]=ncovcol+1=11 5250: * Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product 5251: * 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 5252: * Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2]; 5253: * Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted 5254: * V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 5255: * < ncovcol=8 > 5256: * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 d1 d1 d2 d2 5257: * k= 1 2 3 4 5 6 7 8 9 10 11 12 5258: * Tvar[k]= 2 1 3 3 10 11 8 8 5 6 7 8 5259: * p Tvar[1]@12={2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6} 5260: * p Tprod[1]@2={ 6, 5} 5261: *p Tvard[1][1]@4= {7, 8, 5, 6} 5262: * covar[k][i]= V2 V1 ? V3 V5*V6? V7*V8? ? V8 5263: * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; 5264: *How to reorganize? 5265: * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age 5266: * Tvars {2, 1, 3, 3, 11, 10, 8, 8, 7, 8, 5, 6} 5267: * {2, 1, 4, 8, 5, 6, 3, 7} 5268: * Struct [] 5269: */ 5270: 5271: /* This loop fills the array Tvar from the string 'model'.*/ 5272: /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */ 5273: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 */ 5274: /* k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */ 5275: /* k=3 V4 Tvar[k=3]= 4 (from V4) */ 5276: /* k=2 V1 Tvar[k=2]= 1 (from V1) */ 5277: /* k=1 Tvar[1]=2 (from V2) */ 5278: /* k=5 Tvar[5] */ 5279: /* for (k=1; k<=cptcovn;k++) { */ 5280: /* cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */ 5281: /* } */ 5282: /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */ 5283: /* 5284: * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */ 5285: for(k=cptcovt; k>=1;k--) /**< Number of covariates */ 5286: Tvar[k]=0; 5287: cptcovage=0; 5288: for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */ 5289: cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 5290: modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 5291: if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */ 5292: /* printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/ 5293: /*scanf("%d",i);*/ 5294: if (strchr(strb,'*')) { /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */ 5295: cutl(strc,strd,strb,'*'); /**< strd*strc Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */ 5296: if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */ 5297: /* covar is not filled and then is empty */ 5298: cptcovprod--; 5299: cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */ 5300: Tvar[k]=atoi(stre); /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2 */ 5301: cptcovage++; /* Sums the number of covariates which include age as a product */ 5302: Tage[cptcovage]=k; /* Tage[1] = 4 */ 5303: /*printf("stre=%s ", stre);*/ 5304: } else if (strcmp(strd,"age")==0) { /* or age*Vn */ 5305: cptcovprod--; 5306: cutl(stre,strb,strc,'V'); 5307: Tvar[k]=atoi(stre); 5308: cptcovage++; 5309: Tage[cptcovage]=k; 5310: } else { /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2 strb=V3*V2*/ 5311: /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */ 5312: cptcovn++; 5313: cptcovprodnoage++;k1++; 5314: cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/ 5315: Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but 5316: because this model-covariate is a construction we invent a new column 5317: ncovcol + k1 5318: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2 5319: Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */ 5320: cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */ 5321: Tprod[k1]=k; /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 */ 5322: Tvard[k1][1] =atoi(strc); /* m 1 for V1*/ 5323: Tvard[k1][2] =atoi(stre); /* n 4 for V4*/ 5324: k2=k2+2; 5325: Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */ 5326: Tvar[cptcovt+k2+1]=Tvard[k1][2]; /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */ 5327: for (i=1; i<=lastobs;i++){ 5328: /* Computes the new covariate which is a product of 5329: covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */ 5330: covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i]; 5331: } 5332: } /* End age is not in the model */ 5333: } /* End if model includes a product */ 5334: else { /* no more sum */ 5335: /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/ 5336: /* scanf("%d",i);*/ 5337: cutl(strd,strc,strb,'V'); 5338: ks++; /**< Number of simple covariates */ 5339: cptcovn++; 5340: Tvar[k]=atoi(strd); 5341: } 5342: strcpy(modelsav,stra); /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 5343: /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav); 5344: scanf("%d",i);*/ 5345: } /* end of loop + */ 5346: } /* end model */ 5347: 5348: /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products. 5349: If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/ 5350: 5351: /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]); 5352: printf("cptcovprod=%d ", cptcovprod); 5353: fprintf(ficlog,"cptcovprod=%d ", cptcovprod); 5354: 5355: scanf("%d ",i);*/ 5356: 5357: 5358: return (0); /* with covar[new additional covariate if product] and Tage if age */ 5359: /*endread:*/ 5360: printf("Exiting decodemodel: "); 5361: return (1); 5362: } 5363: 5364: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn ) 5365: { 5366: int i, m; 5367: 5368: for (i=1; i<=imx; i++) { 5369: for(m=2; (m<= maxwav); m++) { 5370: if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){ 5371: anint[m][i]=9999; 5372: s[m][i]=-1; 5373: } 5374: if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){ 5375: *nberr = *nberr + 1; 5376: 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); 5377: 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); 5378: s[m][i]=-1; 5379: } 5380: if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){ 5381: (*nberr)++; 5382: 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]); 5383: 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]); 5384: s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */ 5385: } 5386: } 5387: } 5388: 5389: for (i=1; i<=imx; i++) { 5390: agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]); 5391: for(m=firstpass; (m<= lastpass); m++){ 5392: if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){ 5393: if (s[m][i] >= nlstate+1) { 5394: if(agedc[i]>0){ 5395: if((int)moisdc[i]!=99 && (int)andc[i]!=9999){ 5396: agev[m][i]=agedc[i]; 5397: /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/ 5398: }else { 5399: if ((int)andc[i]!=9999){ 5400: nbwarn++; 5401: printf("Warning negative age at death: %ld line:%d\n",num[i],i); 5402: fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i); 5403: agev[m][i]=-1; 5404: } 5405: } 5406: } /* agedc > 0 */ 5407: } 5408: else if(s[m][i] !=9){ /* Standard case, age in fractional 5409: years but with the precision of a month */ 5410: agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]); 5411: if((int)mint[m][i]==99 || (int)anint[m][i]==9999) 5412: agev[m][i]=1; 5413: else if(agev[m][i] < *agemin){ 5414: *agemin=agev[m][i]; 5415: printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin); 5416: } 5417: else if(agev[m][i] >*agemax){ 5418: *agemax=agev[m][i]; 5419: /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/ 5420: } 5421: /*agev[m][i]=anint[m][i]-annais[i];*/ 5422: /* agev[m][i] = age[i]+2*m;*/ 5423: } 5424: else { /* =9 */ 5425: agev[m][i]=1; 5426: s[m][i]=-1; 5427: } 5428: } 5429: else /*= 0 Unknown */ 5430: agev[m][i]=1; 5431: } 5432: 5433: } 5434: for (i=1; i<=imx; i++) { 5435: for(m=firstpass; (m<=lastpass); m++){ 5436: if (s[m][i] > (nlstate+ndeath)) { 5437: (*nberr)++; 5438: 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); 5439: 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); 5440: return 1; 5441: } 5442: } 5443: } 5444: 5445: /*for (i=1; i<=imx; i++){ 5446: for (m=firstpass; (m<lastpass); m++){ 5447: printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]); 5448: } 5449: 5450: }*/ 5451: 5452: 5453: printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 5454: fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 5455: 5456: return (0); 5457: /* endread:*/ 5458: printf("Exiting calandcheckages: "); 5459: return (1); 5460: } 5461: 5462: #if defined(_MSC_VER) 5463: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/ 5464: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/ 5465: //#include "stdafx.h" 5466: //#include <stdio.h> 5467: //#include <tchar.h> 5468: //#include <windows.h> 5469: //#include <iostream> 5470: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL); 5471: 5472: LPFN_ISWOW64PROCESS fnIsWow64Process; 5473: 5474: BOOL IsWow64() 5475: { 5476: BOOL bIsWow64 = FALSE; 5477: 5478: //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS) 5479: // (HANDLE, PBOOL); 5480: 5481: //LPFN_ISWOW64PROCESS fnIsWow64Process; 5482: 5483: HMODULE module = GetModuleHandle(_T("kernel32")); 5484: const char funcName[] = "IsWow64Process"; 5485: fnIsWow64Process = (LPFN_ISWOW64PROCESS) 5486: GetProcAddress(module, funcName); 5487: 5488: if (NULL != fnIsWow64Process) 5489: { 5490: if (!fnIsWow64Process(GetCurrentProcess(), 5491: &bIsWow64)) 5492: //throw std::exception("Unknown error"); 5493: printf("Unknown error\n"); 5494: } 5495: return bIsWow64 != FALSE; 5496: } 5497: #endif 5498: void syscompilerinfo() 5499: { 5500: /* #include "syscompilerinfo.h"*/ 5501: /* #include <gnu/libc-version.h> */ /* Only on gnu */ 5502: #include <stdint.h> 5503: printf("Compiled with:");fprintf(ficlog,"Compiled with:"); 5504: #if defined(__clang__) 5505: printf(" Clang/LLVM");fprintf(ficlog," Clang/LLVM"); /* Clang/LLVM. ---------------------------------------------- */ 5506: #endif 5507: #if defined(__ICC) || defined(__INTEL_COMPILER) 5508: printf(" Intel ICC/ICPC");fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */ 5509: #endif 5510: #if defined(__GNUC__) || defined(__GNUG__) 5511: printf(" GNU GCC/G++");fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */ 5512: #endif 5513: #if defined(__HP_cc) || defined(__HP_aCC) 5514: printf(" Hewlett-Packard C/aC++");fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */ 5515: #endif 5516: #if defined(__IBMC__) || defined(__IBMCPP__) 5517: printf(" IBM XL C/C++"); fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */ 5518: #endif 5519: #if defined(_MSC_VER) 5520: printf(" Microsoft Visual Studio");fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */ 5521: #endif 5522: #if defined(__PGI) 5523: printf(" Portland Group PGCC/PGCPP");fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */ 5524: #endif 5525: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC) 5526: printf(" Oracle Solaris Studio");fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */ 5527: #endif 5528: printf(". ");fprintf(ficlog,". "); 5529: 5530: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros 5531: #ifdef _WIN32 // note the underscore: without it, it's not msdn official! 5532: // Windows (x64 and x86) 5533: printf("Windows (x64 and x86). ");fprintf(ficlog,"Windows (x64 and x86). "); 5534: #elif __unix__ // all unices, not all compilers 5535: // Unix 5536: printf("Unix. ");fprintf(ficlog,"Unix. "); 5537: #elif __linux__ 5538: // linux 5539: printf("linux. ");fprintf(ficlog,"linux. "); 5540: #elif __APPLE__ 5541: // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though... 5542: printf("Mac OS. ");fprintf(ficlog,"Mac OS. "); 5543: #endif 5544: 5545: /* __MINGW32__ */ 5546: /* __CYGWIN__ */ 5547: /* __MINGW64__ */ 5548: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx 5549: /* _MSC_VER //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /? */ 5550: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */ 5551: /* _WIN64 // Defined for applications for Win64. */ 5552: /* _M_X64 // Defined for compilations that target x64 processors. */ 5553: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */ 5554: 5555: #if UINTPTR_MAX == 0xffffffff 5556: printf(" 32-bit.\n"); fprintf(ficlog," 32-bit.\n");/* 32-bit */ 5557: #elif UINTPTR_MAX == 0xffffffffffffffff 5558: printf(" 64-bit.\n"); fprintf(ficlog," 64-bit.\n");/* 64-bit */ 5559: #else 5560: printf(" wtf-bit.\n"); fprintf(ficlog," wtf-bit.\n");/* wtf */ 5561: #endif 5562: 5563: /* struct utsname sysInfo; 5564: 5565: if (uname(&sysInfo) != -1) { 5566: printf(" %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine); 5567: fprintf(ficlog," %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine); 5568: } 5569: else 5570: perror("uname() error"); 5571: */ 5572: #if defined(__GNUC__) 5573: # if defined(__GNUC_PATCHLEVEL__) 5574: # define __GNUC_VERSION__ (__GNUC__ * 10000 \ 5575: + __GNUC_MINOR__ * 100 \ 5576: + __GNUC_PATCHLEVEL__) 5577: # else 5578: # define __GNUC_VERSION__ (__GNUC__ * 10000 \ 5579: + __GNUC_MINOR__ * 100) 5580: # endif 5581: printf("GNU C version %d.\n", __GNUC_VERSION__); 5582: fprintf(ficlog, "GNU C version %d.\n", __GNUC_VERSION__); 5583: #endif 5584: 5585: // void main() 5586: // { 5587: #if defined(_MSC_VER) 5588: if (IsWow64()) 5589: printf("The process is running under WOW64.\n"); 5590: else 5591: printf("The process is not running under WOW64.\n"); 5592: 5593: // printf("\nPress Enter to continue..."); 5594: // getchar(); 5595: // } 5596: 5597: #endif 5598: 5599: /* printf("GNU libc version: %s\n", gnu_get_libc_version()); */ 5600: 5601: } 5602: 5603: /***********************************************/ 5604: /**************** Main Program *****************/ 5605: /***********************************************/ 5606: 5607: int main(int argc, char *argv[]) 5608: { 5609: #ifdef GSL 5610: const gsl_multimin_fminimizer_type *T; 5611: size_t iteri = 0, it; 5612: int rval = GSL_CONTINUE; 5613: int status = GSL_SUCCESS; 5614: double ssval; 5615: #endif 5616: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav); 5617: int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; 5618: 5619: int jj, ll, li, lj, lk; 5620: int numlinepar=0; /* Current linenumber of parameter file */ 5621: int itimes; 5622: int NDIM=2; 5623: int vpopbased=0; 5624: 5625: char ca[32], cb[32]; 5626: /* FILE *fichtm; *//* Html File */ 5627: /* FILE *ficgp;*/ /*Gnuplot File */ 5628: struct stat info; 5629: double agedeb; 5630: double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20; 5631: 5632: double fret; 5633: double dum; /* Dummy variable */ 5634: double ***p3mat; 5635: double ***mobaverage; 5636: 5637: char line[MAXLINE]; 5638: char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE]; 5639: char pathr[MAXLINE], pathimach[MAXLINE]; 5640: char *tok, *val; /* pathtot */ 5641: int firstobs=1, lastobs=10; 5642: int c, h , cpt; 5643: int jl; 5644: int i1, j1, jk, stepsize; 5645: int *tab; 5646: int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */ 5647: int mobilav=0,popforecast=0; 5648: int hstepm, nhstepm; 5649: int agemortsup; 5650: float sumlpop=0.; 5651: double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000; 5652: double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000; 5653: 5654: double bage=0, fage=110, age, agelim, agebase; 5655: double ftolpl=FTOL; 5656: double **prlim; 5657: double ***param; /* Matrix of parameters */ 5658: double *p; 5659: double **matcov; /* Matrix of covariance */ 5660: double ***delti3; /* Scale */ 5661: double *delti; /* Scale */ 5662: double ***eij, ***vareij; 5663: double **varpl; /* Variances of prevalence limits by age */ 5664: double *epj, vepp; 5665: 5666: double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000; 5667: double **ximort; 5668: char *alph[]={"a","a","b","c","d","e"}, str[4]="1234"; 5669: int *dcwave; 5670: 5671: char z[1]="c"; 5672: 5673: /*char *strt;*/ 5674: char strtend[80]; 5675: 5676: 5677: /* setlocale (LC_ALL, ""); */ 5678: /* bindtextdomain (PACKAGE, LOCALEDIR); */ 5679: /* textdomain (PACKAGE); */ 5680: /* setlocale (LC_CTYPE, ""); */ 5681: /* setlocale (LC_MESSAGES, ""); */ 5682: 5683: /* gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */ 5684: rstart_time = time(NULL); 5685: /* (void) gettimeofday(&start_time,&tzp);*/ 5686: start_time = *localtime(&rstart_time); 5687: curr_time=start_time; 5688: /*tml = *localtime(&start_time.tm_sec);*/ 5689: /* strcpy(strstart,asctime(&tml)); */ 5690: strcpy(strstart,asctime(&start_time)); 5691: 5692: /* printf("Localtime (at start)=%s",strstart); */ 5693: /* tp.tm_sec = tp.tm_sec +86400; */ 5694: /* tm = *localtime(&start_time.tm_sec); */ 5695: /* tmg.tm_year=tmg.tm_year +dsign*dyear; */ 5696: /* tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */ 5697: /* tmg.tm_hour=tmg.tm_hour + 1; */ 5698: /* tp.tm_sec = mktime(&tmg); */ 5699: /* strt=asctime(&tmg); */ 5700: /* printf("Time(after) =%s",strstart); */ 5701: /* (void) time (&time_value); 5702: * printf("time=%d,t-=%d\n",time_value,time_value-86400); 5703: * tm = *localtime(&time_value); 5704: * strstart=asctime(&tm); 5705: * printf("tim_value=%d,asctime=%s\n",time_value,strstart); 5706: */ 5707: 5708: nberr=0; /* Number of errors and warnings */ 5709: nbwarn=0; 5710: getcwd(pathcd, size); 5711: 5712: printf("\n%s\n%s",version,fullversion); 5713: if(argc <=1){ 5714: printf("\nEnter the parameter file name: "); 5715: fgets(pathr,FILENAMELENGTH,stdin); 5716: i=strlen(pathr); 5717: if(pathr[i-1]=='\n') 5718: pathr[i-1]='\0'; 5719: i=strlen(pathr); 5720: if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */ 5721: pathr[i-1]='\0'; 5722: for (tok = pathr; tok != NULL; ){ 5723: printf("Pathr |%s|\n",pathr); 5724: while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0'); 5725: printf("val= |%s| pathr=%s\n",val,pathr); 5726: strcpy (pathtot, val); 5727: if(pathr[0] == '\0') break; /* Dirty */ 5728: } 5729: } 5730: else{ 5731: strcpy(pathtot,argv[1]); 5732: } 5733: /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/ 5734: /*cygwin_split_path(pathtot,path,optionfile); 5735: printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/ 5736: /* cutv(path,optionfile,pathtot,'\\');*/ 5737: 5738: /* Split argv[0], imach program to get pathimach */ 5739: printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]); 5740: split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname); 5741: printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname); 5742: /* strcpy(pathimach,argv[0]); */ 5743: /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */ 5744: split(pathtot,path,optionfile,optionfilext,optionfilefiname); 5745: printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname); 5746: chdir(path); /* Can be a relative path */ 5747: if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */ 5748: printf("Current directory %s!\n",pathcd); 5749: strcpy(command,"mkdir "); 5750: strcat(command,optionfilefiname); 5751: if((outcmd=system(command)) != 0){ 5752: printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd); 5753: /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */ 5754: /* fclose(ficlog); */ 5755: /* exit(1); */ 5756: } 5757: /* if((imk=mkdir(optionfilefiname))<0){ */ 5758: /* perror("mkdir"); */ 5759: /* } */ 5760: 5761: /*-------- arguments in the command line --------*/ 5762: 5763: /* Log file */ 5764: strcat(filelog, optionfilefiname); 5765: strcat(filelog,".log"); /* */ 5766: if((ficlog=fopen(filelog,"w"))==NULL) { 5767: printf("Problem with logfile %s\n",filelog); 5768: goto end; 5769: } 5770: fprintf(ficlog,"Log filename:%s\n",filelog); 5771: fprintf(ficlog,"\n%s\n%s",version,fullversion); 5772: fprintf(ficlog,"\nEnter the parameter file name: \n"); 5773: fprintf(ficlog,"pathimach=%s\npathtot=%s\n\ 5774: path=%s \n\ 5775: optionfile=%s\n\ 5776: optionfilext=%s\n\ 5777: optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname); 5778: 5779: syscompilerinfo(); 5780: 5781: printf("Local time (at start):%s",strstart); 5782: fprintf(ficlog,"Local time (at start): %s",strstart); 5783: fflush(ficlog); 5784: /* (void) gettimeofday(&curr_time,&tzp); */ 5785: /* printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */ 5786: 5787: /* */ 5788: strcpy(fileres,"r"); 5789: strcat(fileres, optionfilefiname); 5790: strcat(fileres,".txt"); /* Other files have txt extension */ 5791: 5792: /*---------arguments file --------*/ 5793: 5794: if((ficpar=fopen(optionfile,"r"))==NULL) { 5795: printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno)); 5796: fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno)); 5797: fflush(ficlog); 5798: /* goto end; */ 5799: exit(70); 5800: } 5801: 5802: 5803: 5804: strcpy(filereso,"o"); 5805: strcat(filereso,fileres); 5806: if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */ 5807: printf("Problem with Output resultfile: %s\n", filereso); 5808: fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso); 5809: fflush(ficlog); 5810: goto end; 5811: } 5812: 5813: /* Reads comments: lines beginning with '#' */ 5814: numlinepar=0; 5815: while((c=getc(ficpar))=='#' && c!= EOF){ 5816: ungetc(c,ficpar); 5817: fgets(line, MAXLINE, ficpar); 5818: numlinepar++; 5819: fputs(line,stdout); 5820: fputs(line,ficparo); 5821: fputs(line,ficlog); 5822: } 5823: ungetc(c,ficpar); 5824: 5825: 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); 5826: numlinepar++; 5827: 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); 5828: 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); 5829: 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); 5830: fflush(ficlog); 5831: while((c=getc(ficpar))=='#' && c!= EOF){ 5832: ungetc(c,ficpar); 5833: fgets(line, MAXLINE, ficpar); 5834: numlinepar++; 5835: fputs(line, stdout); 5836: //puts(line); 5837: fputs(line,ficparo); 5838: fputs(line,ficlog); 5839: } 5840: ungetc(c,ficpar); 5841: 5842: 5843: covar=matrix(0,NCOVMAX,1,n); /**< used in readdata */ 5844: cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/ 5845: /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5 5846: v1+v2*age+v2*v3 makes cptcovn = 3 5847: */ 5848: if (strlen(model)>1) 5849: 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*/ 5850: else 5851: ncovmodel=2; 5852: nvar=ncovmodel-1; /* Suppressing age as a basic covariate */ 5853: nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */ 5854: npar= nforce*ncovmodel; /* Number of parameters like aij*/ 5855: if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){ 5856: 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); 5857: 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); 5858: fflush(stdout); 5859: fclose (ficlog); 5860: goto end; 5861: } 5862: delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); 5863: delti=delti3[1][1]; 5864: /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/ 5865: if(mle==-1){ /* Print a wizard for help writing covariance matrix */ 5866: prwizard(ncovmodel, nlstate, ndeath, model, ficparo); 5867: printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso); 5868: fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso); 5869: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 5870: fclose (ficparo); 5871: fclose (ficlog); 5872: goto end; 5873: exit(0); 5874: } 5875: else if(mle==-3) { 5876: prwizard(ncovmodel, nlstate, ndeath, model, ficparo); 5877: printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso); 5878: fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso); 5879: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); 5880: matcov=matrix(1,npar,1,npar); 5881: } 5882: else{ 5883: /* Read guessed parameters */ 5884: /* Reads comments: lines beginning with '#' */ 5885: while((c=getc(ficpar))=='#' && c!= EOF){ 5886: ungetc(c,ficpar); 5887: fgets(line, MAXLINE, ficpar); 5888: numlinepar++; 5889: fputs(line,stdout); 5890: fputs(line,ficparo); 5891: fputs(line,ficlog); 5892: } 5893: ungetc(c,ficpar); 5894: 5895: param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); 5896: for(i=1; i <=nlstate; i++){ 5897: j=0; 5898: for(jj=1; jj <=nlstate+ndeath; jj++){ 5899: if(jj==i) continue; 5900: j++; 5901: fscanf(ficpar,"%1d%1d",&i1,&j1); 5902: if ((i1 != i) && (j1 != j)){ 5903: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \ 5904: It might be a problem of design; if ncovcol and the model are correct\n \ 5905: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1); 5906: exit(1); 5907: } 5908: fprintf(ficparo,"%1d%1d",i1,j1); 5909: if(mle==1) 5910: printf("%1d%1d",i,j); 5911: fprintf(ficlog,"%1d%1d",i,j); 5912: for(k=1; k<=ncovmodel;k++){ 5913: fscanf(ficpar," %lf",¶m[i][j][k]); 5914: if(mle==1){ 5915: printf(" %lf",param[i][j][k]); 5916: fprintf(ficlog," %lf",param[i][j][k]); 5917: } 5918: else 5919: fprintf(ficlog," %lf",param[i][j][k]); 5920: fprintf(ficparo," %lf",param[i][j][k]); 5921: } 5922: fscanf(ficpar,"\n"); 5923: numlinepar++; 5924: if(mle==1) 5925: printf("\n"); 5926: fprintf(ficlog,"\n"); 5927: fprintf(ficparo,"\n"); 5928: } 5929: } 5930: fflush(ficlog); 5931: 5932: /* Reads scales values */ 5933: p=param[1][1]; 5934: 5935: /* Reads comments: lines beginning with '#' */ 5936: while((c=getc(ficpar))=='#' && c!= EOF){ 5937: ungetc(c,ficpar); 5938: fgets(line, MAXLINE, ficpar); 5939: numlinepar++; 5940: fputs(line,stdout); 5941: fputs(line,ficparo); 5942: fputs(line,ficlog); 5943: } 5944: ungetc(c,ficpar); 5945: 5946: for(i=1; i <=nlstate; i++){ 5947: for(j=1; j <=nlstate+ndeath-1; j++){ 5948: fscanf(ficpar,"%1d%1d",&i1,&j1); 5949: if ( (i1-i) * (j1-j) != 0){ 5950: printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1); 5951: exit(1); 5952: } 5953: printf("%1d%1d",i,j); 5954: fprintf(ficparo,"%1d%1d",i1,j1); 5955: fprintf(ficlog,"%1d%1d",i1,j1); 5956: for(k=1; k<=ncovmodel;k++){ 5957: fscanf(ficpar,"%le",&delti3[i][j][k]); 5958: printf(" %le",delti3[i][j][k]); 5959: fprintf(ficparo," %le",delti3[i][j][k]); 5960: fprintf(ficlog," %le",delti3[i][j][k]); 5961: } 5962: fscanf(ficpar,"\n"); 5963: numlinepar++; 5964: printf("\n"); 5965: fprintf(ficparo,"\n"); 5966: fprintf(ficlog,"\n"); 5967: } 5968: } 5969: fflush(ficlog); 5970: 5971: /* Reads covariance matrix */ 5972: delti=delti3[1][1]; 5973: 5974: 5975: /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */ 5976: 5977: /* Reads comments: lines beginning with '#' */ 5978: while((c=getc(ficpar))=='#' && c!= EOF){ 5979: ungetc(c,ficpar); 5980: fgets(line, MAXLINE, ficpar); 5981: numlinepar++; 5982: fputs(line,stdout); 5983: fputs(line,ficparo); 5984: fputs(line,ficlog); 5985: } 5986: ungetc(c,ficpar); 5987: 5988: matcov=matrix(1,npar,1,npar); 5989: for(i=1; i <=npar; i++) 5990: for(j=1; j <=npar; j++) matcov[i][j]=0.; 5991: 5992: for(i=1; i <=npar; i++){ 5993: fscanf(ficpar,"%s",str); 5994: if(mle==1) 5995: printf("%s",str); 5996: fprintf(ficlog,"%s",str); 5997: fprintf(ficparo,"%s",str); 5998: for(j=1; j <=i; j++){ 5999: fscanf(ficpar," %le",&matcov[i][j]); 6000: if(mle==1){ 6001: printf(" %.5le",matcov[i][j]); 6002: } 6003: fprintf(ficlog," %.5le",matcov[i][j]); 6004: fprintf(ficparo," %.5le",matcov[i][j]); 6005: } 6006: fscanf(ficpar,"\n"); 6007: numlinepar++; 6008: if(mle==1) 6009: printf("\n"); 6010: fprintf(ficlog,"\n"); 6011: fprintf(ficparo,"\n"); 6012: } 6013: for(i=1; i <=npar; i++) 6014: for(j=i+1;j<=npar;j++) 6015: matcov[i][j]=matcov[j][i]; 6016: 6017: if(mle==1) 6018: printf("\n"); 6019: fprintf(ficlog,"\n"); 6020: 6021: fflush(ficlog); 6022: 6023: /*-------- Rewriting parameter file ----------*/ 6024: strcpy(rfileres,"r"); /* "Rparameterfile */ 6025: strcat(rfileres,optionfilefiname); /* Parameter file first name*/ 6026: strcat(rfileres,"."); /* */ 6027: strcat(rfileres,optionfilext); /* Other files have txt extension */ 6028: if((ficres =fopen(rfileres,"w"))==NULL) { 6029: printf("Problem writing new parameter file: %s\n", fileres);goto end; 6030: fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end; 6031: } 6032: fprintf(ficres,"#%s\n",version); 6033: } /* End of mle != -3 */ 6034: 6035: 6036: n= lastobs; 6037: num=lvector(1,n); 6038: moisnais=vector(1,n); 6039: annais=vector(1,n); 6040: moisdc=vector(1,n); 6041: andc=vector(1,n); 6042: agedc=vector(1,n); 6043: cod=ivector(1,n); 6044: weight=vector(1,n); 6045: for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */ 6046: mint=matrix(1,maxwav,1,n); 6047: anint=matrix(1,maxwav,1,n); 6048: s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 6049: tab=ivector(1,NCOVMAX); 6050: ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */ 6051: 6052: /* Reads data from file datafile */ 6053: if (readdata(datafile, firstobs, lastobs, &imx)==1) 6054: goto end; 6055: 6056: /* Calculation of the number of parameters from char model */ 6057: /* modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 6058: k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4 6059: k=3 V4 Tvar[k=3]= 4 (from V4) 6060: k=2 V1 Tvar[k=2]= 1 (from V1) 6061: k=1 Tvar[1]=2 (from V2) 6062: */ 6063: Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */ 6064: /* V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 6065: For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 6066: Tvar[4=age*V3] is 3 and 'age' is recorded in Tage. 6067: */ 6068: /* For model-covariate k tells which data-covariate to use but 6069: because this model-covariate is a construction we invent a new column 6070: ncovcol + k1 6071: If already ncovcol=4 and model=V2+V1+V1*V4+age*V3 6072: Tvar[3=V1*V4]=4+1 etc */ 6073: Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */ 6074: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3 6075: if V2+V1+V1*V4+age*V3+V3*V2 TProd[k1=2]=5 (V3*V2) 6076: */ 6077: Tvaraff=ivector(1,NCOVMAX); /* Unclear */ 6078: 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 6079: * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 6080: * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */ 6081: Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age 6082: 4 covariates (3 plus signs) 6083: Tage[1=V3*age]= 4; Tage[2=age*V4] = 3 6084: */ 6085: 6086: if(decodemodel(model, lastobs) == 1) 6087: goto end; 6088: 6089: if((double)(lastobs-imx)/(double)imx > 1.10){ 6090: nbwarn++; 6091: 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); 6092: 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); 6093: } 6094: /* if(mle==1){*/ 6095: if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/ 6096: for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */ 6097: } 6098: 6099: /*-calculation of age at interview from date of interview and age at death -*/ 6100: agev=matrix(1,maxwav,1,imx); 6101: 6102: if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1) 6103: goto end; 6104: 6105: 6106: agegomp=(int)agemin; 6107: free_vector(moisnais,1,n); 6108: free_vector(annais,1,n); 6109: /* free_matrix(mint,1,maxwav,1,n); 6110: free_matrix(anint,1,maxwav,1,n);*/ 6111: free_vector(moisdc,1,n); 6112: free_vector(andc,1,n); 6113: /* */ 6114: 6115: wav=ivector(1,imx); 6116: dh=imatrix(1,lastpass-firstpass+1,1,imx); 6117: bh=imatrix(1,lastpass-firstpass+1,1,imx); 6118: mw=imatrix(1,lastpass-firstpass+1,1,imx); 6119: 6120: /* Concatenates waves */ 6121: concatwav(wav, dh, bh, mw, s, agedc, agev, firstpass, lastpass, imx, nlstate, stepm); 6122: /* */ 6123: 6124: /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */ 6125: 6126: nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 6127: ncodemax[1]=1; 6128: Ndum =ivector(-1,NCOVMAX); 6129: if (ncovmodel > 2) 6130: tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */ 6131: 6132: codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */ 6133: /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/ 6134: h=0; 6135: 6136: 6137: /*if (cptcovn > 0) */ 6138: 6139: 6140: m=pow(2,cptcoveff); 6141: 6142: for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */ 6143: 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 */ 6144: for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/ 6145: for(cpt=1; cpt <=pow(2,k-1); cpt++){ /* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 */ 6146: h++; 6147: if (h>m) 6148: h=1; 6149: /**< codtab(h,k) k = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1 6150: * h 1 2 3 4 6151: *______________________________ 6152: * 1 i=1 1 i=1 1 i=1 1 i=1 1 6153: * 2 2 1 1 1 6154: * 3 i=2 1 2 1 1 6155: * 4 2 2 1 1 6156: * 5 i=3 1 i=2 1 2 1 6157: * 6 2 1 2 1 6158: * 7 i=4 1 2 2 1 6159: * 8 2 2 2 1 6160: * 9 i=5 1 i=3 1 i=2 1 1 6161: * 10 2 1 1 1 6162: * 11 i=6 1 2 1 1 6163: * 12 2 2 1 1 6164: * 13 i=7 1 i=4 1 2 1 6165: * 14 2 1 2 1 6166: * 15 i=8 1 2 2 1 6167: * 16 2 2 2 1 6168: */ 6169: codtab[h][k]=j; 6170: /*codtab[h][Tvar[k]]=j;*/ 6171: 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]]); 6172: } 6173: } 6174: } 6175: } 6176: /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 6177: codtab[1][2]=1;codtab[2][2]=2; */ 6178: /* for(i=1; i <=m ;i++){ 6179: for(k=1; k <=cptcovn; k++){ 6180: printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff); 6181: } 6182: printf("\n"); 6183: } 6184: scanf("%d",i);*/ 6185: 6186: free_ivector(Ndum,-1,NCOVMAX); 6187: 6188: 6189: 6190: /*------------ gnuplot -------------*/ 6191: strcpy(optionfilegnuplot,optionfilefiname); 6192: if(mle==-3) 6193: strcat(optionfilegnuplot,"-mort"); 6194: strcat(optionfilegnuplot,".gp"); 6195: 6196: if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) { 6197: printf("Problem with file %s",optionfilegnuplot); 6198: } 6199: else{ 6200: fprintf(ficgp,"\n# %s\n", version); 6201: fprintf(ficgp,"# %s\n", optionfilegnuplot); 6202: //fprintf(ficgp,"set missing 'NaNq'\n"); 6203: fprintf(ficgp,"set datafile missing 'NaNq'\n"); 6204: } 6205: /* fclose(ficgp);*/ 6206: /*--------- index.htm --------*/ 6207: 6208: strcpy(optionfilehtm,optionfilefiname); /* Main html file */ 6209: if(mle==-3) 6210: strcat(optionfilehtm,"-mort"); 6211: strcat(optionfilehtm,".htm"); 6212: if((fichtm=fopen(optionfilehtm,"w"))==NULL) { 6213: printf("Problem with %s \n",optionfilehtm); 6214: exit(0); 6215: } 6216: 6217: strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */ 6218: strcat(optionfilehtmcov,"-cov.htm"); 6219: if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL) { 6220: printf("Problem with %s \n",optionfilehtmcov), exit(0); 6221: } 6222: else{ 6223: fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \ 6224: <hr size=\"2\" color=\"#EC5E5E\"> \n\ 6225: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\ 6226: optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model); 6227: } 6228: 6229: fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \ 6230: <hr size=\"2\" color=\"#EC5E5E\"> \n\ 6231: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\ 6232: \n\ 6233: <hr size=\"2\" color=\"#EC5E5E\">\ 6234: <ul><li><h4>Parameter files</h4>\n\ 6235: - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\ 6236: - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\ 6237: - Log file of the run: <a href=\"%s\">%s</a><br>\n\ 6238: - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\ 6239: - Date and time at start: %s</ul>\n",\ 6240: optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\ 6241: optionfilefiname,optionfilext,optionfilefiname,optionfilext,\ 6242: fileres,fileres,\ 6243: filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart); 6244: fflush(fichtm); 6245: 6246: strcpy(pathr,path); 6247: strcat(pathr,optionfilefiname); 6248: chdir(optionfilefiname); /* Move to directory named optionfile */ 6249: 6250: /* Calculates basic frequencies. Computes observed prevalence at single age 6251: and prints on file fileres'p'. */ 6252: freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart); 6253: 6254: fprintf(fichtm,"\n"); 6255: fprintf(fichtm,"<br>Total number of observations=%d <br>\n\ 6256: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\ 6257: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\ 6258: imx,agemin,agemax,jmin,jmax,jmean); 6259: pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */ 6260: oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */ 6261: newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */ 6262: savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */ 6263: oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */ 6264: 6265: 6266: /* For Powell, parameters are in a vector p[] starting at p[1] 6267: so we point p on param[1][1] so that p[1] maps on param[1][1][1] */ 6268: p=param[1][1]; /* *(*(*(param +1)+1)+0) */ 6269: 6270: globpr=0; /* To get the number ipmx of contributions and the sum of weights*/ 6271: 6272: if (mle==-3){ 6273: ximort=matrix(1,NDIM,1,NDIM); 6274: /* ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */ 6275: cens=ivector(1,n); 6276: ageexmed=vector(1,n); 6277: agecens=vector(1,n); 6278: dcwave=ivector(1,n); 6279: 6280: for (i=1; i<=imx; i++){ 6281: dcwave[i]=-1; 6282: for (m=firstpass; m<=lastpass; m++) 6283: if (s[m][i]>nlstate) { 6284: dcwave[i]=m; 6285: /* printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/ 6286: break; 6287: } 6288: } 6289: 6290: for (i=1; i<=imx; i++) { 6291: if (wav[i]>0){ 6292: ageexmed[i]=agev[mw[1][i]][i]; 6293: j=wav[i]; 6294: agecens[i]=1.; 6295: 6296: if (ageexmed[i]> 1 && wav[i] > 0){ 6297: agecens[i]=agev[mw[j][i]][i]; 6298: cens[i]= 1; 6299: }else if (ageexmed[i]< 1) 6300: cens[i]= -1; 6301: if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass) 6302: cens[i]=0 ; 6303: } 6304: else cens[i]=-1; 6305: } 6306: 6307: for (i=1;i<=NDIM;i++) { 6308: for (j=1;j<=NDIM;j++) 6309: ximort[i][j]=(i == j ? 1.0 : 0.0); 6310: } 6311: 6312: /*p[1]=0.0268; p[NDIM]=0.083;*/ 6313: /*printf("%lf %lf", p[1], p[2]);*/ 6314: 6315: 6316: #ifdef GSL 6317: printf("GSL optimization\n"); fprintf(ficlog,"Powell\n"); 6318: #else 6319: printf("Powell\n"); fprintf(ficlog,"Powell\n"); 6320: #endif 6321: strcpy(filerespow,"pow-mort"); 6322: strcat(filerespow,fileres); 6323: if((ficrespow=fopen(filerespow,"w"))==NULL) { 6324: printf("Problem with resultfile: %s\n", filerespow); 6325: fprintf(ficlog,"Problem with resultfile: %s\n", filerespow); 6326: } 6327: #ifdef GSL 6328: fprintf(ficrespow,"# GSL optimization\n# iter -2*LL"); 6329: #else 6330: fprintf(ficrespow,"# Powell\n# iter -2*LL"); 6331: #endif 6332: /* for (i=1;i<=nlstate;i++) 6333: for(j=1;j<=nlstate+ndeath;j++) 6334: if(j!=i)fprintf(ficrespow," p%1d%1d",i,j); 6335: */ 6336: fprintf(ficrespow,"\n"); 6337: #ifdef GSL 6338: /* gsl starts here */ 6339: T = gsl_multimin_fminimizer_nmsimplex; 6340: gsl_multimin_fminimizer *sfm = NULL; 6341: gsl_vector *ss, *x; 6342: gsl_multimin_function minex_func; 6343: 6344: /* Initial vertex size vector */ 6345: ss = gsl_vector_alloc (NDIM); 6346: 6347: if (ss == NULL){ 6348: GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0); 6349: } 6350: /* Set all step sizes to 1 */ 6351: gsl_vector_set_all (ss, 0.001); 6352: 6353: /* Starting point */ 6354: 6355: x = gsl_vector_alloc (NDIM); 6356: 6357: if (x == NULL){ 6358: gsl_vector_free(ss); 6359: GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0); 6360: } 6361: 6362: /* Initialize method and iterate */ 6363: /* p[1]=0.0268; p[NDIM]=0.083; */ 6364: /* gsl_vector_set(x, 0, 0.0268); */ 6365: /* gsl_vector_set(x, 1, 0.083); */ 6366: gsl_vector_set(x, 0, p[1]); 6367: gsl_vector_set(x, 1, p[2]); 6368: 6369: minex_func.f = &gompertz_f; 6370: minex_func.n = NDIM; 6371: minex_func.params = (void *)&p; /* ??? */ 6372: 6373: sfm = gsl_multimin_fminimizer_alloc (T, NDIM); 6374: gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss); 6375: 6376: printf("Iterations beginning .....\n\n"); 6377: printf("Iter. # Intercept Slope -Log Likelihood Simplex size\n"); 6378: 6379: iteri=0; 6380: while (rval == GSL_CONTINUE){ 6381: iteri++; 6382: status = gsl_multimin_fminimizer_iterate(sfm); 6383: 6384: if (status) printf("error: %s\n", gsl_strerror (status)); 6385: fflush(0); 6386: 6387: if (status) 6388: break; 6389: 6390: rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6); 6391: ssval = gsl_multimin_fminimizer_size (sfm); 6392: 6393: if (rval == GSL_SUCCESS) 6394: printf ("converged to a local maximum at\n"); 6395: 6396: printf("%5d ", iteri); 6397: for (it = 0; it < NDIM; it++){ 6398: printf ("%10.5f ", gsl_vector_get (sfm->x, it)); 6399: } 6400: printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval); 6401: } 6402: 6403: printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n"); 6404: 6405: gsl_vector_free(x); /* initial values */ 6406: gsl_vector_free(ss); /* inital step size */ 6407: for (it=0; it<NDIM; it++){ 6408: p[it+1]=gsl_vector_get(sfm->x,it); 6409: fprintf(ficrespow," %.12lf", p[it]); 6410: } 6411: gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1) */ 6412: #endif 6413: #ifdef POWELL 6414: powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz); 6415: #endif 6416: fclose(ficrespow); 6417: 6418: hesscov(matcov, p, NDIM, delti, 1e-4, gompertz); 6419: 6420: for(i=1; i <=NDIM; i++) 6421: for(j=i+1;j<=NDIM;j++) 6422: matcov[i][j]=matcov[j][i]; 6423: 6424: printf("\nCovariance matrix\n "); 6425: for(i=1; i <=NDIM; i++) { 6426: for(j=1;j<=NDIM;j++){ 6427: printf("%f ",matcov[i][j]); 6428: } 6429: printf("\n "); 6430: } 6431: 6432: printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp); 6433: for (i=1;i<=NDIM;i++) 6434: printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i])); 6435: 6436: lsurv=vector(1,AGESUP); 6437: lpop=vector(1,AGESUP); 6438: tpop=vector(1,AGESUP); 6439: lsurv[agegomp]=100000; 6440: 6441: for (k=agegomp;k<=AGESUP;k++) { 6442: agemortsup=k; 6443: if (p[1]*exp(p[2]*(k-agegomp))>1) break; 6444: } 6445: 6446: for (k=agegomp;k<agemortsup;k++) 6447: lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp))); 6448: 6449: for (k=agegomp;k<agemortsup;k++){ 6450: lpop[k]=(lsurv[k]+lsurv[k+1])/2.; 6451: sumlpop=sumlpop+lpop[k]; 6452: } 6453: 6454: tpop[agegomp]=sumlpop; 6455: for (k=agegomp;k<(agemortsup-3);k++){ 6456: /* tpop[k+1]=2;*/ 6457: tpop[k+1]=tpop[k]-lpop[k]; 6458: } 6459: 6460: 6461: printf("\nAge lx qx dx Lx Tx e(x)\n"); 6462: for (k=agegomp;k<(agemortsup-2);k++) 6463: 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]); 6464: 6465: 6466: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */ 6467: printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p); 6468: 6469: printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \ 6470: stepm, weightopt,\ 6471: model,imx,p,matcov,agemortsup); 6472: 6473: free_vector(lsurv,1,AGESUP); 6474: free_vector(lpop,1,AGESUP); 6475: free_vector(tpop,1,AGESUP); 6476: #ifdef GSL 6477: free_ivector(cens,1,n); 6478: free_vector(agecens,1,n); 6479: free_ivector(dcwave,1,n); 6480: free_matrix(ximort,1,NDIM,1,NDIM); 6481: #endif 6482: } /* Endof if mle==-3 */ 6483: 6484: else{ /* For mle >=1 */ 6485: globpr=0;/* debug */ 6486: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */ 6487: printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw); 6488: for (k=1; k<=npar;k++) 6489: printf(" %d %8.5f",k,p[k]); 6490: printf("\n"); 6491: globpr=1; /* to print the contributions */ 6492: likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */ 6493: printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw); 6494: for (k=1; k<=npar;k++) 6495: printf(" %d %8.5f",k,p[k]); 6496: printf("\n"); 6497: if(mle>=1){ /* Could be 1 or 2 */ 6498: mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func); 6499: } 6500: 6501: /*--------- results files --------------*/ 6502: 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); 6503: 6504: 6505: fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); 6506: printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); 6507: fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); 6508: for(i=1,jk=1; i <=nlstate; i++){ 6509: for(k=1; k <=(nlstate+ndeath); k++){ 6510: if (k != i) { 6511: printf("%d%d ",i,k); 6512: fprintf(ficlog,"%d%d ",i,k); 6513: fprintf(ficres,"%1d%1d ",i,k); 6514: for(j=1; j <=ncovmodel; j++){ 6515: printf("%lf ",p[jk]); 6516: fprintf(ficlog,"%lf ",p[jk]); 6517: fprintf(ficres,"%lf ",p[jk]); 6518: jk++; 6519: } 6520: printf("\n"); 6521: fprintf(ficlog,"\n"); 6522: fprintf(ficres,"\n"); 6523: } 6524: } 6525: } 6526: if(mle!=0){ 6527: /* Computing hessian and covariance matrix */ 6528: ftolhess=ftol; /* Usually correct */ 6529: hesscov(matcov, p, npar, delti, ftolhess, func); 6530: } 6531: fprintf(ficres,"# Scales (for hessian or gradient estimation)\n"); 6532: printf("# Scales (for hessian or gradient estimation)\n"); 6533: fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n"); 6534: for(i=1,jk=1; i <=nlstate; i++){ 6535: for(j=1; j <=nlstate+ndeath; j++){ 6536: if (j!=i) { 6537: fprintf(ficres,"%1d%1d",i,j); 6538: printf("%1d%1d",i,j); 6539: fprintf(ficlog,"%1d%1d",i,j); 6540: for(k=1; k<=ncovmodel;k++){ 6541: printf(" %.5e",delti[jk]); 6542: fprintf(ficlog," %.5e",delti[jk]); 6543: fprintf(ficres," %.5e",delti[jk]); 6544: jk++; 6545: } 6546: printf("\n"); 6547: fprintf(ficlog,"\n"); 6548: fprintf(ficres,"\n"); 6549: } 6550: } 6551: } 6552: 6553: 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"); 6554: if(mle>=1) 6555: 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"); 6556: 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"); 6557: /* # 121 Var(a12)\n\ */ 6558: /* # 122 Cov(b12,a12) Var(b12)\n\ */ 6559: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */ 6560: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */ 6561: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */ 6562: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */ 6563: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */ 6564: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */ 6565: 6566: 6567: /* Just to have a covariance matrix which will be more understandable 6568: even is we still don't want to manage dictionary of variables 6569: */ 6570: for(itimes=1;itimes<=2;itimes++){ 6571: jj=0; 6572: for(i=1; i <=nlstate; i++){ 6573: for(j=1; j <=nlstate+ndeath; j++){ 6574: if(j==i) continue; 6575: for(k=1; k<=ncovmodel;k++){ 6576: jj++; 6577: ca[0]= k+'a'-1;ca[1]='\0'; 6578: if(itimes==1){ 6579: if(mle>=1) 6580: printf("#%1d%1d%d",i,j,k); 6581: fprintf(ficlog,"#%1d%1d%d",i,j,k); 6582: fprintf(ficres,"#%1d%1d%d",i,j,k); 6583: }else{ 6584: if(mle>=1) 6585: printf("%1d%1d%d",i,j,k); 6586: fprintf(ficlog,"%1d%1d%d",i,j,k); 6587: fprintf(ficres,"%1d%1d%d",i,j,k); 6588: } 6589: ll=0; 6590: for(li=1;li <=nlstate; li++){ 6591: for(lj=1;lj <=nlstate+ndeath; lj++){ 6592: if(lj==li) continue; 6593: for(lk=1;lk<=ncovmodel;lk++){ 6594: ll++; 6595: if(ll<=jj){ 6596: cb[0]= lk +'a'-1;cb[1]='\0'; 6597: if(ll<jj){ 6598: if(itimes==1){ 6599: if(mle>=1) 6600: printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj); 6601: fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj); 6602: fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj); 6603: }else{ 6604: if(mle>=1) 6605: printf(" %.5e",matcov[jj][ll]); 6606: fprintf(ficlog," %.5e",matcov[jj][ll]); 6607: fprintf(ficres," %.5e",matcov[jj][ll]); 6608: } 6609: }else{ 6610: if(itimes==1){ 6611: if(mle>=1) 6612: printf(" Var(%s%1d%1d)",ca,i,j); 6613: fprintf(ficlog," Var(%s%1d%1d)",ca,i,j); 6614: fprintf(ficres," Var(%s%1d%1d)",ca,i,j); 6615: }else{ 6616: if(mle>=1) 6617: printf(" %.5e",matcov[jj][ll]); 6618: fprintf(ficlog," %.5e",matcov[jj][ll]); 6619: fprintf(ficres," %.5e",matcov[jj][ll]); 6620: } 6621: } 6622: } 6623: } /* end lk */ 6624: } /* end lj */ 6625: } /* end li */ 6626: if(mle>=1) 6627: printf("\n"); 6628: fprintf(ficlog,"\n"); 6629: fprintf(ficres,"\n"); 6630: numlinepar++; 6631: } /* end k*/ 6632: } /*end j */ 6633: } /* end i */ 6634: } /* end itimes */ 6635: 6636: fflush(ficlog); 6637: fflush(ficres); 6638: 6639: while((c=getc(ficpar))=='#' && c!= EOF){ 6640: ungetc(c,ficpar); 6641: fgets(line, MAXLINE, ficpar); 6642: fputs(line,stdout); 6643: fputs(line,ficparo); 6644: } 6645: ungetc(c,ficpar); 6646: 6647: estepm=0; 6648: fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); 6649: if (estepm==0 || estepm < stepm) estepm=stepm; 6650: if (fage <= 2) { 6651: bage = ageminpar; 6652: fage = agemaxpar; 6653: } 6654: 6655: fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n"); 6656: fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm); 6657: fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm); 6658: 6659: while((c=getc(ficpar))=='#' && c!= EOF){ 6660: ungetc(c,ficpar); 6661: fgets(line, MAXLINE, ficpar); 6662: fputs(line,stdout); 6663: fputs(line,ficparo); 6664: } 6665: ungetc(c,ficpar); 6666: 6667: 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); 6668: 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); 6669: 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); 6670: printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav); 6671: 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); 6672: 6673: while((c=getc(ficpar))=='#' && c!= EOF){ 6674: ungetc(c,ficpar); 6675: fgets(line, MAXLINE, ficpar); 6676: fputs(line,stdout); 6677: fputs(line,ficparo); 6678: } 6679: ungetc(c,ficpar); 6680: 6681: 6682: dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.; 6683: dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.; 6684: 6685: fscanf(ficpar,"pop_based=%d\n",&popbased); 6686: fprintf(ficparo,"pop_based=%d\n",popbased); 6687: fprintf(ficres,"pop_based=%d\n",popbased); 6688: 6689: while((c=getc(ficpar))=='#' && c!= EOF){ 6690: ungetc(c,ficpar); 6691: fgets(line, MAXLINE, ficpar); 6692: fputs(line,stdout); 6693: fputs(line,ficparo); 6694: } 6695: ungetc(c,ficpar); 6696: 6697: 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); 6698: 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); 6699: 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); 6700: 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); 6701: 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); 6702: /* day and month of proj2 are not used but only year anproj2.*/ 6703: 6704: 6705: 6706: /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */ 6707: /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */ 6708: 6709: replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */ 6710: printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p); 6711: 6712: printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\ 6713: model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\ 6714: jprev1,mprev1,anprev1,jprev2,mprev2,anprev2); 6715: 6716: /*------------ free_vector -------------*/ 6717: /* chdir(path); */ 6718: 6719: free_ivector(wav,1,imx); 6720: free_imatrix(dh,1,lastpass-firstpass+1,1,imx); 6721: free_imatrix(bh,1,lastpass-firstpass+1,1,imx); 6722: free_imatrix(mw,1,lastpass-firstpass+1,1,imx); 6723: free_lvector(num,1,n); 6724: free_vector(agedc,1,n); 6725: /*free_matrix(covar,0,NCOVMAX,1,n);*/ 6726: /*free_matrix(covar,1,NCOVMAX,1,n);*/ 6727: fclose(ficparo); 6728: fclose(ficres); 6729: 6730: 6731: /*--------------- Prevalence limit (period or stable prevalence) --------------*/ 6732: #include "prevlim.h" /* Use ficrespl, ficlog */ 6733: fclose(ficrespl); 6734: 6735: #ifdef FREEEXIT2 6736: #include "freeexit2.h" 6737: #endif 6738: 6739: /*------------- h Pij x at various ages ------------*/ 6740: #include "hpijx.h" 6741: fclose(ficrespij); 6742: 6743: /*-------------- Variance of one-step probabilities---*/ 6744: k=1; 6745: varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart); 6746: 6747: 6748: probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX); 6749: for(i=1;i<=AGESUP;i++) 6750: for(j=1;j<=NCOVMAX;j++) 6751: for(k=1;k<=NCOVMAX;k++) 6752: probs[i][j][k]=0.; 6753: 6754: /*---------- Forecasting ------------------*/ 6755: /*if((stepm == 1) && (strcmp(model,".")==0)){*/ 6756: if(prevfcast==1){ 6757: /* if(stepm ==1){*/ 6758: prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff); 6759: /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/ 6760: /* } */ 6761: /* else{ */ 6762: /* erreur=108; */ 6763: /* 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); */ 6764: /* 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); */ 6765: /* } */ 6766: } 6767: 6768: 6769: /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */ 6770: 6771: prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); 6772: /* 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",\ 6773: ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass); 6774: */ 6775: 6776: if (mobilav!=0) { 6777: mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); 6778: if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ 6779: fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); 6780: printf(" Error in movingaverage mobilav=%d\n",mobilav); 6781: } 6782: } 6783: 6784: 6785: /*---------- Health expectancies, no variances ------------*/ 6786: 6787: strcpy(filerese,"e"); 6788: strcat(filerese,fileres); 6789: if((ficreseij=fopen(filerese,"w"))==NULL) { 6790: printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0); 6791: fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0); 6792: } 6793: printf("Computing Health Expectancies: result on file '%s' \n", filerese); 6794: fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese); 6795: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){ 6796: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/ 6797: 6798: for (k=1; k <= (int) pow(2,cptcoveff); k++){ 6799: fprintf(ficreseij,"\n#****** "); 6800: for(j=1;j<=cptcoveff;j++) { 6801: fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]); 6802: } 6803: fprintf(ficreseij,"******\n"); 6804: 6805: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage); 6806: oldm=oldms;savm=savms; 6807: evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart); 6808: 6809: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage); 6810: /*}*/ 6811: } 6812: fclose(ficreseij); 6813: 6814: 6815: /*---------- Health expectancies and variances ------------*/ 6816: 6817: 6818: strcpy(filerest,"t"); 6819: strcat(filerest,fileres); 6820: if((ficrest=fopen(filerest,"w"))==NULL) { 6821: printf("Problem with total LE resultfile: %s\n", filerest);goto end; 6822: fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end; 6823: } 6824: printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 6825: fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 6826: 6827: 6828: strcpy(fileresstde,"stde"); 6829: strcat(fileresstde,fileres); 6830: if((ficresstdeij=fopen(fileresstde,"w"))==NULL) { 6831: printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0); 6832: fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0); 6833: } 6834: printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde); 6835: fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde); 6836: 6837: strcpy(filerescve,"cve"); 6838: strcat(filerescve,fileres); 6839: if((ficrescveij=fopen(filerescve,"w"))==NULL) { 6840: printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0); 6841: fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0); 6842: } 6843: printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve); 6844: fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve); 6845: 6846: strcpy(fileresv,"v"); 6847: strcat(fileresv,fileres); 6848: if((ficresvij=fopen(fileresv,"w"))==NULL) { 6849: printf("Problem with variance resultfile: %s\n", fileresv);exit(0); 6850: fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0); 6851: } 6852: printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv); 6853: fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv); 6854: 6855: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){ 6856: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/ 6857: 6858: for (k=1; k <= (int) pow(2,cptcoveff); k++){ 6859: fprintf(ficrest,"\n#****** "); 6860: for(j=1;j<=cptcoveff;j++) 6861: fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]); 6862: fprintf(ficrest,"******\n"); 6863: 6864: fprintf(ficresstdeij,"\n#****** "); 6865: fprintf(ficrescveij,"\n#****** "); 6866: for(j=1;j<=cptcoveff;j++) { 6867: fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]); 6868: fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]); 6869: } 6870: fprintf(ficresstdeij,"******\n"); 6871: fprintf(ficrescveij,"******\n"); 6872: 6873: fprintf(ficresvij,"\n#****** "); 6874: for(j=1;j<=cptcoveff;j++) 6875: fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]); 6876: fprintf(ficresvij,"******\n"); 6877: 6878: eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage); 6879: oldm=oldms;savm=savms; 6880: cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart); 6881: /* 6882: */ 6883: /* goto endfree; */ 6884: 6885: vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage); 6886: pstamp(ficrest); 6887: 6888: 6889: for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/ 6890: oldm=oldms;savm=savms; /* Segmentation fault */ 6891: cptcod= 0; /* To be deleted */ 6892: 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 */ 6893: 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 "); 6894: if(vpopbased==1) 6895: 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); 6896: else 6897: fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n"); 6898: fprintf(ficrest,"# Age e.. (std) "); 6899: for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i); 6900: fprintf(ficrest,"\n"); 6901: 6902: epj=vector(1,nlstate+1); 6903: for(age=bage; age <=fage ;age++){ 6904: prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k); 6905: if (vpopbased==1) { 6906: if(mobilav ==0){ 6907: for(i=1; i<=nlstate;i++) 6908: prlim[i][i]=probs[(int)age][i][k]; 6909: }else{ /* mobilav */ 6910: for(i=1; i<=nlstate;i++) 6911: prlim[i][i]=mobaverage[(int)age][i][k]; 6912: } 6913: } 6914: 6915: fprintf(ficrest," %4.0f",age); 6916: for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){ 6917: for(i=1, epj[j]=0.;i <=nlstate;i++) { 6918: epj[j] += prlim[i][i]*eij[i][j][(int)age]; 6919: /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/ 6920: } 6921: epj[nlstate+1] +=epj[j]; 6922: } 6923: 6924: for(i=1, vepp=0.;i <=nlstate;i++) 6925: for(j=1;j <=nlstate;j++) 6926: vepp += vareij[i][j][(int)age]; 6927: fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp)); 6928: for(j=1;j <=nlstate;j++){ 6929: fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age])); 6930: } 6931: fprintf(ficrest,"\n"); 6932: } 6933: } 6934: free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage); 6935: free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage); 6936: free_vector(epj,1,nlstate+1); 6937: /*}*/ 6938: } 6939: free_vector(weight,1,n); 6940: free_imatrix(Tvard,1,NCOVMAX,1,2); 6941: free_imatrix(s,1,maxwav+1,1,n); 6942: free_matrix(anint,1,maxwav,1,n); 6943: free_matrix(mint,1,maxwav,1,n); 6944: free_ivector(cod,1,n); 6945: free_ivector(tab,1,NCOVMAX); 6946: fclose(ficresstdeij); 6947: fclose(ficrescveij); 6948: fclose(ficresvij); 6949: fclose(ficrest); 6950: fclose(ficpar); 6951: 6952: /*------- Variance of period (stable) prevalence------*/ 6953: 6954: strcpy(fileresvpl,"vpl"); 6955: strcat(fileresvpl,fileres); 6956: if((ficresvpl=fopen(fileresvpl,"w"))==NULL) { 6957: printf("Problem with variance of period (stable) prevalence resultfile: %s\n", fileresvpl); 6958: exit(0); 6959: } 6960: printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl); 6961: 6962: /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){ 6963: for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/ 6964: 6965: for (k=1; k <= (int) pow(2,cptcoveff); k++){ 6966: fprintf(ficresvpl,"\n#****** "); 6967: for(j=1;j<=cptcoveff;j++) 6968: fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]); 6969: fprintf(ficresvpl,"******\n"); 6970: 6971: varpl=matrix(1,nlstate,(int) bage, (int) fage); 6972: oldm=oldms;savm=savms; 6973: varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart); 6974: free_matrix(varpl,1,nlstate,(int) bage, (int)fage); 6975: /*}*/ 6976: } 6977: 6978: fclose(ficresvpl); 6979: 6980: /*---------- End : free ----------------*/ 6981: if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); 6982: free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX); 6983: } /* mle==-3 arrives here for freeing */ 6984: /* endfree:*/ 6985: free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */ 6986: free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath); 6987: free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath); 6988: free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath); 6989: free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath); 6990: free_matrix(covar,0,NCOVMAX,1,n); 6991: free_matrix(matcov,1,npar,1,npar); 6992: /*free_vector(delti,1,npar);*/ 6993: free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 6994: free_matrix(agev,1,maxwav,1,imx); 6995: free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 6996: 6997: free_ivector(ncodemax,1,NCOVMAX); 6998: free_ivector(Tvar,1,NCOVMAX); 6999: free_ivector(Tprod,1,NCOVMAX); 7000: free_ivector(Tvaraff,1,NCOVMAX); 7001: free_ivector(Tage,1,NCOVMAX); 7002: 7003: free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX); 7004: free_imatrix(codtab,1,100,1,10); 7005: fflush(fichtm); 7006: fflush(ficgp); 7007: 7008: 7009: if((nberr >0) || (nbwarn>0)){ 7010: printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn); 7011: fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn); 7012: }else{ 7013: printf("End of Imach\n"); 7014: fprintf(ficlog,"End of Imach\n"); 7015: } 7016: printf("See log file on %s\n",filelog); 7017: /* gettimeofday(&end_time, (struct timezone*)0);*/ /* after time */ 7018: /*(void) gettimeofday(&end_time,&tzp);*/ 7019: rend_time = time(NULL); 7020: end_time = *localtime(&rend_time); 7021: /* tml = *localtime(&end_time.tm_sec); */ 7022: strcpy(strtend,asctime(&end_time)); 7023: printf("Local time at start %s\nLocal time at end %s",strstart, strtend); 7024: fprintf(ficlog,"Local time at start %s\nLocal time at end %s\n",strstart, strtend); 7025: printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout)); 7026: 7027: printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time)); 7028: fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout)); 7029: fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time)); 7030: /* printf("Total time was %d uSec.\n", total_usecs);*/ 7031: /* if(fileappend(fichtm,optionfilehtm)){ */ 7032: fprintf(fichtm,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend); 7033: fclose(fichtm); 7034: fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end %s<br>\n</body></html>",strstart, strtend); 7035: fclose(fichtmcov); 7036: fclose(ficgp); 7037: fclose(ficlog); 7038: /*------ End -----------*/ 7039: 7040: 7041: printf("Before Current directory %s!\n",pathcd); 7042: if(chdir(pathcd) != 0) 7043: printf("Can't move to directory %s!\n",path); 7044: if(getcwd(pathcd,MAXLINE) > 0) 7045: printf("Current directory %s!\n",pathcd); 7046: /*strcat(plotcmd,CHARSEPARATOR);*/ 7047: sprintf(plotcmd,"gnuplot"); 7048: #ifdef _WIN32 7049: sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach); 7050: #endif 7051: if(!stat(plotcmd,&info)){ 7052: printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout); 7053: if(!stat(getenv("GNUPLOTBIN"),&info)){ 7054: printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout); 7055: }else 7056: strcpy(pplotcmd,plotcmd); 7057: #ifdef __unix 7058: strcpy(plotcmd,GNUPLOTPROGRAM); 7059: if(!stat(plotcmd,&info)){ 7060: printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout); 7061: }else 7062: strcpy(pplotcmd,plotcmd); 7063: #endif 7064: }else 7065: strcpy(pplotcmd,plotcmd); 7066: 7067: sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot); 7068: printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout); 7069: 7070: if((outcmd=system(plotcmd)) != 0){ 7071: printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd); 7072: printf("\n Trying if gnuplot resides on the same directory that IMaCh\n"); 7073: sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot); 7074: if((outcmd=system(plotcmd)) != 0) 7075: printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd); 7076: } 7077: printf(" Successful, please wait..."); 7078: while (z[0] != 'q') { 7079: /* chdir(path); */ 7080: printf("\nType e to edit results with your browser, g to graph again and q for exit: "); 7081: scanf("%s",z); 7082: /* if (z[0] == 'c') system("./imach"); */ 7083: if (z[0] == 'e') { 7084: #ifdef __APPLE__ 7085: sprintf(pplotcmd, "open %s", optionfilehtm); 7086: #elif __linux 7087: sprintf(pplotcmd, "xdg-open %s", optionfilehtm); 7088: #else 7089: sprintf(pplotcmd, "%s", optionfilehtm); 7090: #endif 7091: printf("Starting browser with: %s",pplotcmd);fflush(stdout); 7092: system(pplotcmd); 7093: } 7094: else if (z[0] == 'g') system(plotcmd); 7095: else if (z[0] == 'q') exit(0); 7096: } 7097: end: 7098: while (z[0] != 'q') { 7099: printf("\nType q for exiting: "); 7100: scanf("%s",z); 7101: } 7102: }