Annotation of imach/src/imach.c, revision 1.243

1.243   ! brouard     1: /* $Id: imach.c,v 1.242 2016/08/30 15:01:20 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.243   ! brouard     4:   Revision 1.242  2016/08/30 15:01:20  brouard
        !             5:   Summary: Fixing a lots
        !             6: 
1.242     brouard     7:   Revision 1.241  2016/08/29 17:17:25  brouard
                      8:   Summary: gnuplot problem in Back projection to fix
                      9: 
1.241     brouard    10:   Revision 1.240  2016/08/29 07:53:18  brouard
                     11:   Summary: Better
                     12: 
1.240     brouard    13:   Revision 1.239  2016/08/26 15:51:03  brouard
                     14:   Summary: Improvement in Powell output in order to copy and paste
                     15: 
                     16:   Author:
                     17: 
1.239     brouard    18:   Revision 1.238  2016/08/26 14:23:35  brouard
                     19:   Summary: Starting tests of 0.99
                     20: 
1.238     brouard    21:   Revision 1.237  2016/08/26 09:20:19  brouard
                     22:   Summary: to valgrind
                     23: 
1.237     brouard    24:   Revision 1.236  2016/08/25 10:50:18  brouard
                     25:   *** empty log message ***
                     26: 
1.236     brouard    27:   Revision 1.235  2016/08/25 06:59:23  brouard
                     28:   *** empty log message ***
                     29: 
1.235     brouard    30:   Revision 1.234  2016/08/23 16:51:20  brouard
                     31:   *** empty log message ***
                     32: 
1.234     brouard    33:   Revision 1.233  2016/08/23 07:40:50  brouard
                     34:   Summary: not working
                     35: 
1.233     brouard    36:   Revision 1.232  2016/08/22 14:20:21  brouard
                     37:   Summary: not working
                     38: 
1.232     brouard    39:   Revision 1.231  2016/08/22 07:17:15  brouard
                     40:   Summary: not working
                     41: 
1.231     brouard    42:   Revision 1.230  2016/08/22 06:55:53  brouard
                     43:   Summary: Not working
                     44: 
1.230     brouard    45:   Revision 1.229  2016/07/23 09:45:53  brouard
                     46:   Summary: Completing for func too
                     47: 
1.229     brouard    48:   Revision 1.228  2016/07/22 17:45:30  brouard
                     49:   Summary: Fixing some arrays, still debugging
                     50: 
1.227     brouard    51:   Revision 1.226  2016/07/12 18:42:34  brouard
                     52:   Summary: temp
                     53: 
1.226     brouard    54:   Revision 1.225  2016/07/12 08:40:03  brouard
                     55:   Summary: saving but not running
                     56: 
1.225     brouard    57:   Revision 1.224  2016/07/01 13:16:01  brouard
                     58:   Summary: Fixes
                     59: 
1.224     brouard    60:   Revision 1.223  2016/02/19 09:23:35  brouard
                     61:   Summary: temporary
                     62: 
1.223     brouard    63:   Revision 1.222  2016/02/17 08:14:50  brouard
                     64:   Summary: Probably last 0.98 stable version 0.98r6
                     65: 
1.222     brouard    66:   Revision 1.221  2016/02/15 23:35:36  brouard
                     67:   Summary: minor bug
                     68: 
1.220     brouard    69:   Revision 1.219  2016/02/15 00:48:12  brouard
                     70:   *** empty log message ***
                     71: 
1.219     brouard    72:   Revision 1.218  2016/02/12 11:29:23  brouard
                     73:   Summary: 0.99 Back projections
                     74: 
1.218     brouard    75:   Revision 1.217  2015/12/23 17:18:31  brouard
                     76:   Summary: Experimental backcast
                     77: 
1.217     brouard    78:   Revision 1.216  2015/12/18 17:32:11  brouard
                     79:   Summary: 0.98r4 Warning and status=-2
                     80: 
                     81:   Version 0.98r4 is now:
                     82:    - displaying an error when status is -1, date of interview unknown and date of death known;
                     83:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                     84:   Older changes concerning s=-2, dating from 2005 have been supersed.
                     85: 
1.216     brouard    86:   Revision 1.215  2015/12/16 08:52:24  brouard
                     87:   Summary: 0.98r4 working
                     88: 
1.215     brouard    89:   Revision 1.214  2015/12/16 06:57:54  brouard
                     90:   Summary: temporary not working
                     91: 
1.214     brouard    92:   Revision 1.213  2015/12/11 18:22:17  brouard
                     93:   Summary: 0.98r4
                     94: 
1.213     brouard    95:   Revision 1.212  2015/11/21 12:47:24  brouard
                     96:   Summary: minor typo
                     97: 
1.212     brouard    98:   Revision 1.211  2015/11/21 12:41:11  brouard
                     99:   Summary: 0.98r3 with some graph of projected cross-sectional
                    100: 
                    101:   Author: Nicolas Brouard
                    102: 
1.211     brouard   103:   Revision 1.210  2015/11/18 17:41:20  brouard
                    104:   Summary: Start working on projected prevalences
                    105: 
1.210     brouard   106:   Revision 1.209  2015/11/17 22:12:03  brouard
                    107:   Summary: Adding ftolpl parameter
                    108:   Author: N Brouard
                    109: 
                    110:   We had difficulties to get smoothed confidence intervals. It was due
                    111:   to the period prevalence which wasn't computed accurately. The inner
                    112:   parameter ftolpl is now an outer parameter of the .imach parameter
                    113:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    114:   computation are long.
                    115: 
1.209     brouard   116:   Revision 1.208  2015/11/17 14:31:57  brouard
                    117:   Summary: temporary
                    118: 
1.208     brouard   119:   Revision 1.207  2015/10/27 17:36:57  brouard
                    120:   *** empty log message ***
                    121: 
1.207     brouard   122:   Revision 1.206  2015/10/24 07:14:11  brouard
                    123:   *** empty log message ***
                    124: 
1.206     brouard   125:   Revision 1.205  2015/10/23 15:50:53  brouard
                    126:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    127: 
1.205     brouard   128:   Revision 1.204  2015/10/01 16:20:26  brouard
                    129:   Summary: Some new graphs of contribution to likelihood
                    130: 
1.204     brouard   131:   Revision 1.203  2015/09/30 17:45:14  brouard
                    132:   Summary: looking at better estimation of the hessian
                    133: 
                    134:   Also a better criteria for convergence to the period prevalence And
                    135:   therefore adding the number of years needed to converge. (The
                    136:   prevalence in any alive state shold sum to one
                    137: 
1.203     brouard   138:   Revision 1.202  2015/09/22 19:45:16  brouard
                    139:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    140: 
1.202     brouard   141:   Revision 1.201  2015/09/15 17:34:58  brouard
                    142:   Summary: 0.98r0
                    143: 
                    144:   - Some new graphs like suvival functions
                    145:   - Some bugs fixed like model=1+age+V2.
                    146: 
1.201     brouard   147:   Revision 1.200  2015/09/09 16:53:55  brouard
                    148:   Summary: Big bug thanks to Flavia
                    149: 
                    150:   Even model=1+age+V2. did not work anymore
                    151: 
1.200     brouard   152:   Revision 1.199  2015/09/07 14:09:23  brouard
                    153:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    154: 
1.199     brouard   155:   Revision 1.198  2015/09/03 07:14:39  brouard
                    156:   Summary: 0.98q5 Flavia
                    157: 
1.198     brouard   158:   Revision 1.197  2015/09/01 18:24:39  brouard
                    159:   *** empty log message ***
                    160: 
1.197     brouard   161:   Revision 1.196  2015/08/18 23:17:52  brouard
                    162:   Summary: 0.98q5
                    163: 
1.196     brouard   164:   Revision 1.195  2015/08/18 16:28:39  brouard
                    165:   Summary: Adding a hack for testing purpose
                    166: 
                    167:   After reading the title, ftol and model lines, if the comment line has
                    168:   a q, starting with #q, the answer at the end of the run is quit. It
                    169:   permits to run test files in batch with ctest. The former workaround was
                    170:   $ echo q | imach foo.imach
                    171: 
1.195     brouard   172:   Revision 1.194  2015/08/18 13:32:00  brouard
                    173:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    174: 
1.194     brouard   175:   Revision 1.193  2015/08/04 07:17:42  brouard
                    176:   Summary: 0.98q4
                    177: 
1.193     brouard   178:   Revision 1.192  2015/07/16 16:49:02  brouard
                    179:   Summary: Fixing some outputs
                    180: 
1.192     brouard   181:   Revision 1.191  2015/07/14 10:00:33  brouard
                    182:   Summary: Some fixes
                    183: 
1.191     brouard   184:   Revision 1.190  2015/05/05 08:51:13  brouard
                    185:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    186: 
                    187:   Fix 1+age+.
                    188: 
1.190     brouard   189:   Revision 1.189  2015/04/30 14:45:16  brouard
                    190:   Summary: 0.98q2
                    191: 
1.189     brouard   192:   Revision 1.188  2015/04/30 08:27:53  brouard
                    193:   *** empty log message ***
                    194: 
1.188     brouard   195:   Revision 1.187  2015/04/29 09:11:15  brouard
                    196:   *** empty log message ***
                    197: 
1.187     brouard   198:   Revision 1.186  2015/04/23 12:01:52  brouard
                    199:   Summary: V1*age is working now, version 0.98q1
                    200: 
                    201:   Some codes had been disabled in order to simplify and Vn*age was
                    202:   working in the optimization phase, ie, giving correct MLE parameters,
                    203:   but, as usual, outputs were not correct and program core dumped.
                    204: 
1.186     brouard   205:   Revision 1.185  2015/03/11 13:26:42  brouard
                    206:   Summary: Inclusion of compile and links command line for Intel Compiler
                    207: 
1.185     brouard   208:   Revision 1.184  2015/03/11 11:52:39  brouard
                    209:   Summary: Back from Windows 8. Intel Compiler
                    210: 
1.184     brouard   211:   Revision 1.183  2015/03/10 20:34:32  brouard
                    212:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    213: 
                    214:   We use directest instead of original Powell test; probably no
                    215:   incidence on the results, but better justifications;
                    216:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    217:   wrong results.
                    218: 
1.183     brouard   219:   Revision 1.182  2015/02/12 08:19:57  brouard
                    220:   Summary: Trying to keep directest which seems simpler and more general
                    221:   Author: Nicolas Brouard
                    222: 
1.182     brouard   223:   Revision 1.181  2015/02/11 23:22:24  brouard
                    224:   Summary: Comments on Powell added
                    225: 
                    226:   Author:
                    227: 
1.181     brouard   228:   Revision 1.180  2015/02/11 17:33:45  brouard
                    229:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    230: 
1.180     brouard   231:   Revision 1.179  2015/01/04 09:57:06  brouard
                    232:   Summary: back to OS/X
                    233: 
1.179     brouard   234:   Revision 1.178  2015/01/04 09:35:48  brouard
                    235:   *** empty log message ***
                    236: 
1.178     brouard   237:   Revision 1.177  2015/01/03 18:40:56  brouard
                    238:   Summary: Still testing ilc32 on OSX
                    239: 
1.177     brouard   240:   Revision 1.176  2015/01/03 16:45:04  brouard
                    241:   *** empty log message ***
                    242: 
1.176     brouard   243:   Revision 1.175  2015/01/03 16:33:42  brouard
                    244:   *** empty log message ***
                    245: 
1.175     brouard   246:   Revision 1.174  2015/01/03 16:15:49  brouard
                    247:   Summary: Still in cross-compilation
                    248: 
1.174     brouard   249:   Revision 1.173  2015/01/03 12:06:26  brouard
                    250:   Summary: trying to detect cross-compilation
                    251: 
1.173     brouard   252:   Revision 1.172  2014/12/27 12:07:47  brouard
                    253:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    254: 
1.172     brouard   255:   Revision 1.171  2014/12/23 13:26:59  brouard
                    256:   Summary: Back from Visual C
                    257: 
                    258:   Still problem with utsname.h on Windows
                    259: 
1.171     brouard   260:   Revision 1.170  2014/12/23 11:17:12  brouard
                    261:   Summary: Cleaning some \%% back to %%
                    262: 
                    263:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    264: 
1.170     brouard   265:   Revision 1.169  2014/12/22 23:08:31  brouard
                    266:   Summary: 0.98p
                    267: 
                    268:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    269: 
1.169     brouard   270:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   271:   Summary: update
1.169     brouard   272: 
1.168     brouard   273:   Revision 1.167  2014/12/22 13:50:56  brouard
                    274:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    275: 
                    276:   Testing on Linux 64
                    277: 
1.167     brouard   278:   Revision 1.166  2014/12/22 11:40:47  brouard
                    279:   *** empty log message ***
                    280: 
1.166     brouard   281:   Revision 1.165  2014/12/16 11:20:36  brouard
                    282:   Summary: After compiling on Visual C
                    283: 
                    284:   * imach.c (Module): Merging 1.61 to 1.162
                    285: 
1.165     brouard   286:   Revision 1.164  2014/12/16 10:52:11  brouard
                    287:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    288: 
                    289:   * imach.c (Module): Merging 1.61 to 1.162
                    290: 
1.164     brouard   291:   Revision 1.163  2014/12/16 10:30:11  brouard
                    292:   * imach.c (Module): Merging 1.61 to 1.162
                    293: 
1.163     brouard   294:   Revision 1.162  2014/09/25 11:43:39  brouard
                    295:   Summary: temporary backup 0.99!
                    296: 
1.162     brouard   297:   Revision 1.1  2014/09/16 11:06:58  brouard
                    298:   Summary: With some code (wrong) for nlopt
                    299: 
                    300:   Author:
                    301: 
                    302:   Revision 1.161  2014/09/15 20:41:41  brouard
                    303:   Summary: Problem with macro SQR on Intel compiler
                    304: 
1.161     brouard   305:   Revision 1.160  2014/09/02 09:24:05  brouard
                    306:   *** empty log message ***
                    307: 
1.160     brouard   308:   Revision 1.159  2014/09/01 10:34:10  brouard
                    309:   Summary: WIN32
                    310:   Author: Brouard
                    311: 
1.159     brouard   312:   Revision 1.158  2014/08/27 17:11:51  brouard
                    313:   *** empty log message ***
                    314: 
1.158     brouard   315:   Revision 1.157  2014/08/27 16:26:55  brouard
                    316:   Summary: Preparing windows Visual studio version
                    317:   Author: Brouard
                    318: 
                    319:   In order to compile on Visual studio, time.h is now correct and time_t
                    320:   and tm struct should be used. difftime should be used but sometimes I
                    321:   just make the differences in raw time format (time(&now).
                    322:   Trying to suppress #ifdef LINUX
                    323:   Add xdg-open for __linux in order to open default browser.
                    324: 
1.157     brouard   325:   Revision 1.156  2014/08/25 20:10:10  brouard
                    326:   *** empty log message ***
                    327: 
1.156     brouard   328:   Revision 1.155  2014/08/25 18:32:34  brouard
                    329:   Summary: New compile, minor changes
                    330:   Author: Brouard
                    331: 
1.155     brouard   332:   Revision 1.154  2014/06/20 17:32:08  brouard
                    333:   Summary: Outputs now all graphs of convergence to period prevalence
                    334: 
1.154     brouard   335:   Revision 1.153  2014/06/20 16:45:46  brouard
                    336:   Summary: If 3 live state, convergence to period prevalence on same graph
                    337:   Author: Brouard
                    338: 
1.153     brouard   339:   Revision 1.152  2014/06/18 17:54:09  brouard
                    340:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    341: 
1.152     brouard   342:   Revision 1.151  2014/06/18 16:43:30  brouard
                    343:   *** empty log message ***
                    344: 
1.151     brouard   345:   Revision 1.150  2014/06/18 16:42:35  brouard
                    346:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    347:   Author: brouard
                    348: 
1.150     brouard   349:   Revision 1.149  2014/06/18 15:51:14  brouard
                    350:   Summary: Some fixes in parameter files errors
                    351:   Author: Nicolas Brouard
                    352: 
1.149     brouard   353:   Revision 1.148  2014/06/17 17:38:48  brouard
                    354:   Summary: Nothing new
                    355:   Author: Brouard
                    356: 
                    357:   Just a new packaging for OS/X version 0.98nS
                    358: 
1.148     brouard   359:   Revision 1.147  2014/06/16 10:33:11  brouard
                    360:   *** empty log message ***
                    361: 
1.147     brouard   362:   Revision 1.146  2014/06/16 10:20:28  brouard
                    363:   Summary: Merge
                    364:   Author: Brouard
                    365: 
                    366:   Merge, before building revised version.
                    367: 
1.146     brouard   368:   Revision 1.145  2014/06/10 21:23:15  brouard
                    369:   Summary: Debugging with valgrind
                    370:   Author: Nicolas Brouard
                    371: 
                    372:   Lot of changes in order to output the results with some covariates
                    373:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    374:   improve the code.
                    375:   No more memory valgrind error but a lot has to be done in order to
                    376:   continue the work of splitting the code into subroutines.
                    377:   Also, decodemodel has been improved. Tricode is still not
                    378:   optimal. nbcode should be improved. Documentation has been added in
                    379:   the source code.
                    380: 
1.144     brouard   381:   Revision 1.143  2014/01/26 09:45:38  brouard
                    382:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    383: 
                    384:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    385:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    386: 
1.143     brouard   387:   Revision 1.142  2014/01/26 03:57:36  brouard
                    388:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    389: 
                    390:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    391: 
1.142     brouard   392:   Revision 1.141  2014/01/26 02:42:01  brouard
                    393:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    394: 
1.141     brouard   395:   Revision 1.140  2011/09/02 10:37:54  brouard
                    396:   Summary: times.h is ok with mingw32 now.
                    397: 
1.140     brouard   398:   Revision 1.139  2010/06/14 07:50:17  brouard
                    399:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    400:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    401: 
1.139     brouard   402:   Revision 1.138  2010/04/30 18:19:40  brouard
                    403:   *** empty log message ***
                    404: 
1.138     brouard   405:   Revision 1.137  2010/04/29 18:11:38  brouard
                    406:   (Module): Checking covariates for more complex models
                    407:   than V1+V2. A lot of change to be done. Unstable.
                    408: 
1.137     brouard   409:   Revision 1.136  2010/04/26 20:30:53  brouard
                    410:   (Module): merging some libgsl code. Fixing computation
                    411:   of likelione (using inter/intrapolation if mle = 0) in order to
                    412:   get same likelihood as if mle=1.
                    413:   Some cleaning of code and comments added.
                    414: 
1.136     brouard   415:   Revision 1.135  2009/10/29 15:33:14  brouard
                    416:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    417: 
1.135     brouard   418:   Revision 1.134  2009/10/29 13:18:53  brouard
                    419:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    420: 
1.134     brouard   421:   Revision 1.133  2009/07/06 10:21:25  brouard
                    422:   just nforces
                    423: 
1.133     brouard   424:   Revision 1.132  2009/07/06 08:22:05  brouard
                    425:   Many tings
                    426: 
1.132     brouard   427:   Revision 1.131  2009/06/20 16:22:47  brouard
                    428:   Some dimensions resccaled
                    429: 
1.131     brouard   430:   Revision 1.130  2009/05/26 06:44:34  brouard
                    431:   (Module): Max Covariate is now set to 20 instead of 8. A
                    432:   lot of cleaning with variables initialized to 0. Trying to make
                    433:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    434: 
1.130     brouard   435:   Revision 1.129  2007/08/31 13:49:27  lievre
                    436:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    437: 
1.129     lievre    438:   Revision 1.128  2006/06/30 13:02:05  brouard
                    439:   (Module): Clarifications on computing e.j
                    440: 
1.128     brouard   441:   Revision 1.127  2006/04/28 18:11:50  brouard
                    442:   (Module): Yes the sum of survivors was wrong since
                    443:   imach-114 because nhstepm was no more computed in the age
                    444:   loop. Now we define nhstepma in the age loop.
                    445:   (Module): In order to speed up (in case of numerous covariates) we
                    446:   compute health expectancies (without variances) in a first step
                    447:   and then all the health expectancies with variances or standard
                    448:   deviation (needs data from the Hessian matrices) which slows the
                    449:   computation.
                    450:   In the future we should be able to stop the program is only health
                    451:   expectancies and graph are needed without standard deviations.
                    452: 
1.127     brouard   453:   Revision 1.126  2006/04/28 17:23:28  brouard
                    454:   (Module): Yes the sum of survivors was wrong since
                    455:   imach-114 because nhstepm was no more computed in the age
                    456:   loop. Now we define nhstepma in the age loop.
                    457:   Version 0.98h
                    458: 
1.126     brouard   459:   Revision 1.125  2006/04/04 15:20:31  lievre
                    460:   Errors in calculation of health expectancies. Age was not initialized.
                    461:   Forecasting file added.
                    462: 
                    463:   Revision 1.124  2006/03/22 17:13:53  lievre
                    464:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    465:   The log-likelihood is printed in the log file
                    466: 
                    467:   Revision 1.123  2006/03/20 10:52:43  brouard
                    468:   * imach.c (Module): <title> changed, corresponds to .htm file
                    469:   name. <head> headers where missing.
                    470: 
                    471:   * imach.c (Module): Weights can have a decimal point as for
                    472:   English (a comma might work with a correct LC_NUMERIC environment,
                    473:   otherwise the weight is truncated).
                    474:   Modification of warning when the covariates values are not 0 or
                    475:   1.
                    476:   Version 0.98g
                    477: 
                    478:   Revision 1.122  2006/03/20 09:45:41  brouard
                    479:   (Module): Weights can have a decimal point as for
                    480:   English (a comma might work with a correct LC_NUMERIC environment,
                    481:   otherwise the weight is truncated).
                    482:   Modification of warning when the covariates values are not 0 or
                    483:   1.
                    484:   Version 0.98g
                    485: 
                    486:   Revision 1.121  2006/03/16 17:45:01  lievre
                    487:   * imach.c (Module): Comments concerning covariates added
                    488: 
                    489:   * imach.c (Module): refinements in the computation of lli if
                    490:   status=-2 in order to have more reliable computation if stepm is
                    491:   not 1 month. Version 0.98f
                    492: 
                    493:   Revision 1.120  2006/03/16 15:10:38  lievre
                    494:   (Module): refinements in the computation of lli if
                    495:   status=-2 in order to have more reliable computation if stepm is
                    496:   not 1 month. Version 0.98f
                    497: 
                    498:   Revision 1.119  2006/03/15 17:42:26  brouard
                    499:   (Module): Bug if status = -2, the loglikelihood was
                    500:   computed as likelihood omitting the logarithm. Version O.98e
                    501: 
                    502:   Revision 1.118  2006/03/14 18:20:07  brouard
                    503:   (Module): varevsij Comments added explaining the second
                    504:   table of variances if popbased=1 .
                    505:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    506:   (Module): Function pstamp added
                    507:   (Module): Version 0.98d
                    508: 
                    509:   Revision 1.117  2006/03/14 17:16:22  brouard
                    510:   (Module): varevsij Comments added explaining the second
                    511:   table of variances if popbased=1 .
                    512:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    513:   (Module): Function pstamp added
                    514:   (Module): Version 0.98d
                    515: 
                    516:   Revision 1.116  2006/03/06 10:29:27  brouard
                    517:   (Module): Variance-covariance wrong links and
                    518:   varian-covariance of ej. is needed (Saito).
                    519: 
                    520:   Revision 1.115  2006/02/27 12:17:45  brouard
                    521:   (Module): One freematrix added in mlikeli! 0.98c
                    522: 
                    523:   Revision 1.114  2006/02/26 12:57:58  brouard
                    524:   (Module): Some improvements in processing parameter
                    525:   filename with strsep.
                    526: 
                    527:   Revision 1.113  2006/02/24 14:20:24  brouard
                    528:   (Module): Memory leaks checks with valgrind and:
                    529:   datafile was not closed, some imatrix were not freed and on matrix
                    530:   allocation too.
                    531: 
                    532:   Revision 1.112  2006/01/30 09:55:26  brouard
                    533:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    534: 
                    535:   Revision 1.111  2006/01/25 20:38:18  brouard
                    536:   (Module): Lots of cleaning and bugs added (Gompertz)
                    537:   (Module): Comments can be added in data file. Missing date values
                    538:   can be a simple dot '.'.
                    539: 
                    540:   Revision 1.110  2006/01/25 00:51:50  brouard
                    541:   (Module): Lots of cleaning and bugs added (Gompertz)
                    542: 
                    543:   Revision 1.109  2006/01/24 19:37:15  brouard
                    544:   (Module): Comments (lines starting with a #) are allowed in data.
                    545: 
                    546:   Revision 1.108  2006/01/19 18:05:42  lievre
                    547:   Gnuplot problem appeared...
                    548:   To be fixed
                    549: 
                    550:   Revision 1.107  2006/01/19 16:20:37  brouard
                    551:   Test existence of gnuplot in imach path
                    552: 
                    553:   Revision 1.106  2006/01/19 13:24:36  brouard
                    554:   Some cleaning and links added in html output
                    555: 
                    556:   Revision 1.105  2006/01/05 20:23:19  lievre
                    557:   *** empty log message ***
                    558: 
                    559:   Revision 1.104  2005/09/30 16:11:43  lievre
                    560:   (Module): sump fixed, loop imx fixed, and simplifications.
                    561:   (Module): If the status is missing at the last wave but we know
                    562:   that the person is alive, then we can code his/her status as -2
                    563:   (instead of missing=-1 in earlier versions) and his/her
                    564:   contributions to the likelihood is 1 - Prob of dying from last
                    565:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    566:   the healthy state at last known wave). Version is 0.98
                    567: 
                    568:   Revision 1.103  2005/09/30 15:54:49  lievre
                    569:   (Module): sump fixed, loop imx fixed, and simplifications.
                    570: 
                    571:   Revision 1.102  2004/09/15 17:31:30  brouard
                    572:   Add the possibility to read data file including tab characters.
                    573: 
                    574:   Revision 1.101  2004/09/15 10:38:38  brouard
                    575:   Fix on curr_time
                    576: 
                    577:   Revision 1.100  2004/07/12 18:29:06  brouard
                    578:   Add version for Mac OS X. Just define UNIX in Makefile
                    579: 
                    580:   Revision 1.99  2004/06/05 08:57:40  brouard
                    581:   *** empty log message ***
                    582: 
                    583:   Revision 1.98  2004/05/16 15:05:56  brouard
                    584:   New version 0.97 . First attempt to estimate force of mortality
                    585:   directly from the data i.e. without the need of knowing the health
                    586:   state at each age, but using a Gompertz model: log u =a + b*age .
                    587:   This is the basic analysis of mortality and should be done before any
                    588:   other analysis, in order to test if the mortality estimated from the
                    589:   cross-longitudinal survey is different from the mortality estimated
                    590:   from other sources like vital statistic data.
                    591: 
                    592:   The same imach parameter file can be used but the option for mle should be -3.
                    593: 
1.133     brouard   594:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   595:   former routines in order to include the new code within the former code.
                    596: 
                    597:   The output is very simple: only an estimate of the intercept and of
                    598:   the slope with 95% confident intervals.
                    599: 
                    600:   Current limitations:
                    601:   A) Even if you enter covariates, i.e. with the
                    602:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    603:   B) There is no computation of Life Expectancy nor Life Table.
                    604: 
                    605:   Revision 1.97  2004/02/20 13:25:42  lievre
                    606:   Version 0.96d. Population forecasting command line is (temporarily)
                    607:   suppressed.
                    608: 
                    609:   Revision 1.96  2003/07/15 15:38:55  brouard
                    610:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    611:   rewritten within the same printf. Workaround: many printfs.
                    612: 
                    613:   Revision 1.95  2003/07/08 07:54:34  brouard
                    614:   * imach.c (Repository):
                    615:   (Repository): Using imachwizard code to output a more meaningful covariance
                    616:   matrix (cov(a12,c31) instead of numbers.
                    617: 
                    618:   Revision 1.94  2003/06/27 13:00:02  brouard
                    619:   Just cleaning
                    620: 
                    621:   Revision 1.93  2003/06/25 16:33:55  brouard
                    622:   (Module): On windows (cygwin) function asctime_r doesn't
                    623:   exist so I changed back to asctime which exists.
                    624:   (Module): Version 0.96b
                    625: 
                    626:   Revision 1.92  2003/06/25 16:30:45  brouard
                    627:   (Module): On windows (cygwin) function asctime_r doesn't
                    628:   exist so I changed back to asctime which exists.
                    629: 
                    630:   Revision 1.91  2003/06/25 15:30:29  brouard
                    631:   * imach.c (Repository): Duplicated warning errors corrected.
                    632:   (Repository): Elapsed time after each iteration is now output. It
                    633:   helps to forecast when convergence will be reached. Elapsed time
                    634:   is stamped in powell.  We created a new html file for the graphs
                    635:   concerning matrix of covariance. It has extension -cov.htm.
                    636: 
                    637:   Revision 1.90  2003/06/24 12:34:15  brouard
                    638:   (Module): Some bugs corrected for windows. Also, when
                    639:   mle=-1 a template is output in file "or"mypar.txt with the design
                    640:   of the covariance matrix to be input.
                    641: 
                    642:   Revision 1.89  2003/06/24 12:30:52  brouard
                    643:   (Module): Some bugs corrected for windows. Also, when
                    644:   mle=-1 a template is output in file "or"mypar.txt with the design
                    645:   of the covariance matrix to be input.
                    646: 
                    647:   Revision 1.88  2003/06/23 17:54:56  brouard
                    648:   * 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.
                    649: 
                    650:   Revision 1.87  2003/06/18 12:26:01  brouard
                    651:   Version 0.96
                    652: 
                    653:   Revision 1.86  2003/06/17 20:04:08  brouard
                    654:   (Module): Change position of html and gnuplot routines and added
                    655:   routine fileappend.
                    656: 
                    657:   Revision 1.85  2003/06/17 13:12:43  brouard
                    658:   * imach.c (Repository): Check when date of death was earlier that
                    659:   current date of interview. It may happen when the death was just
                    660:   prior to the death. In this case, dh was negative and likelihood
                    661:   was wrong (infinity). We still send an "Error" but patch by
                    662:   assuming that the date of death was just one stepm after the
                    663:   interview.
                    664:   (Repository): Because some people have very long ID (first column)
                    665:   we changed int to long in num[] and we added a new lvector for
                    666:   memory allocation. But we also truncated to 8 characters (left
                    667:   truncation)
                    668:   (Repository): No more line truncation errors.
                    669: 
                    670:   Revision 1.84  2003/06/13 21:44:43  brouard
                    671:   * imach.c (Repository): Replace "freqsummary" at a correct
                    672:   place. It differs from routine "prevalence" which may be called
                    673:   many times. Probs is memory consuming and must be used with
                    674:   parcimony.
                    675:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    676: 
                    677:   Revision 1.83  2003/06/10 13:39:11  lievre
                    678:   *** empty log message ***
                    679: 
                    680:   Revision 1.82  2003/06/05 15:57:20  brouard
                    681:   Add log in  imach.c and  fullversion number is now printed.
                    682: 
                    683: */
                    684: /*
                    685:    Interpolated Markov Chain
                    686: 
                    687:   Short summary of the programme:
                    688:   
1.227     brouard   689:   This program computes Healthy Life Expectancies or State-specific
                    690:   (if states aren't health statuses) Expectancies from
                    691:   cross-longitudinal data. Cross-longitudinal data consist in: 
                    692: 
                    693:   -1- a first survey ("cross") where individuals from different ages
                    694:   are interviewed on their health status or degree of disability (in
                    695:   the case of a health survey which is our main interest)
                    696: 
                    697:   -2- at least a second wave of interviews ("longitudinal") which
                    698:   measure each change (if any) in individual health status.  Health
                    699:   expectancies are computed from the time spent in each health state
                    700:   according to a model. More health states you consider, more time is
                    701:   necessary to reach the Maximum Likelihood of the parameters involved
                    702:   in the model.  The simplest model is the multinomial logistic model
                    703:   where pij is the probability to be observed in state j at the second
                    704:   wave conditional to be observed in state i at the first
                    705:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                    706:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                    707:   have a more complex model than "constant and age", you should modify
                    708:   the program where the markup *Covariates have to be included here
                    709:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard   710:   convergence.
                    711: 
                    712:   The advantage of this computer programme, compared to a simple
                    713:   multinomial logistic model, is clear when the delay between waves is not
                    714:   identical for each individual. Also, if a individual missed an
                    715:   intermediate interview, the information is lost, but taken into
                    716:   account using an interpolation or extrapolation.  
                    717: 
                    718:   hPijx is the probability to be observed in state i at age x+h
                    719:   conditional to the observed state i at age x. The delay 'h' can be
                    720:   split into an exact number (nh*stepm) of unobserved intermediate
                    721:   states. This elementary transition (by month, quarter,
                    722:   semester or year) is modelled as a multinomial logistic.  The hPx
                    723:   matrix is simply the matrix product of nh*stepm elementary matrices
                    724:   and the contribution of each individual to the likelihood is simply
                    725:   hPijx.
                    726: 
                    727:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard   728:   of the life expectancies. It also computes the period (stable) prevalence.
                    729: 
                    730: Back prevalence and projections:
1.227     brouard   731: 
                    732:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                    733:    double agemaxpar, double ftolpl, int *ncvyearp, double
                    734:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                    735:    mobilavproj)
                    736: 
                    737:     Computes the back prevalence limit for any combination of
                    738:     covariate values k at any age between ageminpar and agemaxpar and
                    739:     returns it in **bprlim. In the loops,
                    740: 
                    741:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                    742:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                    743: 
                    744:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard   745:    Computes for any combination of covariates k and any age between bage and fage 
                    746:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                    747:                        oldm=oldms;savm=savms;
1.227     brouard   748: 
                    749:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
1.218     brouard   750:      Computes the transition matrix starting at age 'age' over
                    751:      'nhstepm*hstepm*stepm' months (i.e. until
                    752:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard   753:      nhstepm*hstepm matrices. 
                    754: 
                    755:      Returns p3mat[i][j][h] after calling
                    756:      p3mat[i][j][h]=matprod2(newm,
                    757:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                    758:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                    759:      oldm);
1.226     brouard   760: 
                    761: Important routines
                    762: 
                    763: - func (or funcone), computes logit (pij) distinguishing
                    764:   o fixed variables (single or product dummies or quantitative);
                    765:   o varying variables by:
                    766:    (1) wave (single, product dummies, quantitative), 
                    767:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                    768:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                    769:        % varying dummy (not done) or quantitative (not done);
                    770: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                    771:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                    772: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
                    773:   o There are 2*cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
                    774:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard   775: 
1.226     brouard   776: 
                    777:   
1.133     brouard   778:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    779:            Institut national d'études démographiques, Paris.
1.126     brouard   780:   This software have been partly granted by Euro-REVES, a concerted action
                    781:   from the European Union.
                    782:   It is copyrighted identically to a GNU software product, ie programme and
                    783:   software can be distributed freely for non commercial use. Latest version
                    784:   can be accessed at http://euroreves.ined.fr/imach .
                    785: 
                    786:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    787:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    788:   
                    789:   **********************************************************************/
                    790: /*
                    791:   main
                    792:   read parameterfile
                    793:   read datafile
                    794:   concatwav
                    795:   freqsummary
                    796:   if (mle >= 1)
                    797:     mlikeli
                    798:   print results files
                    799:   if mle==1 
                    800:      computes hessian
                    801:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    802:       begin-prev-date,...
                    803:   open gnuplot file
                    804:   open html file
1.145     brouard   805:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    806:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    807:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    808:     freexexit2 possible for memory heap.
                    809: 
                    810:   h Pij x                         | pij_nom  ficrestpij
                    811:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    812:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    813:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    814: 
                    815:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    816:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    817:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    818:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    819:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    820: 
1.126     brouard   821:   forecasting if prevfcast==1 prevforecast call prevalence()
                    822:   health expectancies
                    823:   Variance-covariance of DFLE
                    824:   prevalence()
                    825:    movingaverage()
                    826:   varevsij() 
                    827:   if popbased==1 varevsij(,popbased)
                    828:   total life expectancies
                    829:   Variance of period (stable) prevalence
                    830:  end
                    831: */
                    832: 
1.187     brouard   833: /* #define DEBUG */
                    834: /* #define DEBUGBRENT */
1.203     brouard   835: /* #define DEBUGLINMIN */
                    836: /* #define DEBUGHESS */
                    837: #define DEBUGHESSIJ
1.224     brouard   838: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard   839: #define POWELL /* Instead of NLOPT */
1.224     brouard   840: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard   841: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                    842: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard   843: 
                    844: #include <math.h>
                    845: #include <stdio.h>
                    846: #include <stdlib.h>
                    847: #include <string.h>
1.226     brouard   848: #include <ctype.h>
1.159     brouard   849: 
                    850: #ifdef _WIN32
                    851: #include <io.h>
1.172     brouard   852: #include <windows.h>
                    853: #include <tchar.h>
1.159     brouard   854: #else
1.126     brouard   855: #include <unistd.h>
1.159     brouard   856: #endif
1.126     brouard   857: 
                    858: #include <limits.h>
                    859: #include <sys/types.h>
1.171     brouard   860: 
                    861: #if defined(__GNUC__)
                    862: #include <sys/utsname.h> /* Doesn't work on Windows */
                    863: #endif
                    864: 
1.126     brouard   865: #include <sys/stat.h>
                    866: #include <errno.h>
1.159     brouard   867: /* extern int errno; */
1.126     brouard   868: 
1.157     brouard   869: /* #ifdef LINUX */
                    870: /* #include <time.h> */
                    871: /* #include "timeval.h" */
                    872: /* #else */
                    873: /* #include <sys/time.h> */
                    874: /* #endif */
                    875: 
1.126     brouard   876: #include <time.h>
                    877: 
1.136     brouard   878: #ifdef GSL
                    879: #include <gsl/gsl_errno.h>
                    880: #include <gsl/gsl_multimin.h>
                    881: #endif
                    882: 
1.167     brouard   883: 
1.162     brouard   884: #ifdef NLOPT
                    885: #include <nlopt.h>
                    886: typedef struct {
                    887:   double (* function)(double [] );
                    888: } myfunc_data ;
                    889: #endif
                    890: 
1.126     brouard   891: /* #include <libintl.h> */
                    892: /* #define _(String) gettext (String) */
                    893: 
1.141     brouard   894: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   895: 
                    896: #define GNUPLOTPROGRAM "gnuplot"
                    897: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    898: #define FILENAMELENGTH 132
                    899: 
                    900: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    901: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    902: 
1.144     brouard   903: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    904: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   905: 
                    906: #define NINTERVMAX 8
1.144     brouard   907: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    908: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    909: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197     brouard   910: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard   911: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                    912: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.126     brouard   913: #define MAXN 20000
1.144     brouard   914: #define YEARM 12. /**< Number of months per year */
1.218     brouard   915: /* #define AGESUP 130 */
                    916: #define AGESUP 150
                    917: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard   918: #define AGEBASE 40
1.194     brouard   919: #define AGEOVERFLOW 1.e20
1.164     brouard   920: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard   921: #ifdef _WIN32
                    922: #define DIRSEPARATOR '\\'
                    923: #define CHARSEPARATOR "\\"
                    924: #define ODIRSEPARATOR '/'
                    925: #else
1.126     brouard   926: #define DIRSEPARATOR '/'
                    927: #define CHARSEPARATOR "/"
                    928: #define ODIRSEPARATOR '\\'
                    929: #endif
                    930: 
1.243   ! brouard   931: /* $Id: imach.c,v 1.242 2016/08/30 15:01:20 brouard Exp $ */
1.126     brouard   932: /* $State: Exp $ */
1.196     brouard   933: #include "version.h"
                    934: char version[]=__IMACH_VERSION__;
1.224     brouard   935: char copyright[]="February 2016,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015-2018";
1.243   ! brouard   936: char fullversion[]="$Revision: 1.242 $ $Date: 2016/08/30 15:01:20 $"; 
1.126     brouard   937: char strstart[80];
                    938: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   939: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard   940: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard   941: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    942: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    943: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
1.225     brouard   944: int cptcovs=0; /**< cptcovs number of simple covariates in the model V2+V1 =2 */
                    945: int cptcovsnq=0; /**< cptcovsnq number of simple covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard   946: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    947: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    948: int cptcoveff=0; /* Total number of covariates to vary for printing results */
1.233     brouard   949: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                    950: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.232     brouard   951: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
1.234     brouard   952: int nsd=0; /**< Total number of single dummy variables (output) */
                    953: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard   954: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard   955: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard   956: int ntveff=0; /**< ntveff number of effective time varying variables */
                    957: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard   958: int cptcov=0; /* Working variable */
1.218     brouard   959: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.126     brouard   960: int npar=NPARMAX;
                    961: int nlstate=2; /* Number of live states */
                    962: int ndeath=1; /* Number of dead states */
1.130     brouard   963: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.223     brouard   964: int  nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable */ 
1.126     brouard   965: int popbased=0;
                    966: 
                    967: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard   968: int maxwav=0; /* Maxim number of waves */
                    969: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    970: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    971: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard   972:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard   973: int mle=1, weightopt=0;
1.126     brouard   974: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    975: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    976: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    977:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard   978: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard   979: int selected(int kvar); /* Is covariate kvar selected for printing results */
                    980: 
1.130     brouard   981: double jmean=1; /* Mean space between 2 waves */
1.145     brouard   982: double **matprod2(); /* test */
1.126     brouard   983: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    984: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard   985: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                    986: 
1.136     brouard   987: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard   988: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard   989: FILE *ficlog, *ficrespow;
1.130     brouard   990: int globpr=0; /* Global variable for printing or not */
1.126     brouard   991: double fretone; /* Only one call to likelihood */
1.130     brouard   992: long ipmx=0; /* Number of contributions */
1.126     brouard   993: double sw; /* Sum of weights */
                    994: char filerespow[FILENAMELENGTH];
                    995: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                    996: FILE *ficresilk;
                    997: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                    998: FILE *ficresprobmorprev;
                    999: FILE *fichtm, *fichtmcov; /* Html File */
                   1000: FILE *ficreseij;
                   1001: char filerese[FILENAMELENGTH];
                   1002: FILE *ficresstdeij;
                   1003: char fileresstde[FILENAMELENGTH];
                   1004: FILE *ficrescveij;
                   1005: char filerescve[FILENAMELENGTH];
                   1006: FILE  *ficresvij;
                   1007: char fileresv[FILENAMELENGTH];
                   1008: FILE  *ficresvpl;
                   1009: char fileresvpl[FILENAMELENGTH];
                   1010: char title[MAXLINE];
1.234     brouard  1011: char model[MAXLINE]; /**< The model line */
1.217     brouard  1012: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1013: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1014: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1015: char command[FILENAMELENGTH];
                   1016: int  outcmd=0;
                   1017: 
1.217     brouard  1018: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1019: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1020: char filelog[FILENAMELENGTH]; /* Log file */
                   1021: char filerest[FILENAMELENGTH];
                   1022: char fileregp[FILENAMELENGTH];
                   1023: char popfile[FILENAMELENGTH];
                   1024: 
                   1025: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1026: 
1.157     brouard  1027: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1028: /* struct timezone tzp; */
                   1029: /* extern int gettimeofday(); */
                   1030: struct tm tml, *gmtime(), *localtime();
                   1031: 
                   1032: extern time_t time();
                   1033: 
                   1034: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1035: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                   1036: struct tm tm;
                   1037: 
1.126     brouard  1038: char strcurr[80], strfor[80];
                   1039: 
                   1040: char *endptr;
                   1041: long lval;
                   1042: double dval;
                   1043: 
                   1044: #define NR_END 1
                   1045: #define FREE_ARG char*
                   1046: #define FTOL 1.0e-10
                   1047: 
                   1048: #define NRANSI 
1.240     brouard  1049: #define ITMAX 200
                   1050: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1051: 
                   1052: #define TOL 2.0e-4 
                   1053: 
                   1054: #define CGOLD 0.3819660 
                   1055: #define ZEPS 1.0e-10 
                   1056: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1057: 
                   1058: #define GOLD 1.618034 
                   1059: #define GLIMIT 100.0 
                   1060: #define TINY 1.0e-20 
                   1061: 
                   1062: static double maxarg1,maxarg2;
                   1063: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1064: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1065:   
                   1066: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1067: #define rint(a) floor(a+0.5)
1.166     brouard  1068: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1069: #define mytinydouble 1.0e-16
1.166     brouard  1070: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1071: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1072: /* static double dsqrarg; */
                   1073: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1074: static double sqrarg;
                   1075: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1076: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1077: int agegomp= AGEGOMP;
                   1078: 
                   1079: int imx; 
                   1080: int stepm=1;
                   1081: /* Stepm, step in month: minimum step interpolation*/
                   1082: 
                   1083: int estepm;
                   1084: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1085: 
                   1086: int m,nb;
                   1087: long *num;
1.197     brouard  1088: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1089: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1090:                   covariate for which somebody answered excluding 
                   1091:                   undefined. Usually 2: 0 and 1. */
                   1092: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1093:                             covariate for which somebody answered including 
                   1094:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1095: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1096: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1097: double ***mobaverage, ***mobaverages; /* New global variable */
1.126     brouard  1098: double *ageexmed,*agecens;
                   1099: double dateintmean=0;
                   1100: 
                   1101: double *weight;
                   1102: int **s; /* Status */
1.141     brouard  1103: double *agedc;
1.145     brouard  1104: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1105:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1106:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.225     brouard  1107: double **coqvar; /* Fixed quantitative covariate iqv */
                   1108: double ***cotvar; /* Time varying covariate itv */
                   1109: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1110: double  idx; 
                   1111: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.234     brouard  1112: /*           V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1113: /*k          1  2   3   4     5    6    7     8    9 */
                   1114: /*Tvar[k]=   5  4   3   6     5    2    7     1    1 */
                   1115: /* Tndvar[k]    1   2   3               4          5 */
                   1116: /*TDvar         4   3   6               7          1 */ /* For outputs only; combination of dummies fixed or varying */
                   1117: /* Tns[k]    1  2   2              4               5 */ /* Number of single cova */
                   1118: /* TvarsD[k]    1   2                              3 */ /* Number of single dummy cova */
                   1119: /* TvarsDind    2   3                              9 */ /* position K of single dummy cova */
                   1120: /* TvarsQ[k] 1                     2                 */ /* Number of single quantitative cova */
                   1121: /* TvarsQind 1                     6                 */ /* position K of single quantitative cova */
                   1122: /* Tprod[i]=k           4               7            */
                   1123: /* Tage[i]=k                  5               8      */
                   1124: /* */
                   1125: /* Type                    */
                   1126: /* V         1  2  3  4  5 */
                   1127: /*           F  F  V  V  V */
                   1128: /*           D  Q  D  D  Q */
                   1129: /*                         */
                   1130: int *TvarsD;
                   1131: int *TvarsDind;
                   1132: int *TvarsQ;
                   1133: int *TvarsQind;
                   1134: 
1.235     brouard  1135: #define MAXRESULTLINES 10
                   1136: int nresult=0;
                   1137: int TKresult[MAXRESULTLINES];
1.237     brouard  1138: int Tresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
                   1139: int Tinvresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
1.235     brouard  1140: int Tvresult[MAXRESULTLINES][NCOVMAX]; /* For dummy variable , variable # (output) */
                   1141: double Tqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
1.237     brouard  1142: double Tqinvresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
1.235     brouard  1143: int Tvqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , variable # (output) */
                   1144: 
1.234     brouard  1145: /* int *TDvar; /\**< TDvar[1]=4,  TDvarF[2]=3, TDvar[3]=6  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
1.232     brouard  1146: int *TvarF; /**< TvarF[1]=Tvar[6]=2,  TvarF[2]=Tvar[7]=7, TvarF[3]=Tvar[9]=1  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1147: int *TvarFind; /**< TvarFind[1]=6,  TvarFind[2]=7, Tvarind[3]=9  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1148: int *TvarV; /**< TvarV[1]=Tvar[1]=5, TvarV[2]=Tvar[2]=4  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1149: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1150: int *TvarA; /**< TvarA[1]=Tvar[5]=5, TvarA[2]=Tvar[8]=1  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1151: int *TvarAind; /**< TvarindA[1]=5, TvarAind[2]=8  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  1152: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1153: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1154: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1155: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1156: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1157: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1158: int *TvarVQ; /* TvarVQ[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple time varying quantitative variable */
                   1159: int *TvarVQind; /* TvarVQind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple time varying quantitative variable */
                   1160: 
1.230     brouard  1161: int *Tvarsel; /**< Selected covariates for output */
                   1162: double *Tvalsel; /**< Selected modality value of covariate for output */
1.226     brouard  1163: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.227     brouard  1164: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1165: int *Dummy; /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
1.238     brouard  1166: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1167: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1168: int *Tage;
1.227     brouard  1169: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1170: int *Tmodelind; /** Tmodelind[Tvaraff[3]]=9 for V1 position,Tvaraff[1]@9={4, 3, 1, 0, 0, 0, 0, 0, 0}, model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.230     brouard  1171: int *TmodelInvind; /** Tmodelind[Tvaraff[3]]=9 for V1 position,Tvaraff[1]@9={4, 3, 1, 0, 0, 0, 0, 0, 0}, model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/ 
                   1172: int *TmodelInvQind; /** Tmodelqind[1]=1 for V5(quantitative varying) position,Tvaraff[1]@9={4, 3, 1, 0, 0, 0, 0, 0, 0}, model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1  */
1.145     brouard  1173: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1174: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1175: int **Tvard;
                   1176: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1177: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1178: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1179:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1180:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1181: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1182: double *lsurv, *lpop, *tpop;
                   1183: 
1.231     brouard  1184: #define FD 1; /* Fixed dummy covariate */
                   1185: #define FQ 2; /* Fixed quantitative covariate */
                   1186: #define FP 3; /* Fixed product covariate */
                   1187: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1188: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1189: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1190: #define VD 10; /* Varying dummy covariate */
                   1191: #define VQ 11; /* Varying quantitative covariate */
                   1192: #define VP 12; /* Varying product covariate */
                   1193: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1194: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1195: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1196: #define APFD 16; /* Age product * fixed dummy covariate */
                   1197: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1198: #define APVD 18; /* Age product * varying dummy covariate */
                   1199: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1200: 
                   1201: #define FTYPE 1; /* Fixed covariate */
                   1202: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1203: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1204: 
                   1205: struct kmodel{
                   1206:        int maintype; /* main type */
                   1207:        int subtype; /* subtype */
                   1208: };
                   1209: struct kmodel modell[NCOVMAX];
                   1210: 
1.143     brouard  1211: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1212: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1213: 
                   1214: /**************** split *************************/
                   1215: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1216: {
                   1217:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1218:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1219:   */ 
                   1220:   char *ss;                            /* pointer */
1.186     brouard  1221:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1222: 
                   1223:   l1 = strlen(path );                  /* length of path */
                   1224:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1225:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1226:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1227:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1228:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1229:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1230:     /* get current working directory */
                   1231:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1232: #ifdef WIN32
                   1233:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1234: #else
                   1235:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1236: #endif
1.126     brouard  1237:       return( GLOCK_ERROR_GETCWD );
                   1238:     }
                   1239:     /* got dirc from getcwd*/
                   1240:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1241:   } else {                             /* strip directory from path */
1.126     brouard  1242:     ss++;                              /* after this, the filename */
                   1243:     l2 = strlen( ss );                 /* length of filename */
                   1244:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1245:     strcpy( name, ss );                /* save file name */
                   1246:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1247:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1248:     printf(" DIRC2 = %s \n",dirc);
                   1249:   }
                   1250:   /* We add a separator at the end of dirc if not exists */
                   1251:   l1 = strlen( dirc );                 /* length of directory */
                   1252:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1253:     dirc[l1] =  DIRSEPARATOR;
                   1254:     dirc[l1+1] = 0; 
                   1255:     printf(" DIRC3 = %s \n",dirc);
                   1256:   }
                   1257:   ss = strrchr( name, '.' );           /* find last / */
                   1258:   if (ss >0){
                   1259:     ss++;
                   1260:     strcpy(ext,ss);                    /* save extension */
                   1261:     l1= strlen( name);
                   1262:     l2= strlen(ss)+1;
                   1263:     strncpy( finame, name, l1-l2);
                   1264:     finame[l1-l2]= 0;
                   1265:   }
                   1266: 
                   1267:   return( 0 );                         /* we're done */
                   1268: }
                   1269: 
                   1270: 
                   1271: /******************************************/
                   1272: 
                   1273: void replace_back_to_slash(char *s, char*t)
                   1274: {
                   1275:   int i;
                   1276:   int lg=0;
                   1277:   i=0;
                   1278:   lg=strlen(t);
                   1279:   for(i=0; i<= lg; i++) {
                   1280:     (s[i] = t[i]);
                   1281:     if (t[i]== '\\') s[i]='/';
                   1282:   }
                   1283: }
                   1284: 
1.132     brouard  1285: char *trimbb(char *out, char *in)
1.137     brouard  1286: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1287:   char *s;
                   1288:   s=out;
                   1289:   while (*in != '\0'){
1.137     brouard  1290:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1291:       in++;
                   1292:     }
                   1293:     *out++ = *in++;
                   1294:   }
                   1295:   *out='\0';
                   1296:   return s;
                   1297: }
                   1298: 
1.187     brouard  1299: /* char *substrchaine(char *out, char *in, char *chain) */
                   1300: /* { */
                   1301: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1302: /*   char *s, *t; */
                   1303: /*   t=in;s=out; */
                   1304: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1305: /*     *out++ = *in++; */
                   1306: /*   } */
                   1307: 
                   1308: /*   /\* *in matches *chain *\/ */
                   1309: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1310: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1311: /*   } */
                   1312: /*   in--; chain--; */
                   1313: /*   while ( (*in != '\0')){ */
                   1314: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1315: /*     *out++ = *in++; */
                   1316: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1317: /*   } */
                   1318: /*   *out='\0'; */
                   1319: /*   out=s; */
                   1320: /*   return out; */
                   1321: /* } */
                   1322: char *substrchaine(char *out, char *in, char *chain)
                   1323: {
                   1324:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1325:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1326: 
                   1327:   char *strloc;
                   1328: 
                   1329:   strcpy (out, in); 
                   1330:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1331:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1332:   if(strloc != NULL){ 
                   1333:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1334:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1335:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1336:   }
                   1337:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1338:   return out;
                   1339: }
                   1340: 
                   1341: 
1.145     brouard  1342: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1343: {
1.187     brouard  1344:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1345:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187     brouard  1346:      gives blocc="abcdef" and alocc="ghi2j".
1.145     brouard  1347:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1348:   */
1.160     brouard  1349:   char *s, *t;
1.145     brouard  1350:   t=in;s=in;
                   1351:   while ((*in != occ) && (*in != '\0')){
                   1352:     *alocc++ = *in++;
                   1353:   }
                   1354:   if( *in == occ){
                   1355:     *(alocc)='\0';
                   1356:     s=++in;
                   1357:   }
                   1358:  
                   1359:   if (s == t) {/* occ not found */
                   1360:     *(alocc-(in-s))='\0';
                   1361:     in=s;
                   1362:   }
                   1363:   while ( *in != '\0'){
                   1364:     *blocc++ = *in++;
                   1365:   }
                   1366: 
                   1367:   *blocc='\0';
                   1368:   return t;
                   1369: }
1.137     brouard  1370: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1371: {
1.187     brouard  1372:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1373:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1374:      gives blocc="abcdef2ghi" and alocc="j".
                   1375:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1376:   */
                   1377:   char *s, *t;
                   1378:   t=in;s=in;
                   1379:   while (*in != '\0'){
                   1380:     while( *in == occ){
                   1381:       *blocc++ = *in++;
                   1382:       s=in;
                   1383:     }
                   1384:     *blocc++ = *in++;
                   1385:   }
                   1386:   if (s == t) /* occ not found */
                   1387:     *(blocc-(in-s))='\0';
                   1388:   else
                   1389:     *(blocc-(in-s)-1)='\0';
                   1390:   in=s;
                   1391:   while ( *in != '\0'){
                   1392:     *alocc++ = *in++;
                   1393:   }
                   1394: 
                   1395:   *alocc='\0';
                   1396:   return s;
                   1397: }
                   1398: 
1.126     brouard  1399: int nbocc(char *s, char occ)
                   1400: {
                   1401:   int i,j=0;
                   1402:   int lg=20;
                   1403:   i=0;
                   1404:   lg=strlen(s);
                   1405:   for(i=0; i<= lg; i++) {
1.234     brouard  1406:     if  (s[i] == occ ) j++;
1.126     brouard  1407:   }
                   1408:   return j;
                   1409: }
                   1410: 
1.137     brouard  1411: /* void cutv(char *u,char *v, char*t, char occ) */
                   1412: /* { */
                   1413: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1414: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1415: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1416: /*   int i,lg,j,p=0; */
                   1417: /*   i=0; */
                   1418: /*   lg=strlen(t); */
                   1419: /*   for(j=0; j<=lg-1; j++) { */
                   1420: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1421: /*   } */
1.126     brouard  1422: 
1.137     brouard  1423: /*   for(j=0; j<p; j++) { */
                   1424: /*     (u[j] = t[j]); */
                   1425: /*   } */
                   1426: /*      u[p]='\0'; */
1.126     brouard  1427: 
1.137     brouard  1428: /*    for(j=0; j<= lg; j++) { */
                   1429: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1430: /*   } */
                   1431: /* } */
1.126     brouard  1432: 
1.160     brouard  1433: #ifdef _WIN32
                   1434: char * strsep(char **pp, const char *delim)
                   1435: {
                   1436:   char *p, *q;
                   1437:          
                   1438:   if ((p = *pp) == NULL)
                   1439:     return 0;
                   1440:   if ((q = strpbrk (p, delim)) != NULL)
                   1441:   {
                   1442:     *pp = q + 1;
                   1443:     *q = '\0';
                   1444:   }
                   1445:   else
                   1446:     *pp = 0;
                   1447:   return p;
                   1448: }
                   1449: #endif
                   1450: 
1.126     brouard  1451: /********************** nrerror ********************/
                   1452: 
                   1453: void nrerror(char error_text[])
                   1454: {
                   1455:   fprintf(stderr,"ERREUR ...\n");
                   1456:   fprintf(stderr,"%s\n",error_text);
                   1457:   exit(EXIT_FAILURE);
                   1458: }
                   1459: /*********************** vector *******************/
                   1460: double *vector(int nl, int nh)
                   1461: {
                   1462:   double *v;
                   1463:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1464:   if (!v) nrerror("allocation failure in vector");
                   1465:   return v-nl+NR_END;
                   1466: }
                   1467: 
                   1468: /************************ free vector ******************/
                   1469: void free_vector(double*v, int nl, int nh)
                   1470: {
                   1471:   free((FREE_ARG)(v+nl-NR_END));
                   1472: }
                   1473: 
                   1474: /************************ivector *******************************/
                   1475: int *ivector(long nl,long nh)
                   1476: {
                   1477:   int *v;
                   1478:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1479:   if (!v) nrerror("allocation failure in ivector");
                   1480:   return v-nl+NR_END;
                   1481: }
                   1482: 
                   1483: /******************free ivector **************************/
                   1484: void free_ivector(int *v, long nl, long nh)
                   1485: {
                   1486:   free((FREE_ARG)(v+nl-NR_END));
                   1487: }
                   1488: 
                   1489: /************************lvector *******************************/
                   1490: long *lvector(long nl,long nh)
                   1491: {
                   1492:   long *v;
                   1493:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1494:   if (!v) nrerror("allocation failure in ivector");
                   1495:   return v-nl+NR_END;
                   1496: }
                   1497: 
                   1498: /******************free lvector **************************/
                   1499: void free_lvector(long *v, long nl, long nh)
                   1500: {
                   1501:   free((FREE_ARG)(v+nl-NR_END));
                   1502: }
                   1503: 
                   1504: /******************* imatrix *******************************/
                   1505: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1506:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1507: { 
                   1508:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1509:   int **m; 
                   1510:   
                   1511:   /* allocate pointers to rows */ 
                   1512:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1513:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1514:   m += NR_END; 
                   1515:   m -= nrl; 
                   1516:   
                   1517:   
                   1518:   /* allocate rows and set pointers to them */ 
                   1519:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1520:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1521:   m[nrl] += NR_END; 
                   1522:   m[nrl] -= ncl; 
                   1523:   
                   1524:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1525:   
                   1526:   /* return pointer to array of pointers to rows */ 
                   1527:   return m; 
                   1528: } 
                   1529: 
                   1530: /****************** free_imatrix *************************/
                   1531: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1532:       int **m;
                   1533:       long nch,ncl,nrh,nrl; 
                   1534:      /* free an int matrix allocated by imatrix() */ 
                   1535: { 
                   1536:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1537:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1538: } 
                   1539: 
                   1540: /******************* matrix *******************************/
                   1541: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1542: {
                   1543:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1544:   double **m;
                   1545: 
                   1546:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1547:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1548:   m += NR_END;
                   1549:   m -= nrl;
                   1550: 
                   1551:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1552:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1553:   m[nrl] += NR_END;
                   1554:   m[nrl] -= ncl;
                   1555: 
                   1556:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1557:   return m;
1.145     brouard  1558:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1559: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1560: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1561:    */
                   1562: }
                   1563: 
                   1564: /*************************free matrix ************************/
                   1565: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1566: {
                   1567:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1568:   free((FREE_ARG)(m+nrl-NR_END));
                   1569: }
                   1570: 
                   1571: /******************* ma3x *******************************/
                   1572: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1573: {
                   1574:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1575:   double ***m;
                   1576: 
                   1577:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1578:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1579:   m += NR_END;
                   1580:   m -= nrl;
                   1581: 
                   1582:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1583:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1584:   m[nrl] += NR_END;
                   1585:   m[nrl] -= ncl;
                   1586: 
                   1587:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1588: 
                   1589:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1590:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1591:   m[nrl][ncl] += NR_END;
                   1592:   m[nrl][ncl] -= nll;
                   1593:   for (j=ncl+1; j<=nch; j++) 
                   1594:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1595:   
                   1596:   for (i=nrl+1; i<=nrh; i++) {
                   1597:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1598:     for (j=ncl+1; j<=nch; j++) 
                   1599:       m[i][j]=m[i][j-1]+nlay;
                   1600:   }
                   1601:   return m; 
                   1602:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1603:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1604:   */
                   1605: }
                   1606: 
                   1607: /*************************free ma3x ************************/
                   1608: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1609: {
                   1610:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1611:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1612:   free((FREE_ARG)(m+nrl-NR_END));
                   1613: }
                   1614: 
                   1615: /*************** function subdirf ***********/
                   1616: char *subdirf(char fileres[])
                   1617: {
                   1618:   /* Caution optionfilefiname is hidden */
                   1619:   strcpy(tmpout,optionfilefiname);
                   1620:   strcat(tmpout,"/"); /* Add to the right */
                   1621:   strcat(tmpout,fileres);
                   1622:   return tmpout;
                   1623: }
                   1624: 
                   1625: /*************** function subdirf2 ***********/
                   1626: char *subdirf2(char fileres[], char *preop)
                   1627: {
                   1628:   
                   1629:   /* Caution optionfilefiname is hidden */
                   1630:   strcpy(tmpout,optionfilefiname);
                   1631:   strcat(tmpout,"/");
                   1632:   strcat(tmpout,preop);
                   1633:   strcat(tmpout,fileres);
                   1634:   return tmpout;
                   1635: }
                   1636: 
                   1637: /*************** function subdirf3 ***********/
                   1638: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1639: {
                   1640:   
                   1641:   /* Caution optionfilefiname is hidden */
                   1642:   strcpy(tmpout,optionfilefiname);
                   1643:   strcat(tmpout,"/");
                   1644:   strcat(tmpout,preop);
                   1645:   strcat(tmpout,preop2);
                   1646:   strcat(tmpout,fileres);
                   1647:   return tmpout;
                   1648: }
1.213     brouard  1649:  
                   1650: /*************** function subdirfext ***********/
                   1651: char *subdirfext(char fileres[], char *preop, char *postop)
                   1652: {
                   1653:   
                   1654:   strcpy(tmpout,preop);
                   1655:   strcat(tmpout,fileres);
                   1656:   strcat(tmpout,postop);
                   1657:   return tmpout;
                   1658: }
1.126     brouard  1659: 
1.213     brouard  1660: /*************** function subdirfext3 ***********/
                   1661: char *subdirfext3(char fileres[], char *preop, char *postop)
                   1662: {
                   1663:   
                   1664:   /* Caution optionfilefiname is hidden */
                   1665:   strcpy(tmpout,optionfilefiname);
                   1666:   strcat(tmpout,"/");
                   1667:   strcat(tmpout,preop);
                   1668:   strcat(tmpout,fileres);
                   1669:   strcat(tmpout,postop);
                   1670:   return tmpout;
                   1671: }
                   1672:  
1.162     brouard  1673: char *asc_diff_time(long time_sec, char ascdiff[])
                   1674: {
                   1675:   long sec_left, days, hours, minutes;
                   1676:   days = (time_sec) / (60*60*24);
                   1677:   sec_left = (time_sec) % (60*60*24);
                   1678:   hours = (sec_left) / (60*60) ;
                   1679:   sec_left = (sec_left) %(60*60);
                   1680:   minutes = (sec_left) /60;
                   1681:   sec_left = (sec_left) % (60);
                   1682:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1683:   return ascdiff;
                   1684: }
                   1685: 
1.126     brouard  1686: /***************** f1dim *************************/
                   1687: extern int ncom; 
                   1688: extern double *pcom,*xicom;
                   1689: extern double (*nrfunc)(double []); 
                   1690:  
                   1691: double f1dim(double x) 
                   1692: { 
                   1693:   int j; 
                   1694:   double f;
                   1695:   double *xt; 
                   1696:  
                   1697:   xt=vector(1,ncom); 
                   1698:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1699:   f=(*nrfunc)(xt); 
                   1700:   free_vector(xt,1,ncom); 
                   1701:   return f; 
                   1702: } 
                   1703: 
                   1704: /*****************brent *************************/
                   1705: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1706: {
                   1707:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1708:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1709:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1710:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1711:    * returned function value. 
                   1712:   */
1.126     brouard  1713:   int iter; 
                   1714:   double a,b,d,etemp;
1.159     brouard  1715:   double fu=0,fv,fw,fx;
1.164     brouard  1716:   double ftemp=0.;
1.126     brouard  1717:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1718:   double e=0.0; 
                   1719:  
                   1720:   a=(ax < cx ? ax : cx); 
                   1721:   b=(ax > cx ? ax : cx); 
                   1722:   x=w=v=bx; 
                   1723:   fw=fv=fx=(*f)(x); 
                   1724:   for (iter=1;iter<=ITMAX;iter++) { 
                   1725:     xm=0.5*(a+b); 
                   1726:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1727:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1728:     printf(".");fflush(stdout);
                   1729:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1730: #ifdef DEBUGBRENT
1.126     brouard  1731:     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);
                   1732:     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);
                   1733:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1734: #endif
                   1735:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1736:       *xmin=x; 
                   1737:       return fx; 
                   1738:     } 
                   1739:     ftemp=fu;
                   1740:     if (fabs(e) > tol1) { 
                   1741:       r=(x-w)*(fx-fv); 
                   1742:       q=(x-v)*(fx-fw); 
                   1743:       p=(x-v)*q-(x-w)*r; 
                   1744:       q=2.0*(q-r); 
                   1745:       if (q > 0.0) p = -p; 
                   1746:       q=fabs(q); 
                   1747:       etemp=e; 
                   1748:       e=d; 
                   1749:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  1750:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  1751:       else { 
1.224     brouard  1752:                                d=p/q; 
                   1753:                                u=x+d; 
                   1754:                                if (u-a < tol2 || b-u < tol2) 
                   1755:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  1756:       } 
                   1757:     } else { 
                   1758:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1759:     } 
                   1760:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1761:     fu=(*f)(u); 
                   1762:     if (fu <= fx) { 
                   1763:       if (u >= x) a=x; else b=x; 
                   1764:       SHFT(v,w,x,u) 
1.183     brouard  1765:       SHFT(fv,fw,fx,fu) 
                   1766:     } else { 
                   1767:       if (u < x) a=u; else b=u; 
                   1768:       if (fu <= fw || w == x) { 
1.224     brouard  1769:                                v=w; 
                   1770:                                w=u; 
                   1771:                                fv=fw; 
                   1772:                                fw=fu; 
1.183     brouard  1773:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  1774:                                v=u; 
                   1775:                                fv=fu; 
1.183     brouard  1776:       } 
                   1777:     } 
1.126     brouard  1778:   } 
                   1779:   nrerror("Too many iterations in brent"); 
                   1780:   *xmin=x; 
                   1781:   return fx; 
                   1782: } 
                   1783: 
                   1784: /****************** mnbrak ***********************/
                   1785: 
                   1786: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1787:            double (*func)(double)) 
1.183     brouard  1788: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1789: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1790: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1791: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1792:    */
1.126     brouard  1793:   double ulim,u,r,q, dum;
                   1794:   double fu; 
1.187     brouard  1795: 
                   1796:   double scale=10.;
                   1797:   int iterscale=0;
                   1798: 
                   1799:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   1800:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   1801: 
                   1802: 
                   1803:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   1804:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   1805:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   1806:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   1807:   /* } */
                   1808: 
1.126     brouard  1809:   if (*fb > *fa) { 
                   1810:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  1811:     SHFT(dum,*fb,*fa,dum) 
                   1812:   } 
1.126     brouard  1813:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1814:   *fc=(*func)(*cx); 
1.183     brouard  1815: #ifdef DEBUG
1.224     brouard  1816:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   1817:   fprintf(ficlog,"mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
1.183     brouard  1818: #endif
1.224     brouard  1819:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc. If fc=inf it exits and if flat fb=fc it exits too.*/
1.126     brouard  1820:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  1821:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  1822:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  1823:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1824:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   1825:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  1826:       fu=(*func)(u); 
1.163     brouard  1827: #ifdef DEBUG
                   1828:       /* f(x)=A(x-u)**2+f(u) */
                   1829:       double A, fparabu; 
                   1830:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1831:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  1832:       printf("\nmnbrak (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf),  (*u=%.12f, fu=%.12lf, fparabu=%.12f, q=%lf < %lf=r)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu, fparabu,q,r);
                   1833:       fprintf(ficlog,"\nmnbrak (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf),  (*u=%.12f, fu=%.12lf, fparabu=%.12f, q=%lf < %lf=r)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu, fparabu,q,r);
1.183     brouard  1834:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   1835:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   1836:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   1837:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  1838: #endif 
1.184     brouard  1839: #ifdef MNBRAKORIGINAL
1.183     brouard  1840: #else
1.191     brouard  1841: /*       if (fu > *fc) { */
                   1842: /* #ifdef DEBUG */
                   1843: /*       printf("mnbrak4  fu > fc \n"); */
                   1844: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   1845: /* #endif */
                   1846: /*     /\* SHFT(u,*cx,*cx,u) /\\* ie a=c, c=u and u=c; in that case, next SHFT(a,b,c,u) will give a=b=b, b=c=u, c=u=c and *\\/  *\/ */
                   1847: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   1848: /*     dum=u; /\* Shifting c and u *\/ */
                   1849: /*     u = *cx; */
                   1850: /*     *cx = dum; */
                   1851: /*     dum = fu; */
                   1852: /*     fu = *fc; */
                   1853: /*     *fc =dum; */
                   1854: /*       } else { /\* end *\/ */
                   1855: /* #ifdef DEBUG */
                   1856: /*       printf("mnbrak3  fu < fc \n"); */
                   1857: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   1858: /* #endif */
                   1859: /*     dum=u; /\* Shifting c and u *\/ */
                   1860: /*     u = *cx; */
                   1861: /*     *cx = dum; */
                   1862: /*     dum = fu; */
                   1863: /*     fu = *fc; */
                   1864: /*     *fc =dum; */
                   1865: /*       } */
1.224     brouard  1866: #ifdef DEBUGMNBRAK
                   1867:                 double A, fparabu; 
                   1868:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1869:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   1870:      printf("\nmnbrak35 ax=%lf fa=%lf bx=%lf fb=%lf, u=%lf fp=%lf fu=%lf < or >= fc=%lf cx=%lf, q=%lf < %lf=r \n",*ax, *fa, *bx,*fb,u,fparabu,fu,*fc,*cx,q,r);
                   1871:      fprintf(ficlog,"\nmnbrak35 ax=%lf fa=%lf bx=%lf fb=%lf, u=%lf fp=%lf fu=%lf < or >= fc=%lf cx=%lf, q=%lf < %lf=r \n",*ax, *fa, *bx,*fb,u,fparabu,fu,*fc,*cx,q,r);
1.183     brouard  1872: #endif
1.191     brouard  1873:       dum=u; /* Shifting c and u */
                   1874:       u = *cx;
                   1875:       *cx = dum;
                   1876:       dum = fu;
                   1877:       fu = *fc;
                   1878:       *fc =dum;
1.183     brouard  1879: #endif
1.162     brouard  1880:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  1881: #ifdef DEBUG
1.224     brouard  1882:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   1883:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  1884: #endif
1.126     brouard  1885:       fu=(*func)(u); 
                   1886:       if (fu < *fc) { 
1.183     brouard  1887: #ifdef DEBUG
1.224     brouard  1888:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   1889:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   1890: #endif
                   1891:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   1892:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   1893: #ifdef DEBUG
                   1894:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  1895: #endif
                   1896:       } 
1.162     brouard  1897:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  1898: #ifdef DEBUG
1.224     brouard  1899:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   1900:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  1901: #endif
1.126     brouard  1902:       u=ulim; 
                   1903:       fu=(*func)(u); 
1.183     brouard  1904:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   1905: #ifdef DEBUG
1.224     brouard  1906:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   1907:       fprintf(ficlog,"\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
1.183     brouard  1908: #endif
1.126     brouard  1909:       u=(*cx)+GOLD*(*cx-*bx); 
                   1910:       fu=(*func)(u); 
1.224     brouard  1911: #ifdef DEBUG
                   1912:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   1913:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   1914: #endif
1.183     brouard  1915:     } /* end tests */
1.126     brouard  1916:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  1917:     SHFT(*fa,*fb,*fc,fu) 
                   1918: #ifdef DEBUG
1.224     brouard  1919:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   1920:       fprintf(ficlog, "\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
1.183     brouard  1921: #endif
                   1922:   } /* end while; ie return (a, b, c, fa, fb, fc) such that a < b < c with f(a) > f(b) and fb < f(c) */
1.126     brouard  1923: } 
                   1924: 
                   1925: /*************** linmin ************************/
1.162     brouard  1926: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   1927: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   1928: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   1929: the value of func at the returned location p . This is actually all accomplished by calling the
                   1930: routines mnbrak and brent .*/
1.126     brouard  1931: int ncom; 
                   1932: double *pcom,*xicom;
                   1933: double (*nrfunc)(double []); 
                   1934:  
1.224     brouard  1935: #ifdef LINMINORIGINAL
1.126     brouard  1936: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  1937: #else
                   1938: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   1939: #endif
1.126     brouard  1940: { 
                   1941:   double brent(double ax, double bx, double cx, 
                   1942:               double (*f)(double), double tol, double *xmin); 
                   1943:   double f1dim(double x); 
                   1944:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1945:              double *fc, double (*func)(double)); 
                   1946:   int j; 
                   1947:   double xx,xmin,bx,ax; 
                   1948:   double fx,fb,fa;
1.187     brouard  1949: 
1.203     brouard  1950: #ifdef LINMINORIGINAL
                   1951: #else
                   1952:   double scale=10., axs, xxs; /* Scale added for infinity */
                   1953: #endif
                   1954:   
1.126     brouard  1955:   ncom=n; 
                   1956:   pcom=vector(1,n); 
                   1957:   xicom=vector(1,n); 
                   1958:   nrfunc=func; 
                   1959:   for (j=1;j<=n;j++) { 
                   1960:     pcom[j]=p[j]; 
1.202     brouard  1961:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  1962:   } 
1.187     brouard  1963: 
1.203     brouard  1964: #ifdef LINMINORIGINAL
                   1965:   xx=1.;
                   1966: #else
                   1967:   axs=0.0;
                   1968:   xxs=1.;
                   1969:   do{
                   1970:     xx= xxs;
                   1971: #endif
1.187     brouard  1972:     ax=0.;
                   1973:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   1974:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   1975:     /* xt[x,j]=pcom[j]+x*xicom[j]  f(ax) = f(xt(a,j=1,n)) = f(p(j) + 0 * xi(j)) and  f(xx) = f(xt(x, j=1,n)) = f(p(j) + 1 * xi(j))   */
                   1976:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   1977:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   1978:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   1979:     /* Find a bracket a,x,b in direction n=xi ie xicom, order may change. Scale is [0:xxs*xi[j]] et non plus  [0:xi[j]]*/
1.203     brouard  1980: #ifdef LINMINORIGINAL
                   1981: #else
                   1982:     if (fx != fx){
1.224     brouard  1983:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   1984:                        printf("|");
                   1985:                        fprintf(ficlog,"|");
1.203     brouard  1986: #ifdef DEBUGLINMIN
1.224     brouard  1987:                        printf("\nLinmin NAN : input [axs=%lf:xxs=%lf], mnbrak outputs fx=%lf <(fb=%lf and fa=%lf) with xx=%lf in [ax=%lf:bx=%lf] \n",  axs, xxs, fx,fb, fa, xx, ax, bx);
1.203     brouard  1988: #endif
                   1989:     }
1.224     brouard  1990:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  1991: #endif
                   1992:   
1.191     brouard  1993: #ifdef DEBUGLINMIN
                   1994:   printf("\nLinmin after mnbrak: ax=%12.7f xx=%12.7f bx=%12.7f fa=%12.2f fx=%12.2f fb=%12.2f\n",  ax,xx,bx,fa,fx,fb);
1.202     brouard  1995:   fprintf(ficlog,"\nLinmin after mnbrak: ax=%12.7f xx=%12.7f bx=%12.7f fa=%12.2f fx=%12.2f fb=%12.2f\n",  ax,xx,bx,fa,fx,fb);
1.191     brouard  1996: #endif
1.224     brouard  1997: #ifdef LINMINORIGINAL
                   1998: #else
                   1999:        if(fb == fx){ /* Flat function in the direction */
                   2000:                xmin=xx;
                   2001:     *flat=1;
                   2002:        }else{
                   2003:     *flat=0;
                   2004: #endif
                   2005:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2006:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2007:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2008:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2009:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2010:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2011: #ifdef DEBUG
1.224     brouard  2012:   printf("retour brent from bracket (a=%lf fa=%lf, xx=%lf fx=%lf, b=%lf fb=%lf): fret=%lf xmin=%lf\n",ax,fa,xx,fx,bx,fb,*fret,xmin);
                   2013:   fprintf(ficlog,"retour brent from bracket (a=%lf fa=%lf, xx=%lf fx=%lf, b=%lf fb=%lf): fret=%lf xmin=%lf\n",ax,fa,xx,fx,bx,fb,*fret,xmin);
                   2014: #endif
                   2015: #ifdef LINMINORIGINAL
                   2016: #else
                   2017:                        }
1.126     brouard  2018: #endif
1.191     brouard  2019: #ifdef DEBUGLINMIN
                   2020:   printf("linmin end ");
1.202     brouard  2021:   fprintf(ficlog,"linmin end ");
1.191     brouard  2022: #endif
1.126     brouard  2023:   for (j=1;j<=n;j++) { 
1.203     brouard  2024: #ifdef LINMINORIGINAL
                   2025:     xi[j] *= xmin; 
                   2026: #else
                   2027: #ifdef DEBUGLINMIN
                   2028:     if(xxs <1.0)
                   2029:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2030: #endif
                   2031:     xi[j] *= xmin*xxs; /* xi rescaled by xmin and number of loops: if xmin=-1.237 and xi=(1,0,...,0) xi=(-1.237,0,...,0) */
                   2032: #ifdef DEBUGLINMIN
                   2033:     if(xxs <1.0)
                   2034:       printf(" after xi[%d]=%12.8f, xmin=%12.8f, ax=%12.8f, xx=%12.8f, bx=%12.8f, xxs=%12.8f", j,xi[j], xmin, ax, xx, bx,xxs );
                   2035: #endif
                   2036: #endif
1.187     brouard  2037:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2038:   } 
1.191     brouard  2039: #ifdef DEBUGLINMIN
1.203     brouard  2040:   printf("\n");
1.191     brouard  2041:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2042:   fprintf(ficlog,"Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.191     brouard  2043:   for (j=1;j<=n;j++) { 
1.202     brouard  2044:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2045:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2046:     if(j % ncovmodel == 0){
1.191     brouard  2047:       printf("\n");
1.202     brouard  2048:       fprintf(ficlog,"\n");
                   2049:     }
1.191     brouard  2050:   }
1.203     brouard  2051: #else
1.191     brouard  2052: #endif
1.126     brouard  2053:   free_vector(xicom,1,n); 
                   2054:   free_vector(pcom,1,n); 
                   2055: } 
                   2056: 
                   2057: 
                   2058: /*************** powell ************************/
1.162     brouard  2059: /*
                   2060: Minimization of a function func of n variables. Input consists of an initial starting point
                   2061: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   2062: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   2063: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   2064: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2065: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2066:  */
1.224     brouard  2067: #ifdef LINMINORIGINAL
                   2068: #else
                   2069:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2070:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2071: #endif
1.126     brouard  2072: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2073:            double (*func)(double [])) 
                   2074: { 
1.224     brouard  2075: #ifdef LINMINORIGINAL
                   2076:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2077:              double (*func)(double [])); 
1.224     brouard  2078: #else 
1.241     brouard  2079:  void linmin(double p[], double xi[], int n, double *fret,
                   2080:             double (*func)(double []),int *flat); 
1.224     brouard  2081: #endif
1.239     brouard  2082:  int i,ibig,j,jk,k; 
1.126     brouard  2083:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2084:   double directest;
1.126     brouard  2085:   double fp,fptt;
                   2086:   double *xits;
                   2087:   int niterf, itmp;
1.224     brouard  2088: #ifdef LINMINORIGINAL
                   2089: #else
                   2090: 
                   2091:   flatdir=ivector(1,n); 
                   2092:   for (j=1;j<=n;j++) flatdir[j]=0; 
                   2093: #endif
1.126     brouard  2094: 
                   2095:   pt=vector(1,n); 
                   2096:   ptt=vector(1,n); 
                   2097:   xit=vector(1,n); 
                   2098:   xits=vector(1,n); 
                   2099:   *fret=(*func)(p); 
                   2100:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  2101:   rcurr_time = time(NULL);  
1.126     brouard  2102:   for (*iter=1;;++(*iter)) { 
1.187     brouard  2103:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  2104:     ibig=0; 
                   2105:     del=0.0; 
1.157     brouard  2106:     rlast_time=rcurr_time;
                   2107:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2108:     rcurr_time = time(NULL);  
                   2109:     curr_time = *localtime(&rcurr_time);
                   2110:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   2111:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   2112: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  2113:     for (i=1;i<=n;i++) {
1.126     brouard  2114:       fprintf(ficrespow," %.12lf", p[i]);
                   2115:     }
1.239     brouard  2116:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2117:     printf("\n#model=  1      +     age ");
                   2118:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2119:     if(nagesqr==1){
1.241     brouard  2120:        printf("  + age*age  ");
                   2121:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2122:     }
                   2123:     for(j=1;j <=ncovmodel-2;j++){
                   2124:       if(Typevar[j]==0) {
                   2125:        printf("  +      V%d  ",Tvar[j]);
                   2126:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2127:       }else if(Typevar[j]==1) {
                   2128:        printf("  +    V%d*age ",Tvar[j]);
                   2129:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2130:       }else if(Typevar[j]==2) {
                   2131:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2132:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2133:       }
                   2134:     }
1.126     brouard  2135:     printf("\n");
1.239     brouard  2136: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2137: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2138:     fprintf(ficlog,"\n");
1.239     brouard  2139:     for(i=1,jk=1; i <=nlstate; i++){
                   2140:       for(k=1; k <=(nlstate+ndeath); k++){
                   2141:        if (k != i) {
                   2142:          printf("%d%d ",i,k);
                   2143:          fprintf(ficlog,"%d%d ",i,k);
                   2144:          for(j=1; j <=ncovmodel; j++){
                   2145:            printf("%12.7f ",p[jk]);
                   2146:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2147:            jk++; 
                   2148:          }
                   2149:          printf("\n");
                   2150:          fprintf(ficlog,"\n");
                   2151:        }
                   2152:       }
                   2153:     }
1.241     brouard  2154:     if(*iter <=3 && *iter >1){
1.157     brouard  2155:       tml = *localtime(&rcurr_time);
                   2156:       strcpy(strcurr,asctime(&tml));
                   2157:       rforecast_time=rcurr_time; 
1.126     brouard  2158:       itmp = strlen(strcurr);
                   2159:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2160:        strcurr[itmp-1]='\0';
1.162     brouard  2161:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2162:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  2163:       for(niterf=10;niterf<=30;niterf+=10){
1.241     brouard  2164:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2165:        forecast_time = *localtime(&rforecast_time);
                   2166:        strcpy(strfor,asctime(&forecast_time));
                   2167:        itmp = strlen(strfor);
                   2168:        if(strfor[itmp-1]=='\n')
                   2169:          strfor[itmp-1]='\0';
                   2170:        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);
                   2171:        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);
1.126     brouard  2172:       }
                   2173:     }
1.187     brouard  2174:     for (i=1;i<=n;i++) { /* For each direction i */
                   2175:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2176:       fptt=(*fret); 
                   2177: #ifdef DEBUG
1.203     brouard  2178:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2179:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2180: #endif
1.203     brouard  2181:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2182:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2183: #ifdef LINMINORIGINAL
1.188     brouard  2184:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2185: #else
                   2186:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2187:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2188: #endif
                   2189:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2190:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2191:                                /* because that direction will be replaced unless the gain del is small */
                   2192:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2193:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2194:                                /* with the new direction. */
                   2195:                                del=fabs(fptt-(*fret)); 
                   2196:                                ibig=i; 
1.126     brouard  2197:       } 
                   2198: #ifdef DEBUG
                   2199:       printf("%d %.12e",i,(*fret));
                   2200:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2201:       for (j=1;j<=n;j++) {
1.224     brouard  2202:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2203:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2204:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2205:       }
                   2206:       for(j=1;j<=n;j++) {
1.225     brouard  2207:                                printf(" p(%d)=%.12e",j,p[j]);
                   2208:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2209:       }
                   2210:       printf("\n");
                   2211:       fprintf(ficlog,"\n");
                   2212: #endif
1.187     brouard  2213:     } /* end loop on each direction i */
                   2214:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2215:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2216:     /* New value of last point Pn is not computed, P(n-1) */
1.224     brouard  2217:       for(j=1;j<=n;j++) {
1.225     brouard  2218:                                if(flatdir[j] >0){
                   2219:                                        printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2220:                                        fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2221:                                }
                   2222:                                /* printf("\n"); */
                   2223:                                /* fprintf(ficlog,"\n"); */
                   2224:                        }
1.243   ! brouard  2225:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
        !          2226:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2227:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2228:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2229:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2230:       /* decreased of more than 3.84  */
                   2231:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2232:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2233:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2234:                        
1.188     brouard  2235:       /* Starting the program with initial values given by a former maximization will simply change */
                   2236:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2237:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2238:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2239: #ifdef DEBUG
                   2240:       int k[2],l;
                   2241:       k[0]=1;
                   2242:       k[1]=-1;
                   2243:       printf("Max: %.12e",(*func)(p));
                   2244:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2245:       for (j=1;j<=n;j++) {
                   2246:        printf(" %.12e",p[j]);
                   2247:        fprintf(ficlog," %.12e",p[j]);
                   2248:       }
                   2249:       printf("\n");
                   2250:       fprintf(ficlog,"\n");
                   2251:       for(l=0;l<=1;l++) {
                   2252:        for (j=1;j<=n;j++) {
                   2253:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2254:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2255:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2256:        }
                   2257:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2258:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2259:       }
                   2260: #endif
                   2261: 
1.224     brouard  2262: #ifdef LINMINORIGINAL
                   2263: #else
                   2264:       free_ivector(flatdir,1,n); 
                   2265: #endif
1.126     brouard  2266:       free_vector(xit,1,n); 
                   2267:       free_vector(xits,1,n); 
                   2268:       free_vector(ptt,1,n); 
                   2269:       free_vector(pt,1,n); 
                   2270:       return; 
1.192     brouard  2271:     } /* enough precision */ 
1.240     brouard  2272:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2273:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2274:       ptt[j]=2.0*p[j]-pt[j]; 
                   2275:       xit[j]=p[j]-pt[j]; 
                   2276:       pt[j]=p[j]; 
                   2277:     } 
1.181     brouard  2278:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2279: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2280:                if (*iter <=4) {
1.225     brouard  2281: #else
                   2282: #endif
1.224     brouard  2283: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2284: #else
1.161     brouard  2285:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2286: #endif
1.162     brouard  2287:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2288:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2289:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2290:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2291:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2292:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2293:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2294:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2295:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2296:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2297:       /* mu² and del² are equal when f3=f1 */
                   2298:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2299:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2300:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2301:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2302: #ifdef NRCORIGINAL
                   2303:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2304: #else
                   2305:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del); /* Intel compiler doesn't work on one line; bug reported */
1.161     brouard  2306:       t= t- del*SQR(fp-fptt);
1.183     brouard  2307: #endif
1.202     brouard  2308:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2309: #ifdef DEBUG
1.181     brouard  2310:       printf("t1= %.12lf, t2= %.12lf, t=%.12lf  directest=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t,directest);
                   2311:       fprintf(ficlog,"t1= %.12lf, t2= %.12lf, t=%.12lf directest=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t,directest);
1.161     brouard  2312:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2313:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2314:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2315:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2316:       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);
                   2317:       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);
                   2318: #endif
1.183     brouard  2319: #ifdef POWELLORIGINAL
                   2320:       if (t < 0.0) { /* Then we use it for new direction */
                   2321: #else
1.182     brouard  2322:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2323:                                printf("directest= %.12lf (if <0 we include P0 Pn as new direction), t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt,del);
1.192     brouard  2324:         printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1.224     brouard  2325:         fprintf(ficlog,"directest= %.12lf (if directest<0 or t<0 we include P0 Pn as new direction), t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt, del);
1.192     brouard  2326:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2327:       } 
1.181     brouard  2328:       if (directest < 0.0) { /* Then we use it for new direction */
                   2329: #endif
1.191     brouard  2330: #ifdef DEBUGLINMIN
1.234     brouard  2331:        printf("Before linmin in direction P%d-P0\n",n);
                   2332:        for (j=1;j<=n;j++) {
                   2333:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2334:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2335:          if(j % ncovmodel == 0){
                   2336:            printf("\n");
                   2337:            fprintf(ficlog,"\n");
                   2338:          }
                   2339:        }
1.224     brouard  2340: #endif
                   2341: #ifdef LINMINORIGINAL
1.234     brouard  2342:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2343: #else
1.234     brouard  2344:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2345:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2346: #endif
1.234     brouard  2347:        
1.191     brouard  2348: #ifdef DEBUGLINMIN
1.234     brouard  2349:        for (j=1;j<=n;j++) { 
                   2350:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2351:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2352:          if(j % ncovmodel == 0){
                   2353:            printf("\n");
                   2354:            fprintf(ficlog,"\n");
                   2355:          }
                   2356:        }
1.224     brouard  2357: #endif
1.234     brouard  2358:        for (j=1;j<=n;j++) { 
                   2359:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2360:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2361:        }
1.224     brouard  2362: #ifdef LINMINORIGINAL
                   2363: #else
1.234     brouard  2364:        for (j=1, flatd=0;j<=n;j++) {
                   2365:          if(flatdir[j]>0)
                   2366:            flatd++;
                   2367:        }
                   2368:        if(flatd >0){
                   2369:          printf("%d flat directions\n",flatd);
                   2370:          fprintf(ficlog,"%d flat directions\n",flatd);
                   2371:          for (j=1;j<=n;j++) { 
                   2372:            if(flatdir[j]>0){
                   2373:              printf("%d ",j);
                   2374:              fprintf(ficlog,"%d ",j);
                   2375:            }
                   2376:          }
                   2377:          printf("\n");
                   2378:          fprintf(ficlog,"\n");
                   2379:        }
1.191     brouard  2380: #endif
1.234     brouard  2381:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2382:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2383:        
1.126     brouard  2384: #ifdef DEBUG
1.234     brouard  2385:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2386:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2387:        for(j=1;j<=n;j++){
                   2388:          printf(" %lf",xit[j]);
                   2389:          fprintf(ficlog," %lf",xit[j]);
                   2390:        }
                   2391:        printf("\n");
                   2392:        fprintf(ficlog,"\n");
1.126     brouard  2393: #endif
1.192     brouard  2394:       } /* end of t or directest negative */
1.224     brouard  2395: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2396: #else
1.234     brouard  2397:       } /* end if (fptt < fp)  */
1.192     brouard  2398: #endif
1.225     brouard  2399: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2400:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2401: #else
1.224     brouard  2402: #endif
1.234     brouard  2403:                } /* loop iteration */ 
1.126     brouard  2404: } 
1.234     brouard  2405:   
1.126     brouard  2406: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2407:   
1.235     brouard  2408:   double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij, int nres)
1.234     brouard  2409:   {
1.235     brouard  2410:     /* Computes the prevalence limit in each live state at age x and for covariate combination ij 
                   2411:        (and selected quantitative values in nres)
                   2412:        by left multiplying the unit
1.234     brouard  2413:        matrix by transitions matrix until convergence is reached with precision ftolpl */
1.206     brouard  2414:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2415:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2416:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2417:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2418:   /* Initial matrix pimij */
                   2419:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2420:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2421:   /*  0,                   0                  , 1} */
                   2422:   /*
                   2423:    * and after some iteration: */
                   2424:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2425:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2426:   /*  0,                   0                  , 1} */
                   2427:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2428:   /* {0.51571254859325999, 0.4842874514067399, */
                   2429:   /*  0.51326036147820708, 0.48673963852179264} */
                   2430:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2431:     
1.126     brouard  2432:   int i, ii,j,k;
1.209     brouard  2433:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2434:   /* double **matprod2(); */ /* test */
1.218     brouard  2435:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2436:   double **newm;
1.209     brouard  2437:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2438:   int ncvloop=0;
1.169     brouard  2439:   
1.209     brouard  2440:   min=vector(1,nlstate);
                   2441:   max=vector(1,nlstate);
                   2442:   meandiff=vector(1,nlstate);
                   2443: 
1.218     brouard  2444:        /* Starting with matrix unity */
1.126     brouard  2445:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2446:     for (j=1;j<=nlstate+ndeath;j++){
                   2447:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2448:     }
1.169     brouard  2449:   
                   2450:   cov[1]=1.;
                   2451:   
                   2452:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2453:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2454:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2455:     ncvloop++;
1.126     brouard  2456:     newm=savm;
                   2457:     /* Covariates have to be included here again */
1.138     brouard  2458:     cov[2]=agefin;
1.187     brouard  2459:     if(nagesqr==1)
                   2460:       cov[3]= agefin*agefin;;
1.234     brouard  2461:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2462:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2463:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
1.235     brouard  2464:       /* printf("prevalim Dummy combi=%d k=%d TvarsD[%d]=V%d TvarsDind[%d]=%d nbcode=%d cov=%lf codtabm(%d,Tvar[%d])=%d \n",ij,k, k, TvarsD[k],k,TvarsDind[k],nbcode[TvarsD[k]][codtabm(ij,k)],cov[2+nagesqr+TvarsDind[k]], ij, k, codtabm(ij,k)); */
1.234     brouard  2465:     }
                   2466:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2467:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
1.235     brouard  2468:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   2469:       /* printf("prevalim Quantitative k=%d  TvarsQind[%d]=%d, TvarsQ[%d]=V%d,Tqresult[%d][%d]=%f\n",k,k,TvarsQind[k],k,TvarsQ[k],nres,k,Tqresult[nres][k]); */
1.138     brouard  2470:     }
1.237     brouard  2471:     for (k=1; k<=cptcovage;k++){  /* For product with age */
1.234     brouard  2472:       if(Dummy[Tvar[Tage[k]]]){
                   2473:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2474:       } else{
1.235     brouard  2475:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
1.234     brouard  2476:       }
1.235     brouard  2477:       /* printf("prevalim Age combi=%d k=%d  Tage[%d]=V%d Tqresult[%d][%d]=%f\n",ij,k,k,Tage[k],nres,k,Tqresult[nres][k]); */
1.234     brouard  2478:     }
1.237     brouard  2479:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
1.235     brouard  2480:       /* printf("prevalim Prod ij=%d k=%d  Tprod[%d]=%d Tvard[%d][1]=V%d, Tvard[%d][2]=V%d\n",ij,k,k,Tprod[k], k,Tvard[k][1], k,Tvard[k][2]); */
1.237     brouard  2481:       if(Dummy[Tvard[k][1]==0]){
                   2482:        if(Dummy[Tvard[k][2]==0]){
                   2483:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2484:        }else{
                   2485:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
                   2486:        }
                   2487:       }else{
                   2488:        if(Dummy[Tvard[k][2]==0]){
                   2489:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
                   2490:        }else{
                   2491:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   2492:        }
                   2493:       }
1.234     brouard  2494:     }
1.138     brouard  2495:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2496:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2497:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2498:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2499:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2500:                /* age and covariate values of ij are in 'cov' */
1.142     brouard  2501:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2502:     
1.126     brouard  2503:     savm=oldm;
                   2504:     oldm=newm;
1.209     brouard  2505: 
                   2506:     for(j=1; j<=nlstate; j++){
                   2507:       max[j]=0.;
                   2508:       min[j]=1.;
                   2509:     }
                   2510:     for(i=1;i<=nlstate;i++){
                   2511:       sumnew=0;
                   2512:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2513:       for(j=1; j<=nlstate; j++){ 
                   2514:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2515:        max[j]=FMAX(max[j],prlim[i][j]);
                   2516:        min[j]=FMIN(min[j],prlim[i][j]);
                   2517:       }
                   2518:     }
                   2519: 
1.126     brouard  2520:     maxmax=0.;
1.209     brouard  2521:     for(j=1; j<=nlstate; j++){
                   2522:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2523:       maxmax=FMAX(maxmax,meandiff[j]);
                   2524:       /* printf(" age= %d meandiff[%d]=%f, agefin=%d max[%d]=%f min[%d]=%f maxmax=%f\n", (int)age, j, meandiff[j],(int)agefin, j, max[j], j, min[j],maxmax); */
1.169     brouard  2525:     } /* j loop */
1.203     brouard  2526:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2527:     /* printf("maxmax=%lf maxmin=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, maxmin, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.126     brouard  2528:     if(maxmax < ftolpl){
1.209     brouard  2529:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2530:       free_vector(min,1,nlstate);
                   2531:       free_vector(max,1,nlstate);
                   2532:       free_vector(meandiff,1,nlstate);
1.126     brouard  2533:       return prlim;
                   2534:     }
1.169     brouard  2535:   } /* age loop */
1.208     brouard  2536:     /* After some age loop it doesn't converge */
1.209     brouard  2537:   printf("Warning: the stable prevalence at age %d did not converge with the required precision (%g > ftolpl=%g) within %.0f years. Try to lower 'ftolpl'. \n\
1.208     brouard  2538: Earliest age to start was %d-%d=%d, ncvloop=%d, ncvyear=%d\n", (int)age, maxmax, ftolpl, delaymax, (int)age, (int)delaymax, (int)agefin, ncvloop, *ncvyear);
1.209     brouard  2539:   /* Try to lower 'ftol', for example from 1.e-8 to 6.e-9.\n", ftolpl, (int)age, (int)delaymax, (int)agefin, ncvloop, (int)age-(int)agefin); */
                   2540:   free_vector(min,1,nlstate);
                   2541:   free_vector(max,1,nlstate);
                   2542:   free_vector(meandiff,1,nlstate);
1.208     brouard  2543:   
1.169     brouard  2544:   return prlim; /* should not reach here */
1.126     brouard  2545: }
                   2546: 
1.217     brouard  2547: 
                   2548:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   2549: 
1.218     brouard  2550:  /* double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ageminpar, double agemaxpar, double **oldm, double **savm, double **dnewm, double **doldm, double **dsavm, double ftolpl, int *ncvyear, int ij) */
                   2551:  /* double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double **oldm, double **savm, double **dnewm, double **doldm, double **dsavm, double ftolpl, int *ncvyear, int ij) */
1.242     brouard  2552:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  2553: {
1.218     brouard  2554:   /* Computes the prevalence limit in each live state at age x and covariate ij by left multiplying the unit
1.217     brouard  2555:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   2556:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2557:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2558:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2559:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2560:   /* Initial matrix pimij */
                   2561:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2562:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2563:   /*  0,                   0                  , 1} */
                   2564:   /*
                   2565:    * and after some iteration: */
                   2566:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2567:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2568:   /*  0,                   0                  , 1} */
                   2569:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2570:   /* {0.51571254859325999, 0.4842874514067399, */
                   2571:   /*  0.51326036147820708, 0.48673963852179264} */
                   2572:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2573: 
                   2574:   int i, ii,j,k;
                   2575:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   2576:   /* double **matprod2(); */ /* test */
                   2577:   double **out, cov[NCOVMAX+1], **bmij();
                   2578:   double **newm;
1.218     brouard  2579:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   2580:   double        **oldm, **savm;  /* for use */
                   2581: 
1.217     brouard  2582:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   2583:   int ncvloop=0;
                   2584:   
                   2585:   min=vector(1,nlstate);
                   2586:   max=vector(1,nlstate);
                   2587:   meandiff=vector(1,nlstate);
                   2588: 
1.218     brouard  2589:        dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   2590:        oldm=oldms; savm=savms;
                   2591: 
                   2592:        /* Starting with matrix unity */
                   2593:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2594:                for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  2595:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2596:     }
                   2597:   
                   2598:   cov[1]=1.;
                   2599:   
                   2600:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2601:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  2602:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   2603:   for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  2604:     ncvloop++;
1.218     brouard  2605:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   2606:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  2607:     /* Covariates have to be included here again */
                   2608:     cov[2]=agefin;
                   2609:     if(nagesqr==1)
                   2610:       cov[3]= agefin*agefin;;
1.242     brouard  2611:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2612:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2613:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
                   2614:       /* printf("bprevalim Dummy combi=%d k=%d TvarsD[%d]=V%d TvarsDind[%d]=%d nbcode=%d cov=%lf codtabm(%d,Tvar[%d])=%d \n",ij,k, k, TvarsD[k],k,TvarsDind[k],nbcode[TvarsD[k]][codtabm(ij,k)],cov[2+nagesqr+TvarsDind[k]], ij, k, codtabm(ij,k)); */
                   2615:     }
                   2616:     /* for (k=1; k<=cptcovn;k++) { */
                   2617:     /*   /\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\/ */
                   2618:     /*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   2619:     /*   /\* printf("prevalim ij=%d k=%d Tvar[%d]=%d nbcode=%d cov=%lf codtabm(%d,Tvar[%d])=%d \n",ij,k, k, Tvar[k],nbcode[Tvar[k]][codtabm(ij,Tvar[k])],cov[2+k], ij, k, codtabm(ij,Tvar[k])]); *\/ */
                   2620:     /* } */
                   2621:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2622:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   2623:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   2624:       /* printf("prevalim Quantitative k=%d  TvarsQind[%d]=%d, TvarsQ[%d]=V%d,Tqresult[%d][%d]=%f\n",k,k,TvarsQind[k],k,TvarsQ[k],nres,k,Tqresult[nres][k]); */
                   2625:     }
                   2626:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; */
                   2627:     /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
                   2628:     /*   /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\/ */
                   2629:     /*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; */
                   2630:     for (k=1; k<=cptcovage;k++){  /* For product with age */
                   2631:       if(Dummy[Tvar[Tage[k]]]){
                   2632:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2633:       } else{
                   2634:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   2635:       }
                   2636:       /* printf("prevalim Age combi=%d k=%d  Tage[%d]=V%d Tqresult[%d][%d]=%f\n",ij,k,k,Tage[k],nres,k,Tqresult[nres][k]); */
                   2637:     }
                   2638:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
                   2639:       /* printf("prevalim Prod ij=%d k=%d  Tprod[%d]=%d Tvard[%d][1]=V%d, Tvard[%d][2]=V%d\n",ij,k,k,Tprod[k], k,Tvard[k][1], k,Tvard[k][2]); */
                   2640:       if(Dummy[Tvard[k][1]==0]){
                   2641:        if(Dummy[Tvard[k][2]==0]){
                   2642:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2643:        }else{
                   2644:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
                   2645:        }
                   2646:       }else{
                   2647:        if(Dummy[Tvard[k][2]==0]){
                   2648:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
                   2649:        }else{
                   2650:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   2651:        }
                   2652:       }
1.217     brouard  2653:     }
                   2654:     
                   2655:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2656:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2657:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   2658:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2659:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2660:                /* ij should be linked to the correct index of cov */
                   2661:                /* age and covariate values ij are in 'cov', but we need to pass
                   2662:                 * ij for the observed prevalence at age and status and covariate
                   2663:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   2664:                 */
                   2665:     /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, ageminpar, agemaxpar, dnewm, doldm, dsavm,ij)); /\* Bug Valgrind *\/ */
                   2666:     /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij)); /\* Bug Valgrind *\/ */
                   2667:     out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij)); /* Bug Valgrind */
1.217     brouard  2668:     savm=oldm;
                   2669:     oldm=newm;
                   2670:     for(j=1; j<=nlstate; j++){
                   2671:       max[j]=0.;
                   2672:       min[j]=1.;
                   2673:     }
                   2674:     for(j=1; j<=nlstate; j++){ 
                   2675:       for(i=1;i<=nlstate;i++){
1.234     brouard  2676:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   2677:        bprlim[i][j]= newm[i][j];
                   2678:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   2679:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  2680:       }
                   2681:     }
1.218     brouard  2682:                
1.217     brouard  2683:     maxmax=0.;
                   2684:     for(i=1; i<=nlstate; i++){
                   2685:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column */
                   2686:       maxmax=FMAX(maxmax,meandiff[i]);
                   2687:       /* printf("Back age= %d meandiff[%d]=%f, agefin=%d max[%d]=%f min[%d]=%f maxmax=%f\n", (int)age, i, meandiff[i],(int)agefin, i, max[i], i, min[i],maxmax); */
                   2688:     } /* j loop */
                   2689:     *ncvyear= -( (int)age- (int)agefin);
1.218     brouard  2690:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear);*/
1.217     brouard  2691:     if(maxmax < ftolpl){
1.220     brouard  2692:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  2693:       free_vector(min,1,nlstate);
                   2694:       free_vector(max,1,nlstate);
                   2695:       free_vector(meandiff,1,nlstate);
                   2696:       return bprlim;
                   2697:     }
                   2698:   } /* age loop */
                   2699:     /* After some age loop it doesn't converge */
                   2700:   printf("Warning: the back stable prevalence at age %d did not converge with the required precision (%g > ftolpl=%g) within %.0f years. Try to lower 'ftolpl'. \n\
                   2701: Oldest age to start was %d-%d=%d, ncvloop=%d, ncvyear=%d\n", (int)age, maxmax, ftolpl, delaymax, (int)age, (int)delaymax, (int)agefin, ncvloop, *ncvyear);
                   2702:   /* Try to lower 'ftol', for example from 1.e-8 to 6.e-9.\n", ftolpl, (int)age, (int)delaymax, (int)agefin, ncvloop, (int)age-(int)agefin); */
                   2703:   free_vector(min,1,nlstate);
                   2704:   free_vector(max,1,nlstate);
                   2705:   free_vector(meandiff,1,nlstate);
                   2706:   
                   2707:   return bprlim; /* should not reach here */
                   2708: }
                   2709: 
1.126     brouard  2710: /*************** transition probabilities ***************/ 
                   2711: 
                   2712: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   2713: {
1.138     brouard  2714:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2715:      computes the probability to be observed in state j being in state i by appying the
                   2716:      model to the ncovmodel covariates (including constant and age).
                   2717:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2718:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2719:      ncth covariate in the global vector x is given by the formula:
                   2720:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2721:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2722:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2723:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2724:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2725:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2726:   */
                   2727:   double s1, lnpijopii;
1.126     brouard  2728:   /*double t34;*/
1.164     brouard  2729:   int i,j, nc, ii, jj;
1.126     brouard  2730: 
1.223     brouard  2731:   for(i=1; i<= nlstate; i++){
                   2732:     for(j=1; j<i;j++){
                   2733:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2734:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2735:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2736:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2737:       }
                   2738:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2739:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2740:     }
                   2741:     for(j=i+1; j<=nlstate+ndeath;j++){
                   2742:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2743:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2744:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2745:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   2746:       }
                   2747:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2748:     }
                   2749:   }
1.218     brouard  2750:   
1.223     brouard  2751:   for(i=1; i<= nlstate; i++){
                   2752:     s1=0;
                   2753:     for(j=1; j<i; j++){
                   2754:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2755:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2756:     }
                   2757:     for(j=i+1; j<=nlstate+ndeath; j++){
                   2758:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2759:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2760:     }
                   2761:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   2762:     ps[i][i]=1./(s1+1.);
                   2763:     /* Computing other pijs */
                   2764:     for(j=1; j<i; j++)
                   2765:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2766:     for(j=i+1; j<=nlstate+ndeath; j++)
                   2767:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2768:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2769:   } /* end i */
1.218     brouard  2770:   
1.223     brouard  2771:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2772:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   2773:       ps[ii][jj]=0;
                   2774:       ps[ii][ii]=1;
                   2775:     }
                   2776:   }
1.218     brouard  2777:   
                   2778:   
1.223     brouard  2779:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2780:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2781:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2782:   /*   } */
                   2783:   /*   printf("\n "); */
                   2784:   /* } */
                   2785:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   2786:   /*
                   2787:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  2788:                goto end;*/
1.223     brouard  2789:   return ps;
1.126     brouard  2790: }
                   2791: 
1.218     brouard  2792: /*************** backward transition probabilities ***************/ 
                   2793: 
                   2794:  /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ageminpar, double agemaxpar, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   2795: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   2796:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   2797: {
1.222     brouard  2798:   /* Computes the backward probability at age agefin and covariate ij
                   2799:    * and returns in **ps as well as **bmij.
                   2800:    */
1.218     brouard  2801:   int i, ii, j,k;
1.222     brouard  2802:   
                   2803:   double **out, **pmij();
                   2804:   double sumnew=0.;
1.218     brouard  2805:   double agefin;
1.222     brouard  2806:   
                   2807:   double **dnewm, **dsavm, **doldm;
                   2808:   double **bbmij;
                   2809:   
1.218     brouard  2810:   doldm=ddoldms; /* global pointers */
1.222     brouard  2811:   dnewm=ddnewms;
                   2812:   dsavm=ddsavms;
                   2813:   
                   2814:   agefin=cov[2];
                   2815:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
                   2816:      the observed prevalence (with this covariate ij) */
                   2817:   dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate);
                   2818:   /* We do have the matrix Px in savm  and we need pij */
                   2819:   for (j=1;j<=nlstate+ndeath;j++){
                   2820:     sumnew=0.; /* w1 p11 + w2 p21 only on live states */
                   2821:     for (ii=1;ii<=nlstate;ii++){
                   2822:       sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij];
                   2823:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
                   2824:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   2825:       if(sumnew >= 1.e-10){
                   2826:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
                   2827:        /*      doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
                   2828:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
                   2829:        /*      doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
                   2830:        /* }else */
                   2831:        doldm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   2832:       }else{
1.242     brouard  2833:        ;
                   2834:        /* printf("ii=%d, i=%d, doldm=%lf dsavm=%lf, probs=%lf, sumnew=%lf,agefin=%d\n",ii,j,doldm[ii][j],dsavm[ii][j],prevacurrent[(int)agefin][ii][ij],sumnew, (int)agefin); */
1.222     brouard  2835:       }
                   2836:     } /*End ii */
                   2837:   } /* End j, At the end doldm is diag[1/(w_1p1i+w_2 p2i)] */
                   2838:   /* left Product of this diag matrix by dsavm=Px (newm=dsavm*doldm) */
                   2839:   bbmij=matprod2(dnewm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, doldm); /* Bug Valgrind */
                   2840:   /* dsavm=doldm; /\* dsavm is now diag [1/(w_1p1i+w_2 p2i)] but can be overwritten*\/ */
                   2841:   /* doldm=dnewm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
                   2842:   /* dnewm=dsavm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
                   2843:   /* left Product of this matrix by diag matrix of prevalences (savm) */
                   2844:   for (j=1;j<=nlstate+ndeath;j++){
                   2845:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   2846:       dsavm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij] : 0.0);
                   2847:     }
                   2848:   } /* End j, At the end oldm is diag[1/(w_1p1i+w_2 p2i)] */
                   2849:   ps=matprod2(doldm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dnewm); /* Bug Valgrind */
                   2850:   /* newm or out is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
                   2851:   /* end bmij */
                   2852:   return ps; 
1.218     brouard  2853: }
1.217     brouard  2854: /*************** transition probabilities ***************/ 
                   2855: 
1.218     brouard  2856: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  2857: {
                   2858:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2859:      computes the probability to be observed in state j being in state i by appying the
                   2860:      model to the ncovmodel covariates (including constant and age).
                   2861:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2862:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2863:      ncth covariate in the global vector x is given by the formula:
                   2864:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2865:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2866:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2867:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2868:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2869:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2870:   */
                   2871:   double s1, lnpijopii;
                   2872:   /*double t34;*/
                   2873:   int i,j, nc, ii, jj;
                   2874: 
1.234     brouard  2875:   for(i=1; i<= nlstate; i++){
                   2876:     for(j=1; j<i;j++){
                   2877:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2878:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2879:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2880:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2881:       }
                   2882:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2883:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2884:     }
                   2885:     for(j=i+1; j<=nlstate+ndeath;j++){
                   2886:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2887:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2888:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2889:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   2890:       }
                   2891:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2892:     }
                   2893:   }
                   2894:   
                   2895:   for(i=1; i<= nlstate; i++){
                   2896:     s1=0;
                   2897:     for(j=1; j<i; j++){
                   2898:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2899:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2900:     }
                   2901:     for(j=i+1; j<=nlstate+ndeath; j++){
                   2902:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2903:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2904:     }
                   2905:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   2906:     ps[i][i]=1./(s1+1.);
                   2907:     /* Computing other pijs */
                   2908:     for(j=1; j<i; j++)
                   2909:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2910:     for(j=i+1; j<=nlstate+ndeath; j++)
                   2911:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2912:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2913:   } /* end i */
                   2914:   
                   2915:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2916:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   2917:       ps[ii][jj]=0;
                   2918:       ps[ii][ii]=1;
                   2919:     }
                   2920:   }
                   2921:   /* Added for backcast */ /* Transposed matrix too */
                   2922:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   2923:     s1=0.;
                   2924:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   2925:       s1+=ps[ii][jj];
                   2926:     }
                   2927:     for(ii=1; ii<= nlstate; ii++){
                   2928:       ps[ii][jj]=ps[ii][jj]/s1;
                   2929:     }
                   2930:   }
                   2931:   /* Transposition */
                   2932:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   2933:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   2934:       s1=ps[ii][jj];
                   2935:       ps[ii][jj]=ps[jj][ii];
                   2936:       ps[jj][ii]=s1;
                   2937:     }
                   2938:   }
                   2939:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2940:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2941:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2942:   /*   } */
                   2943:   /*   printf("\n "); */
                   2944:   /* } */
                   2945:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   2946:   /*
                   2947:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   2948:     goto end;*/
                   2949:   return ps;
1.217     brouard  2950: }
                   2951: 
                   2952: 
1.126     brouard  2953: /**************** Product of 2 matrices ******************/
                   2954: 
1.145     brouard  2955: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  2956: {
                   2957:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   2958:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   2959:   /* in, b, out are matrice of pointers which should have been initialized 
                   2960:      before: only the contents of out is modified. The function returns
                   2961:      a pointer to pointers identical to out */
1.145     brouard  2962:   int i, j, k;
1.126     brouard  2963:   for(i=nrl; i<= nrh; i++)
1.145     brouard  2964:     for(k=ncolol; k<=ncoloh; k++){
                   2965:       out[i][k]=0.;
                   2966:       for(j=ncl; j<=nch; j++)
                   2967:        out[i][k] +=in[i][j]*b[j][k];
                   2968:     }
1.126     brouard  2969:   return out;
                   2970: }
                   2971: 
                   2972: 
                   2973: /************* Higher Matrix Product ***************/
                   2974: 
1.235     brouard  2975: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij, int nres )
1.126     brouard  2976: {
1.218     brouard  2977:   /* Computes the transition matrix starting at age 'age' and combination of covariate values corresponding to ij over 
1.126     brouard  2978:      'nhstepm*hstepm*stepm' months (i.e. until
                   2979:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   2980:      nhstepm*hstepm matrices. 
                   2981:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   2982:      (typically every 2 years instead of every month which is too big 
                   2983:      for the memory).
                   2984:      Model is determined by parameters x and covariates have to be 
                   2985:      included manually here. 
                   2986: 
                   2987:      */
                   2988: 
                   2989:   int i, j, d, h, k;
1.131     brouard  2990:   double **out, cov[NCOVMAX+1];
1.126     brouard  2991:   double **newm;
1.187     brouard  2992:   double agexact;
1.214     brouard  2993:   double agebegin, ageend;
1.126     brouard  2994: 
                   2995:   /* Hstepm could be zero and should return the unit matrix */
                   2996:   for (i=1;i<=nlstate+ndeath;i++)
                   2997:     for (j=1;j<=nlstate+ndeath;j++){
                   2998:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   2999:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3000:     }
                   3001:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3002:   for(h=1; h <=nhstepm; h++){
                   3003:     for(d=1; d <=hstepm; d++){
                   3004:       newm=savm;
                   3005:       /* Covariates have to be included here again */
                   3006:       cov[1]=1.;
1.214     brouard  3007:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3008:       cov[2]=agexact;
                   3009:       if(nagesqr==1)
1.227     brouard  3010:        cov[3]= agexact*agexact;
1.235     brouard  3011:       for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   3012:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   3013:        cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
                   3014:        /* printf("hpxij Dummy combi=%d k=%d TvarsD[%d]=V%d TvarsDind[%d]=%d nbcode=%d cov=%lf codtabm(%d,Tvar[%d])=%d \n",ij,k, k, TvarsD[k],k,TvarsDind[k],nbcode[TvarsD[k]][codtabm(ij,k)],cov[2+nagesqr+TvarsDind[k]], ij, k, codtabm(ij,k)); */
                   3015:       }
                   3016:       for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   3017:        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   3018:        cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   3019:        /* printf("hPxij Quantitative k=%d  TvarsQind[%d]=%d, TvarsQ[%d]=V%d,Tqresult[%d][%d]=%f\n",k,k,TvarsQind[k],k,TvarsQ[k],nres,k,Tqresult[nres][k]); */
                   3020:       }
                   3021:       for (k=1; k<=cptcovage;k++){
                   3022:        if(Dummy[Tvar[Tage[k]]]){
                   3023:          cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   3024:        } else{
                   3025:          cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   3026:        }
                   3027:        /* printf("hPxij Age combi=%d k=%d  Tage[%d]=V%d Tqresult[%d][%d]=%f\n",ij,k,k,Tage[k],nres,k,Tqresult[nres][k]); */
                   3028:       }
                   3029:       for (k=1; k<=cptcovprod;k++){ /*  */
                   3030:        /* printf("hPxij Prod ij=%d k=%d  Tprod[%d]=%d Tvard[%d][1]=V%d, Tvard[%d][2]=V%d\n",ij,k,k,Tprod[k], k,Tvard[k][1], k,Tvard[k][2]); */
                   3031:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   3032:       }
                   3033:       /* for (k=1; k<=cptcovn;k++)  */
                   3034:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3035:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3036:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3037:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3038:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3039:       
                   3040:       
1.126     brouard  3041:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3042:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.218     brouard  3043:                        /* right multiplication of oldm by the current matrix */
1.126     brouard  3044:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3045:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3046:       /* if((int)age == 70){ */
                   3047:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3048:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3049:       /*         printf("%d pmmij ",i); */
                   3050:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3051:       /*           printf("%f ",pmmij[i][j]); */
                   3052:       /*         } */
                   3053:       /*         printf(" oldm "); */
                   3054:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3055:       /*           printf("%f ",oldm[i][j]); */
                   3056:       /*         } */
                   3057:       /*         printf("\n"); */
                   3058:       /*       } */
                   3059:       /* } */
1.126     brouard  3060:       savm=oldm;
                   3061:       oldm=newm;
                   3062:     }
                   3063:     for(i=1; i<=nlstate+ndeath; i++)
                   3064:       for(j=1;j<=nlstate+ndeath;j++) {
1.218     brouard  3065:                                po[i][j][h]=newm[i][j];
                   3066:                                /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3067:       }
1.128     brouard  3068:     /*printf("h=%d ",h);*/
1.126     brouard  3069:   } /* end h */
1.218     brouard  3070:        /*     printf("\n H=%d \n",h); */
1.126     brouard  3071:   return po;
                   3072: }
                   3073: 
1.217     brouard  3074: /************* Higher Back Matrix Product ***************/
1.218     brouard  3075: /* double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, double ***prevacurrent, int nlstate, int stepm, double **oldm, double **savm, double **dnewm, double **doldm, double **dsavm, int ij ) */
1.222     brouard  3076: double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, double ***prevacurrent, int nlstate, int stepm, int ij )
1.217     brouard  3077: {
1.218     brouard  3078:   /* Computes the transition matrix starting at age 'age' over
1.217     brouard  3079:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3080:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3081:      nhstepm*hstepm matrices.
                   3082:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3083:      (typically every 2 years instead of every month which is too big
1.217     brouard  3084:      for the memory).
1.218     brouard  3085:      Model is determined by parameters x and covariates have to be
                   3086:      included manually here.
1.217     brouard  3087: 
1.222     brouard  3088:   */
1.217     brouard  3089: 
                   3090:   int i, j, d, h, k;
                   3091:   double **out, cov[NCOVMAX+1];
                   3092:   double **newm;
                   3093:   double agexact;
                   3094:   double agebegin, ageend;
1.222     brouard  3095:   double **oldm, **savm;
1.217     brouard  3096: 
1.222     brouard  3097:   oldm=oldms;savm=savms;
1.217     brouard  3098:   /* Hstepm could be zero and should return the unit matrix */
                   3099:   for (i=1;i<=nlstate+ndeath;i++)
                   3100:     for (j=1;j<=nlstate+ndeath;j++){
                   3101:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3102:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3103:     }
                   3104:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3105:   for(h=1; h <=nhstepm; h++){
                   3106:     for(d=1; d <=hstepm; d++){
                   3107:       newm=savm;
                   3108:       /* Covariates have to be included here again */
                   3109:       cov[1]=1.;
                   3110:       agexact=age-((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
                   3111:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
                   3112:       cov[2]=agexact;
                   3113:       if(nagesqr==1)
1.222     brouard  3114:        cov[3]= agexact*agexact;
1.218     brouard  3115:       for (k=1; k<=cptcovn;k++)
1.222     brouard  3116:        cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   3117:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.217     brouard  3118:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
1.222     brouard  3119:        /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   3120:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   3121:       /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
1.217     brouard  3122:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.222     brouard  3123:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
                   3124:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
1.218     brouard  3125:                        
                   3126:                        
1.217     brouard  3127:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3128:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.218     brouard  3129:       /* Careful transposed matrix */
1.222     brouard  3130:       /* age is in cov[2] */
1.218     brouard  3131:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3132:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3133:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.222     brouard  3134:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
1.217     brouard  3135:       /* if((int)age == 70){ */
                   3136:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3137:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3138:       /*         printf("%d pmmij ",i); */
                   3139:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3140:       /*           printf("%f ",pmmij[i][j]); */
                   3141:       /*         } */
                   3142:       /*         printf(" oldm "); */
                   3143:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3144:       /*           printf("%f ",oldm[i][j]); */
                   3145:       /*         } */
                   3146:       /*         printf("\n"); */
                   3147:       /*       } */
                   3148:       /* } */
                   3149:       savm=oldm;
                   3150:       oldm=newm;
                   3151:     }
                   3152:     for(i=1; i<=nlstate+ndeath; i++)
                   3153:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3154:        po[i][j][h]=newm[i][j];
                   3155:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.217     brouard  3156:       }
                   3157:     /*printf("h=%d ",h);*/
                   3158:   } /* end h */
1.222     brouard  3159:   /*     printf("\n H=%d \n",h); */
1.217     brouard  3160:   return po;
                   3161: }
                   3162: 
                   3163: 
1.162     brouard  3164: #ifdef NLOPT
                   3165:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3166:   double fret;
                   3167:   double *xt;
                   3168:   int j;
                   3169:   myfunc_data *d2 = (myfunc_data *) pd;
                   3170: /* xt = (p1-1); */
                   3171:   xt=vector(1,n); 
                   3172:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3173: 
                   3174:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3175:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3176:   printf("Function = %.12lf ",fret);
                   3177:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3178:   printf("\n");
                   3179:  free_vector(xt,1,n);
                   3180:   return fret;
                   3181: }
                   3182: #endif
1.126     brouard  3183: 
                   3184: /*************** log-likelihood *************/
                   3185: double func( double *x)
                   3186: {
1.226     brouard  3187:   int i, ii, j, k, mi, d, kk;
                   3188:   int ioffset=0;
                   3189:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3190:   double **out;
                   3191:   double lli; /* Individual log likelihood */
                   3192:   int s1, s2;
1.228     brouard  3193:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
1.226     brouard  3194:   double bbh, survp;
                   3195:   long ipmx;
                   3196:   double agexact;
                   3197:   /*extern weight */
                   3198:   /* We are differentiating ll according to initial status */
                   3199:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3200:   /*for(i=1;i<imx;i++) 
                   3201:     printf(" %d\n",s[4][i]);
                   3202:   */
1.162     brouard  3203: 
1.226     brouard  3204:   ++countcallfunc;
1.162     brouard  3205: 
1.226     brouard  3206:   cov[1]=1.;
1.126     brouard  3207: 
1.226     brouard  3208:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3209:   ioffset=0;
1.226     brouard  3210:   if(mle==1){
                   3211:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3212:       /* Computes the values of the ncovmodel covariates of the model
                   3213:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   3214:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   3215:         to be observed in j being in i according to the model.
                   3216:       */
1.243   ! brouard  3217:       ioffset=2+nagesqr ;
1.233     brouard  3218:    /* Fixed */
1.234     brouard  3219:       for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
                   3220:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, only V1 is fixed (k=6)*/
                   3221:       }
1.226     brouard  3222:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   3223:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
                   3224:         has been calculated etc */
                   3225:       /* For an individual i, wav[i] gives the number of effective waves */
                   3226:       /* We compute the contribution to Likelihood of each effective transition
                   3227:         mw[mi][i] is real wave of the mi th effectve wave */
                   3228:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   3229:         s2=s[mw[mi+1][i]][i];
                   3230:         And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
                   3231:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   3232:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   3233:       */
                   3234:       for(mi=1; mi<= wav[i]-1; mi++){
1.234     brouard  3235:        for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242     brouard  3236:          /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
                   3237:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
1.234     brouard  3238:        }
                   3239:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3240:          for (j=1;j<=nlstate+ndeath;j++){
                   3241:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3242:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3243:          }
                   3244:        for(d=0; d<dh[mi][i]; d++){
                   3245:          newm=savm;
                   3246:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3247:          cov[2]=agexact;
                   3248:          if(nagesqr==1)
                   3249:            cov[3]= agexact*agexact;  /* Should be changed here */
                   3250:          for (kk=1; kk<=cptcovage;kk++) {
1.242     brouard  3251:          if(!FixedV[Tvar[Tage[kk]]])
1.234     brouard  3252:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.242     brouard  3253:          else
                   3254:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
1.234     brouard  3255:          }
                   3256:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3257:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3258:          savm=oldm;
                   3259:          oldm=newm;
                   3260:        } /* end mult */
                   3261:        
                   3262:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   3263:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   3264:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   3265:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   3266:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   3267:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   3268:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   3269:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  3270:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   3271:                                 * -stepm/2 to stepm/2 .
                   3272:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   3273:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   3274:                                 */
1.234     brouard  3275:        s1=s[mw[mi][i]][i];
                   3276:        s2=s[mw[mi+1][i]][i];
                   3277:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3278:        /* bias bh is positive if real duration
                   3279:         * is higher than the multiple of stepm and negative otherwise.
                   3280:         */
                   3281:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   3282:        if( s2 > nlstate){ 
                   3283:          /* i.e. if s2 is a death state and if the date of death is known 
                   3284:             then the contribution to the likelihood is the probability to 
                   3285:             die between last step unit time and current  step unit time, 
                   3286:             which is also equal to probability to die before dh 
                   3287:             minus probability to die before dh-stepm . 
                   3288:             In version up to 0.92 likelihood was computed
                   3289:             as if date of death was unknown. Death was treated as any other
                   3290:             health state: the date of the interview describes the actual state
                   3291:             and not the date of a change in health state. The former idea was
                   3292:             to consider that at each interview the state was recorded
                   3293:             (healthy, disable or death) and IMaCh was corrected; but when we
                   3294:             introduced the exact date of death then we should have modified
                   3295:             the contribution of an exact death to the likelihood. This new
                   3296:             contribution is smaller and very dependent of the step unit
                   3297:             stepm. It is no more the probability to die between last interview
                   3298:             and month of death but the probability to survive from last
                   3299:             interview up to one month before death multiplied by the
                   3300:             probability to die within a month. Thanks to Chris
                   3301:             Jackson for correcting this bug.  Former versions increased
                   3302:             mortality artificially. The bad side is that we add another loop
                   3303:             which slows down the processing. The difference can be up to 10%
                   3304:             lower mortality.
                   3305:          */
                   3306:          /* If, at the beginning of the maximization mostly, the
                   3307:             cumulative probability or probability to be dead is
                   3308:             constant (ie = 1) over time d, the difference is equal to
                   3309:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   3310:             s1 at precedent wave, to be dead a month before current
                   3311:             wave is equal to probability, being at state s1 at
                   3312:             precedent wave, to be dead at mont of the current
                   3313:             wave. Then the observed probability (that this person died)
                   3314:             is null according to current estimated parameter. In fact,
                   3315:             it should be very low but not zero otherwise the log go to
                   3316:             infinity.
                   3317:          */
1.183     brouard  3318: /* #ifdef INFINITYORIGINAL */
                   3319: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3320: /* #else */
                   3321: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   3322: /*         lli=log(mytinydouble); */
                   3323: /*       else */
                   3324: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3325: /* #endif */
1.226     brouard  3326:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3327:          
1.226     brouard  3328:        } else if  ( s2==-1 ) { /* alive */
                   3329:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3330:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3331:          /*survp += out[s1][j]; */
                   3332:          lli= log(survp);
                   3333:        }
                   3334:        else if  (s2==-4) { 
                   3335:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   3336:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3337:          lli= log(survp); 
                   3338:        } 
                   3339:        else if  (s2==-5) { 
                   3340:          for (j=1,survp=0. ; j<=2; j++)  
                   3341:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3342:          lli= log(survp); 
                   3343:        } 
                   3344:        else{
                   3345:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3346:          /*  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 */
                   3347:        } 
                   3348:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   3349:        /*if(lli ==000.0)*/
                   3350:        /*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); */
                   3351:        ipmx +=1;
                   3352:        sw += weight[i];
                   3353:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3354:        /* if (lli < log(mytinydouble)){ */
                   3355:        /*   printf("Close to inf lli = %.10lf <  %.10lf i= %d mi= %d, s[%d][i]=%d s1=%d s2=%d\n", lli,log(mytinydouble), i, mi,mw[mi][i], s[mw[mi][i]][i], s1,s2); */
                   3356:        /*   fprintf(ficlog,"Close to inf lli = %.10lf i= %d mi= %d, s[mw[mi][i]][i]=%d\n", lli, i, mi,s[mw[mi][i]][i]); */
                   3357:        /* } */
                   3358:       } /* end of wave */
                   3359:     } /* end of individual */
                   3360:   }  else if(mle==2){
                   3361:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3362:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3363:       for(mi=1; mi<= wav[i]-1; mi++){
                   3364:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3365:          for (j=1;j<=nlstate+ndeath;j++){
                   3366:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3367:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3368:          }
                   3369:        for(d=0; d<=dh[mi][i]; d++){
                   3370:          newm=savm;
                   3371:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3372:          cov[2]=agexact;
                   3373:          if(nagesqr==1)
                   3374:            cov[3]= agexact*agexact;
                   3375:          for (kk=1; kk<=cptcovage;kk++) {
                   3376:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3377:          }
                   3378:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3379:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3380:          savm=oldm;
                   3381:          oldm=newm;
                   3382:        } /* end mult */
                   3383:       
                   3384:        s1=s[mw[mi][i]][i];
                   3385:        s2=s[mw[mi+1][i]][i];
                   3386:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3387:        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 */
                   3388:        ipmx +=1;
                   3389:        sw += weight[i];
                   3390:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3391:       } /* end of wave */
                   3392:     } /* end of individual */
                   3393:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   3394:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3395:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3396:       for(mi=1; mi<= wav[i]-1; mi++){
                   3397:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3398:          for (j=1;j<=nlstate+ndeath;j++){
                   3399:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3400:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3401:          }
                   3402:        for(d=0; d<dh[mi][i]; d++){
                   3403:          newm=savm;
                   3404:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3405:          cov[2]=agexact;
                   3406:          if(nagesqr==1)
                   3407:            cov[3]= agexact*agexact;
                   3408:          for (kk=1; kk<=cptcovage;kk++) {
                   3409:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3410:          }
                   3411:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3412:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3413:          savm=oldm;
                   3414:          oldm=newm;
                   3415:        } /* end mult */
                   3416:       
                   3417:        s1=s[mw[mi][i]][i];
                   3418:        s2=s[mw[mi+1][i]][i];
                   3419:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3420:        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 */
                   3421:        ipmx +=1;
                   3422:        sw += weight[i];
                   3423:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3424:       } /* end of wave */
                   3425:     } /* end of individual */
                   3426:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   3427:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3428:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3429:       for(mi=1; mi<= wav[i]-1; mi++){
                   3430:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3431:          for (j=1;j<=nlstate+ndeath;j++){
                   3432:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3433:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3434:          }
                   3435:        for(d=0; d<dh[mi][i]; d++){
                   3436:          newm=savm;
                   3437:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3438:          cov[2]=agexact;
                   3439:          if(nagesqr==1)
                   3440:            cov[3]= agexact*agexact;
                   3441:          for (kk=1; kk<=cptcovage;kk++) {
                   3442:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3443:          }
1.126     brouard  3444:        
1.226     brouard  3445:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3446:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3447:          savm=oldm;
                   3448:          oldm=newm;
                   3449:        } /* end mult */
                   3450:       
                   3451:        s1=s[mw[mi][i]][i];
                   3452:        s2=s[mw[mi+1][i]][i];
                   3453:        if( s2 > nlstate){ 
                   3454:          lli=log(out[s1][s2] - savm[s1][s2]);
                   3455:        } else if  ( s2==-1 ) { /* alive */
                   3456:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3457:            survp += out[s1][j];
                   3458:          lli= log(survp);
                   3459:        }else{
                   3460:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3461:        }
                   3462:        ipmx +=1;
                   3463:        sw += weight[i];
                   3464:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.126     brouard  3465: /*     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]); */
1.226     brouard  3466:       } /* end of wave */
                   3467:     } /* end of individual */
                   3468:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   3469:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3470:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3471:       for(mi=1; mi<= wav[i]-1; mi++){
                   3472:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3473:          for (j=1;j<=nlstate+ndeath;j++){
                   3474:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3475:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3476:          }
                   3477:        for(d=0; d<dh[mi][i]; d++){
                   3478:          newm=savm;
                   3479:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3480:          cov[2]=agexact;
                   3481:          if(nagesqr==1)
                   3482:            cov[3]= agexact*agexact;
                   3483:          for (kk=1; kk<=cptcovage;kk++) {
                   3484:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3485:          }
1.126     brouard  3486:        
1.226     brouard  3487:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3488:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3489:          savm=oldm;
                   3490:          oldm=newm;
                   3491:        } /* end mult */
                   3492:       
                   3493:        s1=s[mw[mi][i]][i];
                   3494:        s2=s[mw[mi+1][i]][i];
                   3495:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3496:        ipmx +=1;
                   3497:        sw += weight[i];
                   3498:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3499:        /*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]);*/
                   3500:       } /* end of wave */
                   3501:     } /* end of individual */
                   3502:   } /* End of if */
                   3503:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3504:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3505:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3506:   return -l;
1.126     brouard  3507: }
                   3508: 
                   3509: /*************** log-likelihood *************/
                   3510: double funcone( double *x)
                   3511: {
1.228     brouard  3512:   /* Same as func but slower because of a lot of printf and if */
1.126     brouard  3513:   int i, ii, j, k, mi, d, kk;
1.228     brouard  3514:   int ioffset=0;
1.131     brouard  3515:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  3516:   double **out;
                   3517:   double lli; /* Individual log likelihood */
                   3518:   double llt;
                   3519:   int s1, s2;
1.228     brouard  3520:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   3521: 
1.126     brouard  3522:   double bbh, survp;
1.187     brouard  3523:   double agexact;
1.214     brouard  3524:   double agebegin, ageend;
1.126     brouard  3525:   /*extern weight */
                   3526:   /* We are differentiating ll according to initial status */
                   3527:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3528:   /*for(i=1;i<imx;i++) 
                   3529:     printf(" %d\n",s[4][i]);
                   3530:   */
                   3531:   cov[1]=1.;
                   3532: 
                   3533:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3534:   ioffset=0;
                   3535:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.243   ! brouard  3536:     /* ioffset=2+nagesqr+cptcovage; */
        !          3537:     ioffset=2+nagesqr;
1.232     brouard  3538:     /* Fixed */
1.224     brouard  3539:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  3540:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
                   3541:     for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
                   3542:       cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, only V1 is fixed (k=6)*/
                   3543: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   3544: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   3545: /*    cov[2+6]=covar[2][i]; V2  */
                   3546: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   3547: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   3548: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   3549: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   3550: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   3551: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  3552:     }
1.232     brouard  3553:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   3554:     /*   cov[++ioffset]=coqvar[TvarFQ[k]][i];/\* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, only V2 and V1*V2 is fixed (k=6 and 7?)*\/ */
                   3555:     /* } */
1.231     brouard  3556:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   3557:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   3558:     /* } */
1.225     brouard  3559:     
1.233     brouard  3560: 
                   3561:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.232     brouard  3562:     /* Wave varying (but not age varying) */
                   3563:       for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242     brouard  3564:        /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
                   3565:        cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
                   3566:       }
1.232     brouard  3567:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
1.242     brouard  3568:       /* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3569:       /* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
                   3570:       /* k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
                   3571:       /* cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
                   3572:       /* printf(" i=%d,mi=%d,itv=%d,TmodelInvind[itv]=%d,cotvar[mw[mi][i]][TmodelInvind[itv]][i]=%f\n", i, mi, itv, TmodelInvind[itv],cotvar[mw[mi][i]][TmodelInvind[itv]][i]); */
1.232     brouard  3573:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  3574:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3575:       /*       /\* printf(" i=%d,mi=%d,iqtv=%d,TmodelInvQind[iqtv]=%d,cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]=%f\n", i, mi, iqtv, TmodelInvQind[iqtv],cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]); *\/ */
                   3576:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  3577:       /* } */
1.126     brouard  3578:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  3579:        for (j=1;j<=nlstate+ndeath;j++){
                   3580:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3581:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3582:        }
1.214     brouard  3583:       
                   3584:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   3585:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   3586:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.242     brouard  3587:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   3588:          and mw[mi+1][i]. dh depends on stepm.*/
                   3589:        newm=savm;
                   3590:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3591:        cov[2]=agexact;
                   3592:        if(nagesqr==1)
                   3593:          cov[3]= agexact*agexact;
                   3594:        for (kk=1; kk<=cptcovage;kk++) {
                   3595:          if(!FixedV[Tvar[Tage[kk]]])
                   3596:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3597:          else
                   3598:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
                   3599:        }
                   3600:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   3601:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3602:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3603:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3604:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   3605:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   3606:        savm=oldm;
                   3607:        oldm=newm;
1.126     brouard  3608:       } /* end mult */
                   3609:       
                   3610:       s1=s[mw[mi][i]][i];
                   3611:       s2=s[mw[mi+1][i]][i];
1.217     brouard  3612:       /* if(s2==-1){ */
                   3613:       /*       printf(" s1=%d, s2=%d i=%d \n", s1, s2, i); */
                   3614:       /*       /\* exit(1); *\/ */
                   3615:       /* } */
1.126     brouard  3616:       bbh=(double)bh[mi][i]/(double)stepm; 
                   3617:       /* bias is positive if real duration
                   3618:        * is higher than the multiple of stepm and negative otherwise.
                   3619:        */
                   3620:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  3621:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3622:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  3623:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   3624:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3625:        lli= log(survp);
1.126     brouard  3626:       }else if (mle==1){
1.242     brouard  3627:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  3628:       } else if(mle==2){
1.242     brouard  3629:        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 */
1.126     brouard  3630:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  3631:        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 */
1.126     brouard  3632:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  3633:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  3634:       } else{  /* mle=0 back to 1 */
1.242     brouard  3635:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3636:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  3637:       } /* End of if */
                   3638:       ipmx +=1;
                   3639:       sw += weight[i];
                   3640:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  3641:       /*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]); */
1.126     brouard  3642:       if(globpr){
1.242     brouard  3643:        fprintf(ficresilk,"%9ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  3644:  %11.6f %11.6f %11.6f ", \
1.242     brouard  3645:                num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
                   3646:                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
                   3647:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   3648:          llt +=ll[k]*gipmx/gsw;
                   3649:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   3650:        }
                   3651:        fprintf(ficresilk," %10.6f\n", -llt);
1.126     brouard  3652:       }
1.232     brouard  3653:        } /* end of wave */
                   3654: } /* end of individual */
                   3655: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3656: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3657: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3658: if(globpr==0){ /* First time we count the contributions and weights */
                   3659:        gipmx=ipmx;
                   3660:        gsw=sw;
                   3661: }
                   3662: return -l;
1.126     brouard  3663: }
                   3664: 
                   3665: 
                   3666: /*************** function likelione ***********/
                   3667: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   3668: {
                   3669:   /* This routine should help understanding what is done with 
                   3670:      the selection of individuals/waves and
                   3671:      to check the exact contribution to the likelihood.
                   3672:      Plotting could be done.
                   3673:    */
                   3674:   int k;
                   3675: 
                   3676:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  3677:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  3678:     strcat(fileresilk,fileresu);
1.126     brouard  3679:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   3680:       printf("Problem with resultfile: %s\n", fileresilk);
                   3681:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   3682:     }
1.214     brouard  3683:     fprintf(ficresilk, "#individual(line's_record) count ageb ageend s1 s2 wave# effective_wave# number_of_matrices_product pij weight weight/gpw -2ln(pij)*weight 0pij_x 0pij_(x-stepm) cumulating_loglikeli_by_health_state(reweighted=-2ll*weightXnumber_of_contribs/sum_of_weights) and_total\n");
                   3684:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  3685:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   3686:     for(k=1; k<=nlstate; k++) 
                   3687:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   3688:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   3689:   }
                   3690: 
                   3691:   *fretone=(*funcone)(p);
                   3692:   if(*globpri !=0){
                   3693:     fclose(ficresilk);
1.205     brouard  3694:     if (mle ==0)
                   3695:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   3696:     else if(mle >=1)
                   3697:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   3698:     fprintf(fichtm," You should at least run with mle >= 1 to get starting values corresponding to the optimized parameters in order to visualize the real contribution of each individual/wave: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
1.207     brouard  3699:     
1.208     brouard  3700:       
                   3701:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  3702:       fprintf(fichtm,"<br>- Probability p<sub>%dj</sub> by origin %d and destination j. Dot's sizes are related to corresponding weight: <a href=\"%s-p%dj.png\">%s-p%dj.png</a><br> \
1.208     brouard  3703: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   3704:     }
1.207     brouard  3705:     fprintf(fichtm,"<br>- The function drawn is -2Log(L) in Log scale: by state of origin <a href=\"%s-ori.png\">%s-ori.png</a><br> \
1.204     brouard  3706: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3707:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  3708: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3709:     fflush(fichtm);
1.205     brouard  3710:   }
1.126     brouard  3711:   return;
                   3712: }
                   3713: 
                   3714: 
                   3715: /*********** Maximum Likelihood Estimation ***************/
                   3716: 
                   3717: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   3718: {
1.165     brouard  3719:   int i,j, iter=0;
1.126     brouard  3720:   double **xi;
                   3721:   double fret;
                   3722:   double fretone; /* Only one call to likelihood */
                   3723:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  3724: 
                   3725: #ifdef NLOPT
                   3726:   int creturn;
                   3727:   nlopt_opt opt;
                   3728:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   3729:   double *lb;
                   3730:   double minf; /* the minimum objective value, upon return */
                   3731:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   3732:   myfunc_data dinst, *d = &dinst;
                   3733: #endif
                   3734: 
                   3735: 
1.126     brouard  3736:   xi=matrix(1,npar,1,npar);
                   3737:   for (i=1;i<=npar;i++)
                   3738:     for (j=1;j<=npar;j++)
                   3739:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   3740:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  3741:   strcpy(filerespow,"POW_"); 
1.126     brouard  3742:   strcat(filerespow,fileres);
                   3743:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   3744:     printf("Problem with resultfile: %s\n", filerespow);
                   3745:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   3746:   }
                   3747:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   3748:   for (i=1;i<=nlstate;i++)
                   3749:     for(j=1;j<=nlstate+ndeath;j++)
                   3750:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   3751:   fprintf(ficrespow,"\n");
1.162     brouard  3752: #ifdef POWELL
1.126     brouard  3753:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  3754: #endif
1.126     brouard  3755: 
1.162     brouard  3756: #ifdef NLOPT
                   3757: #ifdef NEWUOA
                   3758:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   3759: #else
                   3760:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   3761: #endif
                   3762:   lb=vector(0,npar-1);
                   3763:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   3764:   nlopt_set_lower_bounds(opt, lb);
                   3765:   nlopt_set_initial_step1(opt, 0.1);
                   3766:   
                   3767:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   3768:   d->function = func;
                   3769:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   3770:   nlopt_set_min_objective(opt, myfunc, d);
                   3771:   nlopt_set_xtol_rel(opt, ftol);
                   3772:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   3773:     printf("nlopt failed! %d\n",creturn); 
                   3774:   }
                   3775:   else {
                   3776:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   3777:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   3778:     iter=1; /* not equal */
                   3779:   }
                   3780:   nlopt_destroy(opt);
                   3781: #endif
1.126     brouard  3782:   free_matrix(xi,1,npar,1,npar);
                   3783:   fclose(ficrespow);
1.203     brouard  3784:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   3785:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  3786:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  3787: 
                   3788: }
                   3789: 
                   3790: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  3791: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  3792: {
                   3793:   double  **a,**y,*x,pd;
1.203     brouard  3794:   /* double **hess; */
1.164     brouard  3795:   int i, j;
1.126     brouard  3796:   int *indx;
                   3797: 
                   3798:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  3799:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  3800:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   3801:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   3802:   double gompertz(double p[]);
1.203     brouard  3803:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  3804: 
                   3805:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   3806:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   3807:   for (i=1;i<=npar;i++){
1.203     brouard  3808:     printf("%d-",i);fflush(stdout);
                   3809:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  3810:    
                   3811:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   3812:     
                   3813:     /*  printf(" %f ",p[i]);
                   3814:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   3815:   }
                   3816:   
                   3817:   for (i=1;i<=npar;i++) {
                   3818:     for (j=1;j<=npar;j++)  {
                   3819:       if (j>i) { 
1.203     brouard  3820:        printf(".%d-%d",i,j);fflush(stdout);
                   3821:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   3822:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  3823:        
                   3824:        hess[j][i]=hess[i][j];    
                   3825:        /*printf(" %lf ",hess[i][j]);*/
                   3826:       }
                   3827:     }
                   3828:   }
                   3829:   printf("\n");
                   3830:   fprintf(ficlog,"\n");
                   3831: 
                   3832:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   3833:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   3834:   
                   3835:   a=matrix(1,npar,1,npar);
                   3836:   y=matrix(1,npar,1,npar);
                   3837:   x=vector(1,npar);
                   3838:   indx=ivector(1,npar);
                   3839:   for (i=1;i<=npar;i++)
                   3840:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   3841:   ludcmp(a,npar,indx,&pd);
                   3842: 
                   3843:   for (j=1;j<=npar;j++) {
                   3844:     for (i=1;i<=npar;i++) x[i]=0;
                   3845:     x[j]=1;
                   3846:     lubksb(a,npar,indx,x);
                   3847:     for (i=1;i<=npar;i++){ 
                   3848:       matcov[i][j]=x[i];
                   3849:     }
                   3850:   }
                   3851: 
                   3852:   printf("\n#Hessian matrix#\n");
                   3853:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   3854:   for (i=1;i<=npar;i++) { 
                   3855:     for (j=1;j<=npar;j++) { 
1.203     brouard  3856:       printf("%.6e ",hess[i][j]);
                   3857:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  3858:     }
                   3859:     printf("\n");
                   3860:     fprintf(ficlog,"\n");
                   3861:   }
                   3862: 
1.203     brouard  3863:   /* printf("\n#Covariance matrix#\n"); */
                   3864:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   3865:   /* for (i=1;i<=npar;i++) {  */
                   3866:   /*   for (j=1;j<=npar;j++) {  */
                   3867:   /*     printf("%.6e ",matcov[i][j]); */
                   3868:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   3869:   /*   } */
                   3870:   /*   printf("\n"); */
                   3871:   /*   fprintf(ficlog,"\n"); */
                   3872:   /* } */
                   3873: 
1.126     brouard  3874:   /* Recompute Inverse */
1.203     brouard  3875:   /* for (i=1;i<=npar;i++) */
                   3876:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   3877:   /* ludcmp(a,npar,indx,&pd); */
                   3878: 
                   3879:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   3880: 
                   3881:   /* for (j=1;j<=npar;j++) { */
                   3882:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   3883:   /*   x[j]=1; */
                   3884:   /*   lubksb(a,npar,indx,x); */
                   3885:   /*   for (i=1;i<=npar;i++){  */
                   3886:   /*     y[i][j]=x[i]; */
                   3887:   /*     printf("%.3e ",y[i][j]); */
                   3888:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   3889:   /*   } */
                   3890:   /*   printf("\n"); */
                   3891:   /*   fprintf(ficlog,"\n"); */
                   3892:   /* } */
                   3893: 
                   3894:   /* Verifying the inverse matrix */
                   3895: #ifdef DEBUGHESS
                   3896:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  3897: 
1.203     brouard  3898:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   3899:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  3900: 
                   3901:   for (j=1;j<=npar;j++) {
                   3902:     for (i=1;i<=npar;i++){ 
1.203     brouard  3903:       printf("%.2f ",y[i][j]);
                   3904:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  3905:     }
                   3906:     printf("\n");
                   3907:     fprintf(ficlog,"\n");
                   3908:   }
1.203     brouard  3909: #endif
1.126     brouard  3910: 
                   3911:   free_matrix(a,1,npar,1,npar);
                   3912:   free_matrix(y,1,npar,1,npar);
                   3913:   free_vector(x,1,npar);
                   3914:   free_ivector(indx,1,npar);
1.203     brouard  3915:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  3916: 
                   3917: 
                   3918: }
                   3919: 
                   3920: /*************** hessian matrix ****************/
                   3921: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  3922: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  3923:   int i;
                   3924:   int l=1, lmax=20;
1.203     brouard  3925:   double k1,k2, res, fx;
1.132     brouard  3926:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  3927:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   3928:   int k=0,kmax=10;
                   3929:   double l1;
                   3930: 
                   3931:   fx=func(x);
                   3932:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  3933:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  3934:     l1=pow(10,l);
                   3935:     delts=delt;
                   3936:     for(k=1 ; k <kmax; k=k+1){
                   3937:       delt = delta*(l1*k);
                   3938:       p2[theta]=x[theta] +delt;
1.145     brouard  3939:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  3940:       p2[theta]=x[theta]-delt;
                   3941:       k2=func(p2)-fx;
                   3942:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  3943:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  3944:       
1.203     brouard  3945: #ifdef DEBUGHESSII
1.126     brouard  3946:       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);
                   3947:       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);
                   3948: #endif
                   3949:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   3950:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   3951:        k=kmax;
                   3952:       }
                   3953:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  3954:        k=kmax; l=lmax*10;
1.126     brouard  3955:       }
                   3956:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   3957:        delts=delt;
                   3958:       }
1.203     brouard  3959:     } /* End loop k */
1.126     brouard  3960:   }
                   3961:   delti[theta]=delts;
                   3962:   return res; 
                   3963:   
                   3964: }
                   3965: 
1.203     brouard  3966: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  3967: {
                   3968:   int i;
1.164     brouard  3969:   int l=1, lmax=20;
1.126     brouard  3970:   double k1,k2,k3,k4,res,fx;
1.132     brouard  3971:   double p2[MAXPARM+1];
1.203     brouard  3972:   int k, kmax=1;
                   3973:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  3974: 
                   3975:   int firstime=0;
1.203     brouard  3976:   
1.126     brouard  3977:   fx=func(x);
1.203     brouard  3978:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  3979:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  3980:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   3981:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  3982:     k1=func(p2)-fx;
                   3983:   
1.203     brouard  3984:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   3985:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  3986:     k2=func(p2)-fx;
                   3987:   
1.203     brouard  3988:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   3989:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  3990:     k3=func(p2)-fx;
                   3991:   
1.203     brouard  3992:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   3993:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  3994:     k4=func(p2)-fx;
1.203     brouard  3995:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   3996:     if(k1*k2*k3*k4 <0.){
1.208     brouard  3997:       firstime=1;
1.203     brouard  3998:       kmax=kmax+10;
1.208     brouard  3999:     }
                   4000:     if(kmax >=10 || firstime ==1){
1.218     brouard  4001:       printf("Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; you may increase ftol=%.2e\n",thetai,thetaj, ftol);
                   4002:       fprintf(ficlog,"Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; you may increase ftol=%.2e\n",thetai,thetaj, ftol);
1.203     brouard  4003:       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);
                   4004:       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);
                   4005:     }
                   4006: #ifdef DEBUGHESSIJ
                   4007:     v1=hess[thetai][thetai];
                   4008:     v2=hess[thetaj][thetaj];
                   4009:     cv12=res;
                   4010:     /* Computing eigen value of Hessian matrix */
                   4011:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4012:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4013:     if ((lc2 <0) || (lc1 <0) ){
                   4014:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4015:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4016:       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);
                   4017:       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);
                   4018:     }
1.126     brouard  4019: #endif
                   4020:   }
                   4021:   return res;
                   4022: }
                   4023: 
1.203     brouard  4024:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   4025: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   4026: /* { */
                   4027: /*   int i; */
                   4028: /*   int l=1, lmax=20; */
                   4029: /*   double k1,k2,k3,k4,res,fx; */
                   4030: /*   double p2[MAXPARM+1]; */
                   4031: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   4032: /*   int k=0,kmax=10; */
                   4033: /*   double l1; */
                   4034:   
                   4035: /*   fx=func(x); */
                   4036: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   4037: /*     l1=pow(10,l); */
                   4038: /*     delts=delt; */
                   4039: /*     for(k=1 ; k <kmax; k=k+1){ */
                   4040: /*       delt = delti*(l1*k); */
                   4041: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   4042: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4043: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4044: /*       k1=func(p2)-fx; */
                   4045:       
                   4046: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4047: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4048: /*       k2=func(p2)-fx; */
                   4049:       
                   4050: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4051: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4052: /*       k3=func(p2)-fx; */
                   4053:       
                   4054: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4055: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4056: /*       k4=func(p2)-fx; */
                   4057: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   4058: /* #ifdef DEBUGHESSIJ */
                   4059: /*       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); */
                   4060: /*       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); */
                   4061: /* #endif */
                   4062: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   4063: /*     k=kmax; */
                   4064: /*       } */
                   4065: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   4066: /*     k=kmax; l=lmax*10; */
                   4067: /*       } */
                   4068: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   4069: /*     delts=delt; */
                   4070: /*       } */
                   4071: /*     } /\* End loop k *\/ */
                   4072: /*   } */
                   4073: /*   delti[theta]=delts; */
                   4074: /*   return res;  */
                   4075: /* } */
                   4076: 
                   4077: 
1.126     brouard  4078: /************** Inverse of matrix **************/
                   4079: void ludcmp(double **a, int n, int *indx, double *d) 
                   4080: { 
                   4081:   int i,imax,j,k; 
                   4082:   double big,dum,sum,temp; 
                   4083:   double *vv; 
                   4084:  
                   4085:   vv=vector(1,n); 
                   4086:   *d=1.0; 
                   4087:   for (i=1;i<=n;i++) { 
                   4088:     big=0.0; 
                   4089:     for (j=1;j<=n;j++) 
                   4090:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   4091:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   4092:     vv[i]=1.0/big; 
                   4093:   } 
                   4094:   for (j=1;j<=n;j++) { 
                   4095:     for (i=1;i<j;i++) { 
                   4096:       sum=a[i][j]; 
                   4097:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   4098:       a[i][j]=sum; 
                   4099:     } 
                   4100:     big=0.0; 
                   4101:     for (i=j;i<=n;i++) { 
                   4102:       sum=a[i][j]; 
                   4103:       for (k=1;k<j;k++) 
                   4104:        sum -= a[i][k]*a[k][j]; 
                   4105:       a[i][j]=sum; 
                   4106:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   4107:        big=dum; 
                   4108:        imax=i; 
                   4109:       } 
                   4110:     } 
                   4111:     if (j != imax) { 
                   4112:       for (k=1;k<=n;k++) { 
                   4113:        dum=a[imax][k]; 
                   4114:        a[imax][k]=a[j][k]; 
                   4115:        a[j][k]=dum; 
                   4116:       } 
                   4117:       *d = -(*d); 
                   4118:       vv[imax]=vv[j]; 
                   4119:     } 
                   4120:     indx[j]=imax; 
                   4121:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   4122:     if (j != n) { 
                   4123:       dum=1.0/(a[j][j]); 
                   4124:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   4125:     } 
                   4126:   } 
                   4127:   free_vector(vv,1,n);  /* Doesn't work */
                   4128: ;
                   4129: } 
                   4130: 
                   4131: void lubksb(double **a, int n, int *indx, double b[]) 
                   4132: { 
                   4133:   int i,ii=0,ip,j; 
                   4134:   double sum; 
                   4135:  
                   4136:   for (i=1;i<=n;i++) { 
                   4137:     ip=indx[i]; 
                   4138:     sum=b[ip]; 
                   4139:     b[ip]=b[i]; 
                   4140:     if (ii) 
                   4141:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   4142:     else if (sum) ii=i; 
                   4143:     b[i]=sum; 
                   4144:   } 
                   4145:   for (i=n;i>=1;i--) { 
                   4146:     sum=b[i]; 
                   4147:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   4148:     b[i]=sum/a[i][i]; 
                   4149:   } 
                   4150: } 
                   4151: 
                   4152: void pstamp(FILE *fichier)
                   4153: {
1.196     brouard  4154:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  4155: }
                   4156: 
                   4157: /************ Frequencies ********************/
1.226     brouard  4158: void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
                   4159:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   4160:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
                   4161: {  /* Some frequencies */
                   4162:   
1.227     brouard  4163:   int i, m, jk, j1, bool, z1,j, k, iv;
1.226     brouard  4164:   int iind=0, iage=0;
                   4165:   int mi; /* Effective wave */
                   4166:   int first;
                   4167:   double ***freq; /* Frequencies */
                   4168:   double *meanq;
                   4169:   double **meanqt;
                   4170:   double *pp, **prop, *posprop, *pospropt;
                   4171:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   4172:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   4173:   double agebegin, ageend;
                   4174:     
                   4175:   pp=vector(1,nlstate);
                   4176:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
                   4177:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   4178:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   4179:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   4180:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
                   4181:   meanqt=matrix(1,lastpass,1,nqtveff);
                   4182:   strcpy(fileresp,"P_");
                   4183:   strcat(fileresp,fileresu);
                   4184:   /*strcat(fileresphtm,fileresu);*/
                   4185:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   4186:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   4187:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   4188:     exit(0);
                   4189:   }
1.240     brouard  4190:   
1.226     brouard  4191:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   4192:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   4193:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4194:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4195:     fflush(ficlog);
                   4196:     exit(70); 
                   4197:   }
                   4198:   else{
                   4199:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  4200: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4201: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4202:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4203:   }
1.237     brouard  4204:   fprintf(ficresphtm,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Frequencies and prevalence by age at begin of transition and dummy covariate value at beginning of transition</h4>\n",fileresphtm, fileresphtm);
1.240     brouard  4205:   
1.226     brouard  4206:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   4207:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   4208:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4209:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4210:     fflush(ficlog);
                   4211:     exit(70); 
1.240     brouard  4212:   } else{
1.226     brouard  4213:     fprintf(ficresphtmfr,"<html><head>\n<title>IMaCh PHTM_Frequency table %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  4214: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4215: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4216:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4217:   }
1.240     brouard  4218:   fprintf(ficresphtmfr,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Frequencies of all effective transitions of the model, by age at begin of transition, and covariate value at the begin of transition (if the covariate is a varying covariate) </h4>Unknown status is -1<br/>\n",fileresphtmfr, fileresphtmfr);
                   4219:   
1.226     brouard  4220:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+3+AGEMARGE);
                   4221:   j1=0;
1.126     brouard  4222:   
1.227     brouard  4223:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
                   4224:   j=cptcoveff;  /* Only dummy covariates of the model */
1.226     brouard  4225:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  4226:   
1.226     brouard  4227:   first=1;
1.240     brouard  4228:   
1.226     brouard  4229:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   4230:      reference=low_education V1=0,V2=0
                   4231:      med_educ                V1=1 V2=0, 
                   4232:      high_educ               V1=0 V2=1
                   4233:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcoveff 
                   4234:   */
1.240     brouard  4235:   
1.227     brouard  4236:   for (j1 = 1; j1 <= (int) pow(2,j); j1++){ /* Loop on covariates combination in order of model, excluding quantitatives V4=0, V3=0 for example, fixed or varying covariates */
1.226     brouard  4237:     posproptt=0.;
                   4238:     /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   4239:       scanf("%d", i);*/
                   4240:     for (i=-5; i<=nlstate+ndeath; i++)  
                   4241:       for (jk=-5; jk<=nlstate+ndeath; jk++)  
1.240     brouard  4242:        for(m=iagemin; m <= iagemax+3; m++)
                   4243:          freq[i][jk][m]=0;
                   4244:     
1.226     brouard  4245:     for (i=1; i<=nlstate; i++)  {
                   4246:       for(m=iagemin; m <= iagemax+3; m++)
1.240     brouard  4247:        prop[i][m]=0;
1.226     brouard  4248:       posprop[i]=0;
                   4249:       pospropt[i]=0;
                   4250:     }
1.227     brouard  4251:     /* for (z1=1; z1<= nqfveff; z1++) {   */
                   4252:     /*   meanq[z1]+=0.; */
                   4253:     /*   for(m=1;m<=lastpass;m++){ */
                   4254:     /*         meanqt[m][z1]=0.; */
                   4255:     /*   } */
                   4256:     /* } */
1.240     brouard  4257:     
1.226     brouard  4258:     dateintsum=0;
                   4259:     k2cpt=0;
1.227     brouard  4260:     /* For that combination of covariate j1, we count and print the frequencies in one pass */
1.226     brouard  4261:     for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   4262:       bool=1;
1.227     brouard  4263:       if(anyvaryingduminmodel==0){ /* If All fixed covariates */
1.234     brouard  4264:        if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
1.227     brouard  4265:          /* for (z1=1; z1<= nqfveff; z1++) {   */
                   4266:          /*   meanq[z1]+=coqvar[Tvar[z1]][iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   4267:          /* } */
1.234     brouard  4268:          for (z1=1; z1<=cptcoveff; z1++) {  
                   4269:            /* if(Tvaraff[z1] ==-20){ */
                   4270:            /*   /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   4271:            /* }else  if(Tvaraff[z1] ==-10){ */
                   4272:            /*   /\* sumnew+=coqvar[z1][iind]; *\/ */
                   4273:            /* }else  */
                   4274:            if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
                   4275:              /* Tests if this individual iind responded to j1 (V4=1 V3=0) */
                   4276:              bool=0;
                   4277:              /* printf("bool=%d i=%d, z1=%d, Tvaraff[%d]=%d, covar[Tvarff][%d]=%2f, codtabm(%d,%d)=%d, nbcode[Tvaraff][codtabm(%d,%d)=%d, j1=%d\n", 
                   4278:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   4279:                 j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
                   4280:              /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   4281:            } /* Onlyf fixed */
                   4282:          } /* end z1 */
                   4283:        } /* cptcovn > 0 */
1.227     brouard  4284:       } /* end any */
                   4285:       if (bool==1){ /* We selected an individual iind satisfying combination j1 or all fixed */
1.234     brouard  4286:        /* for(m=firstpass; m<=lastpass; m++){ */
                   4287:        for(mi=1; mi<wav[iind];mi++){ /* For that wave */
                   4288:          m=mw[mi][iind];
                   4289:          if(anyvaryingduminmodel==1){ /* Some are varying covariates */
                   4290:            for (z1=1; z1<=cptcoveff; z1++) {
                   4291:              if( Fixed[Tmodelind[z1]]==1){
                   4292:                iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   4293:                if (cotvar[m][iv][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality */
                   4294:                  bool=0;
                   4295:              }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
                   4296:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   4297:                  bool=0;
                   4298:                }
                   4299:              }
                   4300:            }
                   4301:          }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   4302:          /* bool =0 we keep that guy which corresponds to the combination of dummy values */
                   4303:          if(bool==1){
                   4304:            /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   4305:               and mw[mi+1][iind]. dh depends on stepm. */
                   4306:            agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   4307:            ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   4308:            if(m >=firstpass && m <=lastpass){
                   4309:              k2=anint[m][iind]+(mint[m][iind]/12.);
                   4310:              /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   4311:              if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   4312:              if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   4313:              if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   4314:                prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   4315:              if (m<lastpass) {
                   4316:                /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   4317:                /*   printf(" num=%ld m=%d, iind=%d s1=%d s2=%d agev at m=%d\n", num[iind], m, iind,s[m][iind],s[m+1][iind], (int)agev[m][iind]); */
                   4318:                if(s[m][iind]==-1)
                   4319:                  printf(" num=%ld m=%d, iind=%d s1=%d s2=%d agev at m=%d agebegin=%.2f ageend=%.2f, agemed=%d\n", num[iind], m, iind,s[m][iind],s[m+1][iind], (int)agev[m][iind],agebegin, ageend, (int)((agebegin+ageend)/2.));
                   4320:                freq[s[m][iind]][s[m+1][iind]][(int)agev[m][iind]] += weight[iind]; /* At age of beginning of transition, where status is known */
                   4321:                /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   4322:                freq[s[m][iind]][s[m+1][iind]][iagemax+3] += weight[iind]; /* Total is in iagemax+3 *//* At age of beginning of transition, where status is known */
                   4323:              }
                   4324:            } /* end if between passes */  
                   4325:            if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99)) {
                   4326:              dateintsum=dateintsum+k2;
                   4327:              k2cpt++;
                   4328:              /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
                   4329:            }
                   4330:          } /* end bool 2 */
                   4331:        } /* end m */
1.226     brouard  4332:       } /* end bool */
                   4333:     } /* end iind = 1 to imx */
                   4334:     /* prop[s][age] is feeded for any initial and valid live state as well as
                   4335:        freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
1.240     brouard  4336:     
                   4337:     
1.226     brouard  4338:     /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   4339:     pstamp(ficresp);
1.240     brouard  4340:     if  (cptcoveff>0){
1.226     brouard  4341:       fprintf(ficresp, "\n#********** Variable "); 
                   4342:       fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   4343:       fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
1.240     brouard  4344:       fprintf(ficlog, "\n#********** Variable "); 
1.227     brouard  4345:       for (z1=1; z1<=cptcoveff; z1++){
1.240     brouard  4346:        if(DummyV[z1]){
                   4347:          fprintf(ficresp, "V%d (fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4348:          fprintf(ficresphtm, "V%d (fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4349:          fprintf(ficresphtmfr, "V%d (fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4350:          fprintf(ficlog, "V%d (fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4351:        }else{
                   4352:          fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4353:          fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4354:          fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4355:          fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4356:        }
1.226     brouard  4357:       }
                   4358:       fprintf(ficresp, "**********\n#");
                   4359:       fprintf(ficresphtm, "**********</h3>\n");
                   4360:       fprintf(ficresphtmfr, "**********</h3>\n");
                   4361:       fprintf(ficlog, "**********\n");
                   4362:     }
                   4363:     fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
                   4364:     for(i=1; i<=nlstate;i++) {
1.240     brouard  4365:       fprintf(ficresp, " Age Prev(%d)  N(%d)  N  ",i,i);
1.226     brouard  4366:       fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   4367:     }
                   4368:     fprintf(ficresp, "\n");
                   4369:     fprintf(ficresphtm, "\n");
1.240     brouard  4370:     
1.226     brouard  4371:     /* Header of frequency table by age */
                   4372:     fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   4373:     fprintf(ficresphtmfr,"<th>Age</th> ");
                   4374:     for(jk=-1; jk <=nlstate+ndeath; jk++){
                   4375:       for(m=-1; m <=nlstate+ndeath; m++){
1.234     brouard  4376:        if(jk!=0 && m!=0)
                   4377:          fprintf(ficresphtmfr,"<th>%d%d</th> ",jk,m);
1.226     brouard  4378:       }
                   4379:     }
                   4380:     fprintf(ficresphtmfr, "\n");
1.240     brouard  4381:     
1.226     brouard  4382:     /* For each age */
                   4383:     for(iage=iagemin; iage <= iagemax+3; iage++){
                   4384:       fprintf(ficresphtm,"<tr>");
                   4385:       if(iage==iagemax+1){
1.240     brouard  4386:        fprintf(ficlog,"1");
                   4387:        fprintf(ficresphtmfr,"<tr><th>0</th> ");
1.226     brouard  4388:       }else if(iage==iagemax+2){
1.240     brouard  4389:        fprintf(ficlog,"0");
                   4390:        fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
1.226     brouard  4391:       }else if(iage==iagemax+3){
1.240     brouard  4392:        fprintf(ficlog,"Total");
                   4393:        fprintf(ficresphtmfr,"<tr><th>Total</th> ");
1.226     brouard  4394:       }else{
1.240     brouard  4395:        if(first==1){
                   4396:          first=0;
                   4397:          printf("See log file for details...\n");
                   4398:        }
                   4399:        fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   4400:        fprintf(ficlog,"Age %d", iage);
1.226     brouard  4401:       }
                   4402:       for(jk=1; jk <=nlstate ; jk++){
1.240     brouard  4403:        for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   4404:          pp[jk] += freq[jk][m][iage]; 
1.226     brouard  4405:       }
                   4406:       for(jk=1; jk <=nlstate ; jk++){
1.240     brouard  4407:        for(m=-1, pos=0; m <=0 ; m++)
                   4408:          pos += freq[jk][m][iage];
                   4409:        if(pp[jk]>=1.e-10){
                   4410:          if(first==1){
                   4411:            printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   4412:          }
                   4413:          fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   4414:        }else{
                   4415:          if(first==1)
                   4416:            printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   4417:          fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   4418:        }
1.226     brouard  4419:       }
1.240     brouard  4420:       
1.226     brouard  4421:       for(jk=1; jk <=nlstate ; jk++){ 
1.240     brouard  4422:        /* posprop[jk]=0; */
                   4423:        for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   4424:          pp[jk] += freq[jk][m][iage];
1.226     brouard  4425:       }        /* pp[jk] is the total number of transitions starting from state jk and any ending status until this age */
1.240     brouard  4426:       
1.226     brouard  4427:       for(jk=1,pos=0, pospropta=0.; jk <=nlstate ; jk++){
1.240     brouard  4428:        pos += pp[jk]; /* pos is the total number of transitions until this age */
                   4429:        posprop[jk] += prop[jk][iage]; /* prop is the number of transitions from a live state
                   4430:                                          from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   4431:        pospropta += prop[jk][iage]; /* prop is the number of transitions from a live state
                   4432:                                        from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
1.226     brouard  4433:       }
                   4434:       for(jk=1; jk <=nlstate ; jk++){
1.240     brouard  4435:        if(pos>=1.e-5){
                   4436:          if(first==1)
                   4437:            printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   4438:          fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   4439:        }else{
                   4440:          if(first==1)
                   4441:            printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   4442:          fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   4443:        }
                   4444:        if( iage <= iagemax){
                   4445:          if(pos>=1.e-5){
                   4446:            fprintf(ficresp," %d %.5f %.0f %.0f",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
                   4447:            fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
                   4448:            /*probs[iage][jk][j1]= pp[jk]/pos;*/
                   4449:            /*printf("\niage=%d jk=%d j1=%d %.5f %.0f %.0f %f",iage,jk,j1,pp[jk]/pos, pp[jk],pos,probs[iage][jk][j1]);*/
                   4450:          }
                   4451:          else{
                   4452:            fprintf(ficresp," %d NaNq %.0f %.0f",iage,prop[jk][iage],pospropta);
                   4453:            fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[jk][iage],pospropta);
                   4454:          }
                   4455:        }
                   4456:        pospropt[jk] +=posprop[jk];
1.226     brouard  4457:       } /* end loop jk */
                   4458:       /* pospropt=0.; */
                   4459:       for(jk=-1; jk <=nlstate+ndeath; jk++){
1.240     brouard  4460:        for(m=-1; m <=nlstate+ndeath; m++){
                   4461:          if(freq[jk][m][iage] !=0 ) { /* minimizing output */
                   4462:            if(first==1){
                   4463:              printf(" %d%d=%.0f",jk,m,freq[jk][m][iage]);
                   4464:            }
                   4465:            fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][iage]);
                   4466:          }
                   4467:          if(jk!=0 && m!=0)
                   4468:            fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[jk][m][iage]);
                   4469:        }
1.226     brouard  4470:       } /* end loop jk */
                   4471:       posproptt=0.; 
                   4472:       for(jk=1; jk <=nlstate; jk++){
1.240     brouard  4473:        posproptt += pospropt[jk];
1.226     brouard  4474:       }
                   4475:       fprintf(ficresphtmfr,"</tr>\n ");
                   4476:       if(iage <= iagemax){
1.240     brouard  4477:        fprintf(ficresp,"\n");
                   4478:        fprintf(ficresphtm,"</tr>\n");
1.226     brouard  4479:       }
                   4480:       if(first==1)
1.240     brouard  4481:        printf("Others in log...\n");
1.226     brouard  4482:       fprintf(ficlog,"\n");
                   4483:     } /* end loop age iage */
                   4484:     fprintf(ficresphtm,"<tr><th>Tot</th>");
                   4485:     for(jk=1; jk <=nlstate ; jk++){
                   4486:       if(posproptt < 1.e-5){
1.240     brouard  4487:        fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[jk],posproptt);   
1.226     brouard  4488:       }else{
1.240     brouard  4489:        fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[jk]/posproptt,pospropt[jk],posproptt);    
1.226     brouard  4490:       }
                   4491:     }
                   4492:     fprintf(ficresphtm,"</tr>\n");
                   4493:     fprintf(ficresphtm,"</table>\n");
                   4494:     fprintf(ficresphtmfr,"</table>\n");
                   4495:     if(posproptt < 1.e-5){
                   4496:       fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   4497:       fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   4498:       fprintf(ficres,"\n  This combination (%d) is not valid and no result will be produced\n\n",j1);
                   4499:       invalidvarcomb[j1]=1;
                   4500:     }else{
                   4501:       fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
                   4502:       invalidvarcomb[j1]=0;
                   4503:     }
                   4504:     fprintf(ficresphtmfr,"</table>\n");
                   4505:   } /* end selected combination of covariate j1 */
                   4506:   dateintmean=dateintsum/k2cpt; 
1.240     brouard  4507:   
1.226     brouard  4508:   fclose(ficresp);
                   4509:   fclose(ficresphtm);
                   4510:   fclose(ficresphtmfr);
                   4511:   free_vector(meanq,1,nqfveff);
                   4512:   free_matrix(meanqt,1,lastpass,1,nqtveff);
                   4513:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+3+AGEMARGE);
                   4514:   free_vector(pospropt,1,nlstate);
                   4515:   free_vector(posprop,1,nlstate);
                   4516:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+3+AGEMARGE);
                   4517:   free_vector(pp,1,nlstate);
                   4518:   /* End of freqsummary */
                   4519: }
1.126     brouard  4520: 
                   4521: /************ Prevalence ********************/
1.227     brouard  4522: 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)
                   4523: {  
                   4524:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   4525:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   4526:      We still use firstpass and lastpass as another selection.
                   4527:   */
1.126     brouard  4528:  
1.227     brouard  4529:   int i, m, jk, j1, bool, z1,j, iv;
                   4530:   int mi; /* Effective wave */
                   4531:   int iage;
                   4532:   double agebegin, ageend;
                   4533: 
                   4534:   double **prop;
                   4535:   double posprop; 
                   4536:   double  y2; /* in fractional years */
                   4537:   int iagemin, iagemax;
                   4538:   int first; /** to stop verbosity which is redirected to log file */
                   4539: 
                   4540:   iagemin= (int) agemin;
                   4541:   iagemax= (int) agemax;
                   4542:   /*pp=vector(1,nlstate);*/
                   4543:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
                   4544:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   4545:   j1=0;
1.222     brouard  4546:   
1.227     brouard  4547:   /*j=cptcoveff;*/
                   4548:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  4549:   
1.227     brouard  4550:   first=1;
                   4551:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of covariate */
                   4552:     for (i=1; i<=nlstate; i++)  
                   4553:       for(iage=iagemin-AGEMARGE; iage <= iagemax+3+AGEMARGE; iage++)
                   4554:        prop[i][iage]=0.0;
                   4555:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   4556:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   4557:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   4558:     
                   4559:     for (i=1; i<=imx; i++) { /* Each individual */
                   4560:       bool=1;
                   4561:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   4562:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   4563:        m=mw[mi][i];
                   4564:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   4565:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   4566:        for (z1=1; z1<=cptcoveff; z1++){
                   4567:          if( Fixed[Tmodelind[z1]]==1){
                   4568:            iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   4569:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality */
                   4570:              bool=0;
                   4571:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
                   4572:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   4573:              bool=0;
                   4574:            }
                   4575:        }
                   4576:        if(bool==1){ /* Otherwise we skip that wave/person */
                   4577:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   4578:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   4579:          if(m >=firstpass && m <=lastpass){
                   4580:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   4581:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   4582:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   4583:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   4584:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+3+AGEMARGE){
                   4585:                printf("Error on individual # %d agev[m][i]=%f <%d-%d or > %d+3+%d  m=%d; either change agemin or agemax or fix data\n",i, agev[m][i],iagemin,AGEMARGE, iagemax,AGEMARGE,m); 
                   4586:                exit(1);
                   4587:              }
                   4588:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   4589:                /*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]]);*/
                   4590:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   4591:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   4592:              } /* end valid statuses */ 
                   4593:            } /* end selection of dates */
                   4594:          } /* end selection of waves */
                   4595:        } /* end bool */
                   4596:       } /* end wave */
                   4597:     } /* end individual */
                   4598:     for(i=iagemin; i <= iagemax+3; i++){  
                   4599:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   4600:        posprop += prop[jk][i]; 
                   4601:       } 
                   4602:       
                   4603:       for(jk=1; jk <=nlstate ; jk++){      
                   4604:        if( i <=  iagemax){ 
                   4605:          if(posprop>=1.e-5){ 
                   4606:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   4607:          } else{
                   4608:            if(first==1){
                   4609:              first=0;
                   4610:              printf("Warning Observed prevalence probs[%d][%d][%d]=%lf because of lack of cases\nSee others in log file...\n",jk,i,j1,probs[i][jk][j1]);
                   4611:            }
                   4612:          }
                   4613:        } 
                   4614:       }/* end jk */ 
                   4615:     }/* end i */ 
1.222     brouard  4616:      /*} *//* end i1 */
1.227     brouard  4617:   } /* end j1 */
1.222     brouard  4618:   
1.227     brouard  4619:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   4620:   /*free_vector(pp,1,nlstate);*/
                   4621:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+3+AGEMARGE);
                   4622: }  /* End of prevalence */
1.126     brouard  4623: 
                   4624: /************* Waves Concatenation ***************/
                   4625: 
                   4626: 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)
                   4627: {
                   4628:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   4629:      Death is a valid wave (if date is known).
                   4630:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   4631:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4632:      and mw[mi+1][i]. dh depends on stepm.
1.227     brouard  4633:   */
1.126     brouard  4634: 
1.224     brouard  4635:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  4636:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   4637:      double sum=0., jmean=0.;*/
1.224     brouard  4638:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  4639:   int j, k=0,jk, ju, jl;
                   4640:   double sum=0.;
                   4641:   first=0;
1.214     brouard  4642:   firstwo=0;
1.217     brouard  4643:   firsthree=0;
1.218     brouard  4644:   firstfour=0;
1.164     brouard  4645:   jmin=100000;
1.126     brouard  4646:   jmax=-1;
                   4647:   jmean=0.;
1.224     brouard  4648: 
                   4649: /* Treating live states */
1.214     brouard  4650:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  4651:     mi=0;  /* First valid wave */
1.227     brouard  4652:     mli=0; /* Last valid wave */
1.126     brouard  4653:     m=firstpass;
1.214     brouard  4654:     while(s[m][i] <= nlstate){  /* a live state */
1.227     brouard  4655:       if(m >firstpass && s[m][i]==s[m-1][i] && mint[m][i]==mint[m-1][i] && anint[m][i]==anint[m-1][i]){/* Two succesive identical information on wave m */
                   4656:        mli=m-1;/* mw[++mi][i]=m-1; */
                   4657:       }else if(s[m][i]>=1 || s[m][i]==-4 || s[m][i]==-5){ /* Since 0.98r4 if status=-2 vital status is really unknown, wave should be skipped */
                   4658:        mw[++mi][i]=m;
                   4659:        mli=m;
1.224     brouard  4660:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   4661:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  4662:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  4663:       }
1.227     brouard  4664:       else{ /* m >= lastpass, eventual special issue with warning */
1.224     brouard  4665: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  4666:        break;
1.224     brouard  4667: #else
1.227     brouard  4668:        if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){
                   4669:          if(firsthree == 0){
                   4670:            printf("Information! Unknown status for individual %ld line=%d occurred at last wave %d at known date %d/%d. Please, check if your unknown date of death %d/%d means a live state %d at wave %d. This case(%d)/wave(%d) contributes to the likelihood as pi. .\nOthers in log file only\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], (int) moisdc[i], (int) andc[i], s[m][i], m, i, m);
                   4671:            firsthree=1;
                   4672:          }
                   4673:          fprintf(ficlog,"Information! Unknown status for individual %ld line=%d occurred at last wave %d at known date %d/%d. Please, check if your unknown date of death %d/%d means a live state %d at wave %d. This case(%d)/wave(%d) contributes to the likelihood as pi. .\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], (int) moisdc[i], (int) andc[i], s[m][i], m, i, m);
                   4674:          mw[++mi][i]=m;
                   4675:          mli=m;
                   4676:        }
                   4677:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   4678:          nbwarn++;
                   4679:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified? */
                   4680:            printf("Warning! Vital status for individual %ld (line=%d) at last wave %d interviewed at date %d/%d is unknown %d. Please, check if the vital status and the date of death %d/%d are really unknown. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\nOthers in log file only\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], s[m][i], (int) moisdc[i], (int) andc[i], i, m);
                   4681:            fprintf(ficlog,"Warning! Vital status for individual %ld (line=%d) at last wave %d interviewed at date %d/%d is unknown %d. Please, check if the vital status and the date of death %d/%d are really unknown. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\n",num[i],i,lastpass,(int)mint[m][i],(int)anint[m][i], s[m][i], (int) moisdc[i], (int) andc[i], i, m);
                   4682:          }
                   4683:          break;
                   4684:        }
                   4685:        break;
1.224     brouard  4686: #endif
1.227     brouard  4687:       }/* End m >= lastpass */
1.126     brouard  4688:     }/* end while */
1.224     brouard  4689: 
1.227     brouard  4690:     /* mi is the last effective wave, m is lastpass, mw[j][i] gives the # of j-th effective wave for individual i */
1.216     brouard  4691:     /* After last pass */
1.224     brouard  4692: /* Treating death states */
1.214     brouard  4693:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  4694:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   4695:       /* } */
1.126     brouard  4696:       mi++;    /* Death is another wave */
                   4697:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  4698:       /* Only death is a correct wave */
1.126     brouard  4699:       mw[mi][i]=m;
1.224     brouard  4700:     }
                   4701: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.227     brouard  4702:     else if ((int) andc[i] != 9999) { /* Status is negative. A death occured after lastpass, we can't take it into account because of potential bias */
1.216     brouard  4703:       /* m++; */
                   4704:       /* mi++; */
                   4705:       /* s[m][i]=nlstate+1;  /\* We are setting the status to the last of non live state *\/ */
                   4706:       /* mw[mi][i]=m; */
1.218     brouard  4707:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.227     brouard  4708:        if((andc[i]+moisdc[i]/12.) <=(anint[m][i]+mint[m][i]/12.)){ /* death occured before last wave and status should have been death instead of -1 */
                   4709:          nbwarn++;
                   4710:          if(firstfiv==0){
                   4711:            printf("Warning! Death for individual %ld line=%d occurred at %d/%d before last wave %d interviewed at %d/%d and should have been coded as death instead of '%d'. This case (%d)/wave (%d) is contributing to likelihood.\nOthers in log file only\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], s[m][i], i,m );
                   4712:            firstfiv=1;
                   4713:          }else{
                   4714:            fprintf(ficlog,"Warning! Death for individual %ld line=%d occurred at %d/%d before last wave %d interviewed at %d/%d and should have been coded as death instead of '%d'. This case (%d)/wave (%d) is contributing to likelihood.\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], s[m][i], i,m );
                   4715:          }
                   4716:        }else{ /* Death occured afer last wave potential bias */
                   4717:          nberr++;
                   4718:          if(firstwo==0){
                   4719:            printf("Error! Death for individual %ld line=%d occurred at %d/%d after last wave %d interviewed at %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\nOthers in log file only\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
                   4720:            firstwo=1;
                   4721:          }
                   4722:          fprintf(ficlog,"Error! Death for individual %ld line=%d occurred at %d/%d after last wave %d interviewed at %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
                   4723:        }
1.218     brouard  4724:       }else{ /* end date of interview is known */
1.227     brouard  4725:        /* death is known but not confirmed by death status at any wave */
                   4726:        if(firstfour==0){
                   4727:          printf("Error! Death for individual %ld line=%d  occurred %d/%d but not confirmed by any death status for any wave, including last wave %d at unknown date %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\nOthers in log file only\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
                   4728:          firstfour=1;
                   4729:        }
                   4730:        fprintf(ficlog,"Error! Death for individual %ld line=%d  occurred %d/%d but not confirmed by any death status for any wave, including last wave %d at unknown date %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood.\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
1.214     brouard  4731:       }
1.224     brouard  4732:     } /* end if date of death is known */
                   4733: #endif
                   4734:     wav[i]=mi; /* mi should be the last effective wave (or mli) */
                   4735:     /* wav[i]=mw[mi][i]; */
1.126     brouard  4736:     if(mi==0){
                   4737:       nbwarn++;
                   4738:       if(first==0){
1.227     brouard  4739:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   4740:        first=1;
1.126     brouard  4741:       }
                   4742:       if(first==1){
1.227     brouard  4743:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  4744:       }
                   4745:     } /* end mi==0 */
                   4746:   } /* End individuals */
1.214     brouard  4747:   /* wav and mw are no more changed */
1.223     brouard  4748:        
1.214     brouard  4749:   
1.126     brouard  4750:   for(i=1; i<=imx; i++){
                   4751:     for(mi=1; mi<wav[i];mi++){
                   4752:       if (stepm <=0)
1.227     brouard  4753:        dh[mi][i]=1;
1.126     brouard  4754:       else{
1.227     brouard  4755:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                   4756:          if (agedc[i] < 2*AGESUP) {
                   4757:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   4758:            if(j==0) j=1;  /* Survives at least one month after exam */
                   4759:            else if(j<0){
                   4760:              nberr++;
                   4761:              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]);
                   4762:              j=1; /* Temporary Dangerous patch */
                   4763:              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);
                   4764:              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]);
                   4765:              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);
                   4766:            }
                   4767:            k=k+1;
                   4768:            if (j >= jmax){
                   4769:              jmax=j;
                   4770:              ijmax=i;
                   4771:            }
                   4772:            if (j <= jmin){
                   4773:              jmin=j;
                   4774:              ijmin=i;
                   4775:            }
                   4776:            sum=sum+j;
                   4777:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   4778:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   4779:          }
                   4780:        }
                   4781:        else{
                   4782:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  4783: /*       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]); */
1.223     brouard  4784:                                        
1.227     brouard  4785:          k=k+1;
                   4786:          if (j >= jmax) {
                   4787:            jmax=j;
                   4788:            ijmax=i;
                   4789:          }
                   4790:          else if (j <= jmin){
                   4791:            jmin=j;
                   4792:            ijmin=i;
                   4793:          }
                   4794:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   4795:          /*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]);*/
                   4796:          if(j<0){
                   4797:            nberr++;
                   4798:            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]);
                   4799:            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]);
                   4800:          }
                   4801:          sum=sum+j;
                   4802:        }
                   4803:        jk= j/stepm;
                   4804:        jl= j -jk*stepm;
                   4805:        ju= j -(jk+1)*stepm;
                   4806:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   4807:          if(jl==0){
                   4808:            dh[mi][i]=jk;
                   4809:            bh[mi][i]=0;
                   4810:          }else{ /* We want a negative bias in order to only have interpolation ie
                   4811:                  * to avoid the price of an extra matrix product in likelihood */
                   4812:            dh[mi][i]=jk+1;
                   4813:            bh[mi][i]=ju;
                   4814:          }
                   4815:        }else{
                   4816:          if(jl <= -ju){
                   4817:            dh[mi][i]=jk;
                   4818:            bh[mi][i]=jl;       /* bias is positive if real duration
                   4819:                                 * is higher than the multiple of stepm and negative otherwise.
                   4820:                                 */
                   4821:          }
                   4822:          else{
                   4823:            dh[mi][i]=jk+1;
                   4824:            bh[mi][i]=ju;
                   4825:          }
                   4826:          if(dh[mi][i]==0){
                   4827:            dh[mi][i]=1; /* At least one step */
                   4828:            bh[mi][i]=ju; /* At least one step */
                   4829:            /*  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);*/
                   4830:          }
                   4831:        } /* end if mle */
1.126     brouard  4832:       }
                   4833:     } /* end wave */
                   4834:   }
                   4835:   jmean=sum/k;
                   4836:   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);
1.141     brouard  4837:   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);
1.227     brouard  4838: }
1.126     brouard  4839: 
                   4840: /*********** Tricode ****************************/
1.220     brouard  4841:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  4842:  {
                   4843:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   4844:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   4845:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   4846:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   4847:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   4848:     */
1.130     brouard  4849: 
1.242     brouard  4850:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   4851:    int modmaxcovj=0; /* Modality max of covariates j */
                   4852:    int cptcode=0; /* Modality max of covariates j */
                   4853:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  4854: 
                   4855: 
1.242     brouard  4856:    /* cptcoveff=0;  */
                   4857:    /* *cptcov=0; */
1.126     brouard  4858:  
1.242     brouard  4859:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  4860: 
1.242     brouard  4861:    /* Loop on covariates without age and products and no quantitative variable */
                   4862:    /* for (j=1; j<=(cptcovs); j++) { /\* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only *\/ */
                   4863:    for (k=1; k<=cptcovt; k++) { /* From model V1 + V2*age + V3 + V3*V4 keeps V1 + V3 = 2 only */
                   4864:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
                   4865:      if(Dummy[k]==0 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
                   4866:        switch(Fixed[k]) {
                   4867:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
                   4868:         for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the  modality of this covariate Vj*/
                   4869:           ij=(int)(covar[Tvar[k]][i]);
                   4870:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   4871:            * If product of Vn*Vm, still boolean *:
                   4872:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   4873:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   4874:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   4875:              modality of the nth covariate of individual i. */
                   4876:           if (ij > modmaxcovj)
                   4877:             modmaxcovj=ij; 
                   4878:           else if (ij < modmincovj) 
                   4879:             modmincovj=ij; 
                   4880:           if ((ij < -1) && (ij > NCOVMAX)){
                   4881:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   4882:             exit(1);
                   4883:           }else
                   4884:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   4885:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   4886:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   4887:           /* getting the maximum value of the modality of the covariate
                   4888:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   4889:              female ies 1, then modmaxcovj=1.
                   4890:           */
                   4891:         } /* end for loop on individuals i */
                   4892:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   4893:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   4894:         cptcode=modmaxcovj;
                   4895:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   4896:         /*for (i=0; i<=cptcode; i++) {*/
                   4897:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   4898:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   4899:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   4900:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   4901:             if( j != -1){
                   4902:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   4903:                                  covariate for which somebody answered excluding 
                   4904:                                  undefined. Usually 2: 0 and 1. */
                   4905:             }
                   4906:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   4907:                                     covariate for which somebody answered including 
                   4908:                                     undefined. Usually 3: -1, 0 and 1. */
                   4909:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   4910:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   4911:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  4912:                        
1.242     brouard  4913:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   4914:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   4915:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   4916:         /* modmincovj=3; modmaxcovj = 7; */
                   4917:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   4918:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   4919:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   4920:         /* nbcode[Tvar[j]][ij]=k; */
                   4921:         /* nbcode[Tvar[j]][1]=0; */
                   4922:         /* nbcode[Tvar[j]][2]=1; */
                   4923:         /* nbcode[Tvar[j]][3]=2; */
                   4924:         /* To be continued (not working yet). */
                   4925:         ij=0; /* ij is similar to i but can jump over null modalities */
                   4926:         for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 or from -1 or 0 to 1 currently*/
                   4927:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   4928:             break;
                   4929:           }
                   4930:           ij++;
                   4931:           nbcode[Tvar[k]][ij]=i;  /* stores the original value of modality i in an array nbcode, ij modality from 1 to last non-nul modality. nbcode[1][1]=0 nbcode[1][2]=1*/
                   4932:           cptcode = ij; /* New max modality for covar j */
                   4933:         } /* end of loop on modality i=-1 to 1 or more */
                   4934:         break;
                   4935:        case 1: /* Testing on varying covariate, could be simple and
                   4936:                * should look at waves or product of fixed *
                   4937:                * varying. No time to test -1, assuming 0 and 1 only */
                   4938:         ij=0;
                   4939:         for(i=0; i<=1;i++){
                   4940:           nbcode[Tvar[k]][++ij]=i;
                   4941:         }
                   4942:         break;
                   4943:        default:
                   4944:         break;
                   4945:        } /* end switch */
                   4946:      } /* end dummy test */
                   4947:     
                   4948:      /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
                   4949:      /*        /\*recode from 0 *\/ */
                   4950:      /*                                     k is a modality. If we have model=V1+V1*sex  */
                   4951:      /*                                     then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
                   4952:      /*                                  But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
                   4953:      /*        } */
                   4954:      /*        /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
                   4955:      /*        if (ij > ncodemax[j]) { */
                   4956:      /*          printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
                   4957:      /*          fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
                   4958:      /*          break; */
                   4959:      /*        } */
                   4960:      /*   }  /\* end of loop on modality k *\/ */
                   4961:    } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   4962:   
                   4963:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   4964:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   4965:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   4966:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   4967:      ij=Tvar[i]; /* Tvar 5,4,3,6,5,7,1,4 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V4*age */ 
                   4968:      Ndum[ij]++; /* Count the # of 1, 2 etc: {1,1,1,2,2,1,1} because V1 once, V2 once, two V4 and V5 in above */
                   4969:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   4970:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   4971:   
                   4972:    ij=0;
                   4973:    /* for (i=0; i<=  maxncov-1; i++) { /\* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) *\/ */
                   4974:    for (k=1; k<=  cptcovt; k++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   4975:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   4976:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
                   4977:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy and non empty in the model */
                   4978:        /* If product not in single variable we don't print results */
                   4979:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   4980:        ++ij;/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, */
                   4981:        Tvaraff[ij]=Tvar[k]; /* For printing combination *//* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, Tvar {5, 4, 3, 6, 5, 2, 7, 1, 1} Tvaraff={4, 3, 1} V4, V3, V1*/
                   4982:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   4983:        TmodelInvind[ij]=Tvar[k]- ncovcol-nqv; /* Inverse TmodelInvind[2=V4]=2 second dummy varying cov (V4)4-1-1 {0, 2, 1, } TmodelInvind[3]=1 */
                   4984:        if(Fixed[k]!=0)
                   4985:         anyvaryingduminmodel=1;
                   4986:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   4987:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   4988:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   4989:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   4990:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   4991:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   4992:      } 
                   4993:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   4994:    /* ij--; */
                   4995:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
                   4996:    *cptcov=ij; /*Number of total real effective covariates: effective
                   4997:                * because they can be excluded from the model and real
                   4998:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   4999:    for(j=ij+1; j<= cptcovt; j++){
                   5000:      Tvaraff[j]=0;
                   5001:      Tmodelind[j]=0;
                   5002:    }
                   5003:    for(j=ntveff+1; j<= cptcovt; j++){
                   5004:      TmodelInvind[j]=0;
                   5005:    }
                   5006:    /* To be sorted */
                   5007:    ;
                   5008:  }
1.126     brouard  5009: 
1.145     brouard  5010: 
1.126     brouard  5011: /*********** Health Expectancies ****************/
                   5012: 
1.235     brouard  5013:  void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[], int nres )
1.126     brouard  5014: 
                   5015: {
                   5016:   /* Health expectancies, no variances */
1.164     brouard  5017:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  5018:   int nhstepma, nstepma; /* Decreasing with age */
                   5019:   double age, agelim, hf;
                   5020:   double ***p3mat;
                   5021:   double eip;
                   5022: 
1.238     brouard  5023:   /* pstamp(ficreseij); */
1.126     brouard  5024:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   5025:   fprintf(ficreseij,"# Age");
                   5026:   for(i=1; i<=nlstate;i++){
                   5027:     for(j=1; j<=nlstate;j++){
                   5028:       fprintf(ficreseij," e%1d%1d ",i,j);
                   5029:     }
                   5030:     fprintf(ficreseij," e%1d. ",i);
                   5031:   }
                   5032:   fprintf(ficreseij,"\n");
                   5033: 
                   5034:   
                   5035:   if(estepm < stepm){
                   5036:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5037:   }
                   5038:   else  hstepm=estepm;   
                   5039:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   5040:    * This is mainly to measure the difference between two models: for example
                   5041:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   5042:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   5043:    * progression in between and thus overestimating or underestimating according
                   5044:    * to the curvature of the survival function. If, for the same date, we 
                   5045:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   5046:    * to compare the new estimate of Life expectancy with the same linear 
                   5047:    * hypothesis. A more precise result, taking into account a more precise
                   5048:    * curvature will be obtained if estepm is as small as stepm. */
                   5049: 
                   5050:   /* For example we decided to compute the life expectancy with the smallest unit */
                   5051:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5052:      nhstepm is the number of hstepm from age to agelim 
                   5053:      nstepm is the number of stepm from age to agelin. 
                   5054:      Look at hpijx to understand the reason of that which relies in memory size
                   5055:      and note for a fixed period like estepm months */
                   5056:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   5057:      survival function given by stepm (the optimization length). Unfortunately it
                   5058:      means that if the survival funtion is printed only each two years of age and if
                   5059:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5060:      results. So we changed our mind and took the option of the best precision.
                   5061:   */
                   5062:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5063: 
                   5064:   agelim=AGESUP;
                   5065:   /* If stepm=6 months */
                   5066:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   5067:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   5068:     
                   5069: /* nhstepm age range expressed in number of stepm */
                   5070:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5071:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5072:   /* if (stepm >= YEARM) hstepm=1;*/
                   5073:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5074:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5075: 
                   5076:   for (age=bage; age<=fage; age ++){ 
                   5077:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5078:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5079:     /* if (stepm >= YEARM) hstepm=1;*/
                   5080:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   5081: 
                   5082:     /* If stepm=6 months */
                   5083:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   5084:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   5085:     
1.235     brouard  5086:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  5087:     
                   5088:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   5089:     
                   5090:     printf("%d|",(int)age);fflush(stdout);
                   5091:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   5092:     
                   5093:     /* Computing expectancies */
                   5094:     for(i=1; i<=nlstate;i++)
                   5095:       for(j=1; j<=nlstate;j++)
                   5096:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   5097:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   5098:          
                   5099:          /* 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]);*/
                   5100: 
                   5101:        }
                   5102: 
                   5103:     fprintf(ficreseij,"%3.0f",age );
                   5104:     for(i=1; i<=nlstate;i++){
                   5105:       eip=0;
                   5106:       for(j=1; j<=nlstate;j++){
                   5107:        eip +=eij[i][j][(int)age];
                   5108:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   5109:       }
                   5110:       fprintf(ficreseij,"%9.4f", eip );
                   5111:     }
                   5112:     fprintf(ficreseij,"\n");
                   5113:     
                   5114:   }
                   5115:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5116:   printf("\n");
                   5117:   fprintf(ficlog,"\n");
                   5118:   
                   5119: }
                   5120: 
1.235     brouard  5121:  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[], int nres )
1.126     brouard  5122: 
                   5123: {
                   5124:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  5125:      to initial status i, ei. .
1.126     brouard  5126:   */
                   5127:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   5128:   int nhstepma, nstepma; /* Decreasing with age */
                   5129:   double age, agelim, hf;
                   5130:   double ***p3matp, ***p3matm, ***varhe;
                   5131:   double **dnewm,**doldm;
                   5132:   double *xp, *xm;
                   5133:   double **gp, **gm;
                   5134:   double ***gradg, ***trgradg;
                   5135:   int theta;
                   5136: 
                   5137:   double eip, vip;
                   5138: 
                   5139:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   5140:   xp=vector(1,npar);
                   5141:   xm=vector(1,npar);
                   5142:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   5143:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   5144:   
                   5145:   pstamp(ficresstdeij);
                   5146:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   5147:   fprintf(ficresstdeij,"# Age");
                   5148:   for(i=1; i<=nlstate;i++){
                   5149:     for(j=1; j<=nlstate;j++)
                   5150:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   5151:     fprintf(ficresstdeij," e%1d. ",i);
                   5152:   }
                   5153:   fprintf(ficresstdeij,"\n");
                   5154: 
                   5155:   pstamp(ficrescveij);
                   5156:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   5157:   fprintf(ficrescveij,"# Age");
                   5158:   for(i=1; i<=nlstate;i++)
                   5159:     for(j=1; j<=nlstate;j++){
                   5160:       cptj= (j-1)*nlstate+i;
                   5161:       for(i2=1; i2<=nlstate;i2++)
                   5162:        for(j2=1; j2<=nlstate;j2++){
                   5163:          cptj2= (j2-1)*nlstate+i2;
                   5164:          if(cptj2 <= cptj)
                   5165:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   5166:        }
                   5167:     }
                   5168:   fprintf(ficrescveij,"\n");
                   5169:   
                   5170:   if(estepm < stepm){
                   5171:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5172:   }
                   5173:   else  hstepm=estepm;   
                   5174:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   5175:    * This is mainly to measure the difference between two models: for example
                   5176:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   5177:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   5178:    * progression in between and thus overestimating or underestimating according
                   5179:    * to the curvature of the survival function. If, for the same date, we 
                   5180:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   5181:    * to compare the new estimate of Life expectancy with the same linear 
                   5182:    * hypothesis. A more precise result, taking into account a more precise
                   5183:    * curvature will be obtained if estepm is as small as stepm. */
                   5184: 
                   5185:   /* For example we decided to compute the life expectancy with the smallest unit */
                   5186:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5187:      nhstepm is the number of hstepm from age to agelim 
                   5188:      nstepm is the number of stepm from age to agelin. 
                   5189:      Look at hpijx to understand the reason of that which relies in memory size
                   5190:      and note for a fixed period like estepm months */
                   5191:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   5192:      survival function given by stepm (the optimization length). Unfortunately it
                   5193:      means that if the survival funtion is printed only each two years of age and if
                   5194:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5195:      results. So we changed our mind and took the option of the best precision.
                   5196:   */
                   5197:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5198: 
                   5199:   /* If stepm=6 months */
                   5200:   /* nhstepm age range expressed in number of stepm */
                   5201:   agelim=AGESUP;
                   5202:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   5203:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5204:   /* if (stepm >= YEARM) hstepm=1;*/
                   5205:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5206:   
                   5207:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5208:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5209:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   5210:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   5211:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   5212:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   5213: 
                   5214:   for (age=bage; age<=fage; age ++){ 
                   5215:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5216:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5217:     /* if (stepm >= YEARM) hstepm=1;*/
                   5218:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  5219:                
1.126     brouard  5220:     /* If stepm=6 months */
                   5221:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   5222:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   5223:     
                   5224:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  5225:                
1.126     brouard  5226:     /* Computing  Variances of health expectancies */
                   5227:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   5228:        decrease memory allocation */
                   5229:     for(theta=1; theta <=npar; theta++){
                   5230:       for(i=1; i<=npar; i++){ 
1.222     brouard  5231:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5232:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  5233:       }
1.235     brouard  5234:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   5235:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  5236:                        
1.126     brouard  5237:       for(j=1; j<= nlstate; j++){
1.222     brouard  5238:        for(i=1; i<=nlstate; i++){
                   5239:          for(h=0; h<=nhstepm-1; h++){
                   5240:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   5241:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   5242:          }
                   5243:        }
1.126     brouard  5244:       }
1.218     brouard  5245:                        
1.126     brouard  5246:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  5247:        for(h=0; h<=nhstepm-1; h++){
                   5248:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   5249:        }
1.126     brouard  5250:     }/* End theta */
                   5251:     
                   5252:     
                   5253:     for(h=0; h<=nhstepm-1; h++)
                   5254:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  5255:        for(theta=1; theta <=npar; theta++)
                   5256:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  5257:     
1.218     brouard  5258:                
1.222     brouard  5259:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  5260:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  5261:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  5262:                
1.222     brouard  5263:     printf("%d|",(int)age);fflush(stdout);
                   5264:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   5265:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  5266:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  5267:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   5268:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   5269:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   5270:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   5271:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  5272:       }
                   5273:     }
1.218     brouard  5274:                
1.126     brouard  5275:     /* Computing expectancies */
1.235     brouard  5276:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  5277:     for(i=1; i<=nlstate;i++)
                   5278:       for(j=1; j<=nlstate;j++)
1.222     brouard  5279:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   5280:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  5281:                                        
1.222     brouard  5282:          /* 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]);*/
1.218     brouard  5283:                                        
1.222     brouard  5284:        }
1.218     brouard  5285:                
1.126     brouard  5286:     fprintf(ficresstdeij,"%3.0f",age );
                   5287:     for(i=1; i<=nlstate;i++){
                   5288:       eip=0.;
                   5289:       vip=0.;
                   5290:       for(j=1; j<=nlstate;j++){
1.222     brouard  5291:        eip += eij[i][j][(int)age];
                   5292:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   5293:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   5294:        fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
1.126     brouard  5295:       }
                   5296:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   5297:     }
                   5298:     fprintf(ficresstdeij,"\n");
1.218     brouard  5299:                
1.126     brouard  5300:     fprintf(ficrescveij,"%3.0f",age );
                   5301:     for(i=1; i<=nlstate;i++)
                   5302:       for(j=1; j<=nlstate;j++){
1.222     brouard  5303:        cptj= (j-1)*nlstate+i;
                   5304:        for(i2=1; i2<=nlstate;i2++)
                   5305:          for(j2=1; j2<=nlstate;j2++){
                   5306:            cptj2= (j2-1)*nlstate+i2;
                   5307:            if(cptj2 <= cptj)
                   5308:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   5309:          }
1.126     brouard  5310:       }
                   5311:     fprintf(ficrescveij,"\n");
1.218     brouard  5312:                
1.126     brouard  5313:   }
                   5314:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   5315:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   5316:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   5317:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   5318:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5319:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5320:   printf("\n");
                   5321:   fprintf(ficlog,"\n");
1.218     brouard  5322:        
1.126     brouard  5323:   free_vector(xm,1,npar);
                   5324:   free_vector(xp,1,npar);
                   5325:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   5326:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   5327:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   5328: }
1.218     brouard  5329:  
1.126     brouard  5330: /************ Variance ******************/
1.235     brouard  5331:  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 *ncvyearp, int ij, int estepm, int cptcov, int cptcod, int popbased, int mobilav, char strstart[], int nres)
1.218     brouard  5332:  {
                   5333:    /* Variance of health expectancies */
                   5334:    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   5335:    /* double **newm;*/
                   5336:    /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
                   5337:   
                   5338:    /* int movingaverage(); */
                   5339:    double **dnewm,**doldm;
                   5340:    double **dnewmp,**doldmp;
                   5341:    int i, j, nhstepm, hstepm, h, nstepm ;
                   5342:    int k;
                   5343:    double *xp;
                   5344:    double **gp, **gm;  /* for var eij */
                   5345:    double ***gradg, ***trgradg; /*for var eij */
                   5346:    double **gradgp, **trgradgp; /* for var p point j */
                   5347:    double *gpp, *gmp; /* for var p point j */
                   5348:    double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   5349:    double ***p3mat;
                   5350:    double age,agelim, hf;
                   5351:    /* double ***mobaverage; */
                   5352:    int theta;
                   5353:    char digit[4];
                   5354:    char digitp[25];
                   5355: 
                   5356:    char fileresprobmorprev[FILENAMELENGTH];
                   5357: 
                   5358:    if(popbased==1){
                   5359:      if(mobilav!=0)
                   5360:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   5361:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   5362:    }
                   5363:    else 
                   5364:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  5365: 
1.218     brouard  5366:    /* if (mobilav!=0) { */
                   5367:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   5368:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   5369:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   5370:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   5371:    /*   } */
                   5372:    /* } */
                   5373: 
                   5374:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   5375:    sprintf(digit,"%-d",ij);
                   5376:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   5377:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   5378:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   5379:    strcat(fileresprobmorprev,fileresu);
                   5380:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   5381:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   5382:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   5383:    }
                   5384:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   5385:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   5386:    pstamp(ficresprobmorprev);
                   5387:    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);
1.238     brouard  5388:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
                   5389:    for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   5390:      fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   5391:    }
                   5392:    for(j=1;j<=cptcoveff;j++) 
                   5393:      fprintf(ficresprobmorprev,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,j)]);
                   5394:    fprintf(ficresprobmorprev,"\n");
                   5395: 
1.218     brouard  5396:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   5397:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   5398:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   5399:      for(i=1; i<=nlstate;i++)
                   5400:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   5401:    }  
                   5402:    fprintf(ficresprobmorprev,"\n");
                   5403:   
                   5404:    fprintf(ficgp,"\n# Routine varevsij");
                   5405:    fprintf(ficgp,"\nunset title \n");
                   5406:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   5407:    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");
                   5408:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   5409:    /*   } */
                   5410:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5411:    pstamp(ficresvij);
                   5412:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   5413:    if(popbased==1)
                   5414:      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);
                   5415:    else
                   5416:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   5417:    fprintf(ficresvij,"# Age");
                   5418:    for(i=1; i<=nlstate;i++)
                   5419:      for(j=1; j<=nlstate;j++)
                   5420:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   5421:    fprintf(ficresvij,"\n");
                   5422: 
                   5423:    xp=vector(1,npar);
                   5424:    dnewm=matrix(1,nlstate,1,npar);
                   5425:    doldm=matrix(1,nlstate,1,nlstate);
                   5426:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   5427:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5428: 
                   5429:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   5430:    gpp=vector(nlstate+1,nlstate+ndeath);
                   5431:    gmp=vector(nlstate+1,nlstate+ndeath);
                   5432:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  5433:   
1.218     brouard  5434:    if(estepm < stepm){
                   5435:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   5436:    }
                   5437:    else  hstepm=estepm;   
                   5438:    /* For example we decided to compute the life expectancy with the smallest unit */
                   5439:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5440:       nhstepm is the number of hstepm from age to agelim 
                   5441:       nstepm is the number of stepm from age to agelim. 
                   5442:       Look at function hpijx to understand why because of memory size limitations, 
                   5443:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   5444:       survival function given by stepm (the optimization length). Unfortunately it
                   5445:       means that if the survival funtion is printed every two years of age and if
                   5446:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5447:       results. So we changed our mind and took the option of the best precision.
                   5448:    */
                   5449:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5450:    agelim = AGESUP;
                   5451:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   5452:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   5453:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5454:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5455:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   5456:      gp=matrix(0,nhstepm,1,nlstate);
                   5457:      gm=matrix(0,nhstepm,1,nlstate);
                   5458:                
                   5459:                
                   5460:      for(theta=1; theta <=npar; theta++){
                   5461:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   5462:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5463:        }
                   5464:                        
1.242     brouard  5465:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  5466:                        
                   5467:        if (popbased==1) {
                   5468:         if(mobilav ==0){
                   5469:           for(i=1; i<=nlstate;i++)
                   5470:             prlim[i][i]=probs[(int)age][i][ij];
                   5471:         }else{ /* mobilav */ 
                   5472:           for(i=1; i<=nlstate;i++)
                   5473:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   5474:         }
                   5475:        }
                   5476:                        
1.235     brouard  5477:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  /* Returns p3mat[i][j][h] for h=1 to nhstepm */
1.218     brouard  5478:        for(j=1; j<= nlstate; j++){
                   5479:         for(h=0; h<=nhstepm; h++){
                   5480:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   5481:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   5482:         }
                   5483:        }
                   5484:        /* Next for computing probability of death (h=1 means
                   5485:          computed over hstepm matrices product = hstepm*stepm months) 
                   5486:          as a weighted average of prlim.
                   5487:        */
                   5488:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   5489:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   5490:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   5491:        }    
                   5492:        /* end probability of death */
                   5493:                        
                   5494:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   5495:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   5496:                        
1.242     brouard  5497:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  5498:                        
                   5499:        if (popbased==1) {
                   5500:         if(mobilav ==0){
                   5501:           for(i=1; i<=nlstate;i++)
                   5502:             prlim[i][i]=probs[(int)age][i][ij];
                   5503:         }else{ /* mobilav */ 
                   5504:           for(i=1; i<=nlstate;i++)
                   5505:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   5506:         }
                   5507:        }
                   5508:                        
1.235     brouard  5509:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  5510:                        
                   5511:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   5512:         for(h=0; h<=nhstepm; h++){
                   5513:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   5514:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   5515:         }
                   5516:        }
                   5517:        /* This for computing probability of death (h=1 means
                   5518:          computed over hstepm matrices product = hstepm*stepm months) 
                   5519:          as a weighted average of prlim.
                   5520:        */
                   5521:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   5522:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   5523:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   5524:        }    
                   5525:        /* end probability of death */
                   5526:                        
                   5527:        for(j=1; j<= nlstate; j++) /* vareij */
                   5528:         for(h=0; h<=nhstepm; h++){
                   5529:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   5530:         }
                   5531:                        
                   5532:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   5533:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   5534:        }
                   5535:                        
                   5536:      } /* End theta */
                   5537:                
                   5538:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   5539:                
                   5540:      for(h=0; h<=nhstepm; h++) /* veij */
                   5541:        for(j=1; j<=nlstate;j++)
                   5542:         for(theta=1; theta <=npar; theta++)
                   5543:           trgradg[h][j][theta]=gradg[h][theta][j];
                   5544:                
                   5545:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   5546:        for(theta=1; theta <=npar; theta++)
                   5547:         trgradgp[j][theta]=gradgp[theta][j];
                   5548:                
                   5549:                
                   5550:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   5551:      for(i=1;i<=nlstate;i++)
                   5552:        for(j=1;j<=nlstate;j++)
                   5553:         vareij[i][j][(int)age] =0.;
                   5554:                
                   5555:      for(h=0;h<=nhstepm;h++){
                   5556:        for(k=0;k<=nhstepm;k++){
                   5557:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   5558:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   5559:         for(i=1;i<=nlstate;i++)
                   5560:           for(j=1;j<=nlstate;j++)
                   5561:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   5562:        }
                   5563:      }
                   5564:                
                   5565:      /* pptj */
                   5566:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   5567:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   5568:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   5569:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   5570:         varppt[j][i]=doldmp[j][i];
                   5571:      /* end ppptj */
                   5572:      /*  x centered again */
                   5573:                
1.242     brouard  5574:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  5575:                
                   5576:      if (popbased==1) {
                   5577:        if(mobilav ==0){
                   5578:         for(i=1; i<=nlstate;i++)
                   5579:           prlim[i][i]=probs[(int)age][i][ij];
                   5580:        }else{ /* mobilav */ 
                   5581:         for(i=1; i<=nlstate;i++)
                   5582:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   5583:        }
                   5584:      }
                   5585:                
                   5586:      /* This for computing probability of death (h=1 means
                   5587:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   5588:        as a weighted average of prlim.
                   5589:      */
1.235     brouard  5590:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  5591:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   5592:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   5593:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   5594:      }    
                   5595:      /* end probability of death */
                   5596:                
                   5597:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   5598:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   5599:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   5600:        for(i=1; i<=nlstate;i++){
                   5601:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   5602:        }
                   5603:      } 
                   5604:      fprintf(ficresprobmorprev,"\n");
                   5605:                
                   5606:      fprintf(ficresvij,"%.0f ",age );
                   5607:      for(i=1; i<=nlstate;i++)
                   5608:        for(j=1; j<=nlstate;j++){
                   5609:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   5610:        }
                   5611:      fprintf(ficresvij,"\n");
                   5612:      free_matrix(gp,0,nhstepm,1,nlstate);
                   5613:      free_matrix(gm,0,nhstepm,1,nlstate);
                   5614:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   5615:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   5616:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5617:    } /* End age */
                   5618:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   5619:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   5620:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   5621:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   5622:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   5623:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   5624:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   5625:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   5626:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   5627:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   5628:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   5629:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   5630:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   5631:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   5632:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   5633:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   5634:    fprintf(fichtm,"\n<br> Probability is computed over estepm=%d months. <br> <img src=\"%s%s.svg\"> <br>\n", estepm,subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   5635:    /*  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.svg\"> <br>\n", stepm,YEARM,digitp,digit);
1.126     brouard  5636:     */
1.218     brouard  5637:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   5638:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  5639: 
1.218     brouard  5640:    free_vector(xp,1,npar);
                   5641:    free_matrix(doldm,1,nlstate,1,nlstate);
                   5642:    free_matrix(dnewm,1,nlstate,1,npar);
                   5643:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5644:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   5645:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5646:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   5647:    fclose(ficresprobmorprev);
                   5648:    fflush(ficgp);
                   5649:    fflush(fichtm); 
                   5650:  }  /* end varevsij */
1.126     brouard  5651: 
                   5652: /************ Variance of prevlim ******************/
1.235     brouard  5653:  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 *ncvyearp, int ij, char strstart[], int nres)
1.126     brouard  5654: {
1.205     brouard  5655:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  5656:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  5657: 
1.126     brouard  5658:   double **dnewm,**doldm;
                   5659:   int i, j, nhstepm, hstepm;
                   5660:   double *xp;
                   5661:   double *gp, *gm;
                   5662:   double **gradg, **trgradg;
1.208     brouard  5663:   double **mgm, **mgp;
1.126     brouard  5664:   double age,agelim;
                   5665:   int theta;
                   5666:   
                   5667:   pstamp(ficresvpl);
                   5668:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
1.241     brouard  5669:   fprintf(ficresvpl,"# Age ");
                   5670:   if(nresult >=1)
                   5671:     fprintf(ficresvpl," Result# ");
1.126     brouard  5672:   for(i=1; i<=nlstate;i++)
                   5673:       fprintf(ficresvpl," %1d-%1d",i,i);
                   5674:   fprintf(ficresvpl,"\n");
                   5675: 
                   5676:   xp=vector(1,npar);
                   5677:   dnewm=matrix(1,nlstate,1,npar);
                   5678:   doldm=matrix(1,nlstate,1,nlstate);
                   5679:   
                   5680:   hstepm=1*YEARM; /* Every year of age */
                   5681:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   5682:   agelim = AGESUP;
                   5683:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   5684:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   5685:     if (stepm >= YEARM) hstepm=1;
                   5686:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   5687:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  5688:     mgp=matrix(1,npar,1,nlstate);
                   5689:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  5690:     gp=vector(1,nlstate);
                   5691:     gm=vector(1,nlstate);
                   5692: 
                   5693:     for(theta=1; theta <=npar; theta++){
                   5694:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   5695:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5696:       }
1.209     brouard  5697:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
1.235     brouard  5698:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.209     brouard  5699:       else
1.235     brouard  5700:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  5701:       for(i=1;i<=nlstate;i++){
1.126     brouard  5702:        gp[i] = prlim[i][i];
1.208     brouard  5703:        mgp[theta][i] = prlim[i][i];
                   5704:       }
1.126     brouard  5705:       for(i=1; i<=npar; i++) /* Computes gradient */
                   5706:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.209     brouard  5707:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
1.235     brouard  5708:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.209     brouard  5709:       else
1.235     brouard  5710:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  5711:       for(i=1;i<=nlstate;i++){
1.126     brouard  5712:        gm[i] = prlim[i][i];
1.208     brouard  5713:        mgm[theta][i] = prlim[i][i];
                   5714:       }
1.126     brouard  5715:       for(i=1;i<=nlstate;i++)
                   5716:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  5717:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  5718:     } /* End theta */
                   5719: 
                   5720:     trgradg =matrix(1,nlstate,1,npar);
                   5721: 
                   5722:     for(j=1; j<=nlstate;j++)
                   5723:       for(theta=1; theta <=npar; theta++)
                   5724:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  5725:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   5726:     /*   printf("\nmgm mgp %d ",(int)age); */
                   5727:     /*   for(j=1; j<=nlstate;j++){ */
                   5728:     /*         printf(" %d ",j); */
                   5729:     /*         for(theta=1; theta <=npar; theta++) */
                   5730:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   5731:     /*         printf("\n "); */
                   5732:     /*   } */
                   5733:     /* } */
                   5734:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   5735:     /*   printf("\n gradg %d ",(int)age); */
                   5736:     /*   for(j=1; j<=nlstate;j++){ */
                   5737:     /*         printf("%d ",j); */
                   5738:     /*         for(theta=1; theta <=npar; theta++) */
                   5739:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   5740:     /*         printf("\n "); */
                   5741:     /*   } */
                   5742:     /* } */
1.126     brouard  5743: 
                   5744:     for(i=1;i<=nlstate;i++)
                   5745:       varpl[i][(int)age] =0.;
1.209     brouard  5746:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.205     brouard  5747:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   5748:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   5749:     }else{
1.126     brouard  5750:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   5751:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  5752:     }
1.126     brouard  5753:     for(i=1;i<=nlstate;i++)
                   5754:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   5755: 
                   5756:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  5757:     if(nresult >=1)
                   5758:       fprintf(ficresvpl,"%d ",nres );
1.126     brouard  5759:     for(i=1; i<=nlstate;i++)
                   5760:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   5761:     fprintf(ficresvpl,"\n");
                   5762:     free_vector(gp,1,nlstate);
                   5763:     free_vector(gm,1,nlstate);
1.208     brouard  5764:     free_matrix(mgm,1,npar,1,nlstate);
                   5765:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  5766:     free_matrix(gradg,1,npar,1,nlstate);
                   5767:     free_matrix(trgradg,1,nlstate,1,npar);
                   5768:   } /* End age */
                   5769: 
                   5770:   free_vector(xp,1,npar);
                   5771:   free_matrix(doldm,1,nlstate,1,npar);
                   5772:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   5773: 
                   5774: }
                   5775: 
                   5776: /************ Variance of one-step probabilities  ******************/
                   5777: 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[])
1.222     brouard  5778:  {
                   5779:    int i, j=0,  k1, l1, tj;
                   5780:    int k2, l2, j1,  z1;
                   5781:    int k=0, l;
                   5782:    int first=1, first1, first2;
                   5783:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   5784:    double **dnewm,**doldm;
                   5785:    double *xp;
                   5786:    double *gp, *gm;
                   5787:    double **gradg, **trgradg;
                   5788:    double **mu;
                   5789:    double age, cov[NCOVMAX+1];
                   5790:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   5791:    int theta;
                   5792:    char fileresprob[FILENAMELENGTH];
                   5793:    char fileresprobcov[FILENAMELENGTH];
                   5794:    char fileresprobcor[FILENAMELENGTH];
                   5795:    double ***varpij;
                   5796: 
                   5797:    strcpy(fileresprob,"PROB_"); 
                   5798:    strcat(fileresprob,fileres);
                   5799:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   5800:      printf("Problem with resultfile: %s\n", fileresprob);
                   5801:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   5802:    }
                   5803:    strcpy(fileresprobcov,"PROBCOV_"); 
                   5804:    strcat(fileresprobcov,fileresu);
                   5805:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   5806:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   5807:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   5808:    }
                   5809:    strcpy(fileresprobcor,"PROBCOR_"); 
                   5810:    strcat(fileresprobcor,fileresu);
                   5811:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   5812:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   5813:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   5814:    }
                   5815:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   5816:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   5817:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   5818:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   5819:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   5820:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   5821:    pstamp(ficresprob);
                   5822:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   5823:    fprintf(ficresprob,"# Age");
                   5824:    pstamp(ficresprobcov);
                   5825:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   5826:    fprintf(ficresprobcov,"# Age");
                   5827:    pstamp(ficresprobcor);
                   5828:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   5829:    fprintf(ficresprobcor,"# Age");
1.126     brouard  5830: 
                   5831: 
1.222     brouard  5832:    for(i=1; i<=nlstate;i++)
                   5833:      for(j=1; j<=(nlstate+ndeath);j++){
                   5834:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   5835:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   5836:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   5837:      }  
                   5838:    /* fprintf(ficresprob,"\n");
                   5839:       fprintf(ficresprobcov,"\n");
                   5840:       fprintf(ficresprobcor,"\n");
                   5841:    */
                   5842:    xp=vector(1,npar);
                   5843:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   5844:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   5845:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   5846:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   5847:    first=1;
                   5848:    fprintf(ficgp,"\n# Routine varprob");
                   5849:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   5850:    fprintf(fichtm,"\n");
                   5851: 
                   5852:    fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of one-step probabilities (drawings)</a></h4> this page is important in order to visualize confidence intervals and especially correlation between disability and recovery, or more generally, way in and way back.</li>\n",optionfilehtmcov);
                   5853:    fprintf(fichtmcov,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n",optionfilehtmcov, optionfilehtmcov);
                   5854:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  5855: and drawn. It helps understanding how is the covariance between two incidences.\
                   5856:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  5857:    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. \
1.126     brouard  5858: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   5859: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   5860: standard deviations wide on each axis. <br>\
                   5861:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   5862:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   5863: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   5864: 
1.222     brouard  5865:    cov[1]=1;
                   5866:    /* tj=cptcoveff; */
1.225     brouard  5867:    tj = (int) pow(2,cptcoveff);
1.222     brouard  5868:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   5869:    j1=0;
1.224     brouard  5870:    for(j1=1; j1<=tj;j1++){  /* For each valid combination of covariates or only once*/
1.222     brouard  5871:      if  (cptcovn>0) {
                   5872:        fprintf(ficresprob, "\n#********** Variable "); 
1.225     brouard  5873:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5874:        fprintf(ficresprob, "**********\n#\n");
                   5875:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.225     brouard  5876:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5877:        fprintf(ficresprobcov, "**********\n#\n");
1.220     brouard  5878:                        
1.222     brouard  5879:        fprintf(ficgp, "\n#********** Variable "); 
1.225     brouard  5880:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5881:        fprintf(ficgp, "**********\n#\n");
1.220     brouard  5882:                        
                   5883:                        
1.222     brouard  5884:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.225     brouard  5885:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5886:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  5887:                        
1.222     brouard  5888:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.225     brouard  5889:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5890:        fprintf(ficresprobcor, "**********\n#");    
                   5891:        if(invalidvarcomb[j1]){
                   5892:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   5893:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   5894:         continue;
                   5895:        }
                   5896:      }
                   5897:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   5898:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   5899:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   5900:      gm=vector(1,(nlstate)*(nlstate+ndeath));
                   5901:      for (age=bage; age<=fage; age ++){ 
                   5902:        cov[2]=age;
                   5903:        if(nagesqr==1)
                   5904:         cov[3]= age*age;
                   5905:        for (k=1; k<=cptcovn;k++) {
                   5906:         cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
                   5907:         /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
                   5908:                                                                    * 1  1 1 1 1
                   5909:                                                                    * 2  2 1 1 1
                   5910:                                                                    * 3  1 2 1 1
                   5911:                                                                    */
                   5912:         /* nbcode[1][1]=0 nbcode[1][2]=1;*/
                   5913:        }
                   5914:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   5915:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   5916:        for (k=1; k<=cptcovprod;k++)
                   5917:         cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.220     brouard  5918:                        
                   5919:                        
1.222     brouard  5920:        for(theta=1; theta <=npar; theta++){
                   5921:         for(i=1; i<=npar; i++)
                   5922:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  5923:                                
1.222     brouard  5924:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  5925:                                
1.222     brouard  5926:         k=0;
                   5927:         for(i=1; i<= (nlstate); i++){
                   5928:           for(j=1; j<=(nlstate+ndeath);j++){
                   5929:             k=k+1;
                   5930:             gp[k]=pmmij[i][j];
                   5931:           }
                   5932:         }
1.220     brouard  5933:                                
1.222     brouard  5934:         for(i=1; i<=npar; i++)
                   5935:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  5936:                                
1.222     brouard  5937:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   5938:         k=0;
                   5939:         for(i=1; i<=(nlstate); i++){
                   5940:           for(j=1; j<=(nlstate+ndeath);j++){
                   5941:             k=k+1;
                   5942:             gm[k]=pmmij[i][j];
                   5943:           }
                   5944:         }
1.220     brouard  5945:                                
1.222     brouard  5946:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   5947:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   5948:        }
1.126     brouard  5949: 
1.222     brouard  5950:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   5951:         for(theta=1; theta <=npar; theta++)
                   5952:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  5953:                        
1.222     brouard  5954:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   5955:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  5956:                        
1.222     brouard  5957:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  5958:                        
1.222     brouard  5959:        k=0;
                   5960:        for(i=1; i<=(nlstate); i++){
                   5961:         for(j=1; j<=(nlstate+ndeath);j++){
                   5962:           k=k+1;
                   5963:           mu[k][(int) age]=pmmij[i][j];
                   5964:         }
                   5965:        }
                   5966:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   5967:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   5968:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  5969:                        
1.222     brouard  5970:        /*printf("\n%d ",(int)age);
                   5971:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   5972:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   5973:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   5974:         }*/
1.220     brouard  5975:                        
1.222     brouard  5976:        fprintf(ficresprob,"\n%d ",(int)age);
                   5977:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   5978:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  5979:                        
1.222     brouard  5980:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   5981:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   5982:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   5983:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   5984:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   5985:        }
                   5986:        i=0;
                   5987:        for (k=1; k<=(nlstate);k++){
                   5988:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   5989:           i++;
                   5990:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   5991:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   5992:           for (j=1; j<=i;j++){
                   5993:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   5994:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   5995:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   5996:           }
                   5997:         }
                   5998:        }/* end of loop for state */
                   5999:      } /* end of loop for age */
                   6000:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   6001:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   6002:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   6003:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   6004:     
                   6005:      /* Confidence intervalle of pij  */
                   6006:      /*
                   6007:        fprintf(ficgp,"\nunset parametric;unset label");
                   6008:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   6009:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   6010:        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);
                   6011:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   6012:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   6013:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   6014:      */
                   6015:                
                   6016:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   6017:      first1=1;first2=2;
                   6018:      for (k2=1; k2<=(nlstate);k2++){
                   6019:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   6020:         if(l2==k2) continue;
                   6021:         j=(k2-1)*(nlstate+ndeath)+l2;
                   6022:         for (k1=1; k1<=(nlstate);k1++){
                   6023:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   6024:             if(l1==k1) continue;
                   6025:             i=(k1-1)*(nlstate+ndeath)+l1;
                   6026:             if(i<=j) continue;
                   6027:             for (age=bage; age<=fage; age ++){ 
                   6028:               if ((int)age %5==0){
                   6029:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   6030:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   6031:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   6032:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   6033:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   6034:                 c12=cv12/sqrt(v1*v2);
                   6035:                 /* Computing eigen value of matrix of covariance */
                   6036:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6037:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6038:                 if ((lc2 <0) || (lc1 <0) ){
                   6039:                   if(first2==1){
                   6040:                     first1=0;
                   6041:                     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);
                   6042:                   }
                   6043:                   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);
                   6044:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   6045:                   /* lc2=fabs(lc2); */
                   6046:                 }
1.220     brouard  6047:                                                                
1.222     brouard  6048:                 /* Eigen vectors */
                   6049:                 v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   6050:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   6051:                 v21=(lc1-v1)/cv12*v11;
                   6052:                 v12=-v21;
                   6053:                 v22=v11;
                   6054:                 tnalp=v21/v11;
                   6055:                 if(first1==1){
                   6056:                   first1=0;
                   6057:                   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);
                   6058:                 }
                   6059:                 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);
                   6060:                 /*printf(fignu*/
                   6061:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   6062:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   6063:                 if(first==1){
                   6064:                   first=0;
                   6065:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   6066:                   fprintf(ficgp,"\nset parametric;unset label");
                   6067:                   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);
                   6068:                   fprintf(ficgp,"\nset ter svg size 640, 480");
                   6069:                   fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  6070:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  6071: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  6072:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   6073:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6074:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6075:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   6076:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6077:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   6078:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   6079:                   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",      \
                   6080:                           mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),                                                                         \
                   6081:                           mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   6082:                 }else{
                   6083:                   first=0;
                   6084:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   6085:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   6086:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   6087:                   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", \
                   6088:                           mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),                                 \
                   6089:                           mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   6090:                 }/* if first */
                   6091:               } /* age mod 5 */
                   6092:             } /* end loop age */
                   6093:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6094:             first=1;
                   6095:           } /*l12 */
                   6096:         } /* k12 */
                   6097:        } /*l1 */
                   6098:      }/* k1 */
                   6099:    }  /* loop on combination of covariates j1 */
                   6100:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   6101:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   6102:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   6103:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   6104:    free_vector(xp,1,npar);
                   6105:    fclose(ficresprob);
                   6106:    fclose(ficresprobcov);
                   6107:    fclose(ficresprobcor);
                   6108:    fflush(ficgp);
                   6109:    fflush(fichtmcov);
                   6110:  }
1.126     brouard  6111: 
                   6112: 
                   6113: /******************* Printing html file ***********/
1.201     brouard  6114: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  6115:                  int lastpass, int stepm, int weightopt, char model[],\
                   6116:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.217     brouard  6117:                  int popforecast, int prevfcast, int backcast, int estepm , \
1.213     brouard  6118:                  double jprev1, double mprev1,double anprev1, double dateprev1, \
                   6119:                  double jprev2, double mprev2,double anprev2, double dateprev2){
1.237     brouard  6120:   int jj1, k1, i1, cpt, k4, nres;
1.126     brouard  6121: 
                   6122:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   6123:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   6124: </ul>");
1.237     brouard  6125:    fprintf(fichtm,"<ul><li> model=1+age+%s\n \
                   6126: </ul>", model);
1.214     brouard  6127:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   6128:    fprintf(fichtm,"<li>- Observed frequency between two states (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> (html file)<br/>\n",
                   6129:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
                   6130:    fprintf(fichtm,"<li> - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> (html file) ",
1.213     brouard  6131:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   6132:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  6133:    fprintf(fichtm,"\
                   6134:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  6135:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  6136:    fprintf(fichtm,"\
1.217     brouard  6137:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   6138:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   6139:    fprintf(fichtm,"\
1.126     brouard  6140:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  6141:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  6142:    fprintf(fichtm,"\
1.217     brouard  6143:  - Period (stable) back prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
                   6144:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   6145:    fprintf(fichtm,"\
1.211     brouard  6146:  - (a) Life expectancies by health status at initial age, e<sub>i.</sub> (b) health expectancies by health status at initial age, e<sub>ij</sub> . 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): \
1.126     brouard  6147:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  6148:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  6149:    if(prevfcast==1){
                   6150:      fprintf(fichtm,"\
                   6151:  - Prevalence projections by age and states:                           \
1.201     brouard  6152:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  6153:    }
1.126     brouard  6154: 
1.222     brouard  6155:    fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
1.126     brouard  6156: 
1.225     brouard  6157:    m=pow(2,cptcoveff);
1.222     brouard  6158:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  6159: 
1.222     brouard  6160:    jj1=0;
1.237     brouard  6161: 
                   6162:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.241     brouard  6163:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
1.237     brouard  6164:      if(TKresult[nres]!= k1)
                   6165:        continue;
1.220     brouard  6166: 
1.222     brouard  6167:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   6168:      jj1++;
                   6169:      if (cptcovn > 0) {
                   6170:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  6171:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.237     brouard  6172:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   6173:         printf(" V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);fflush(stdout);
                   6174:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   6175:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  6176:        }
1.237     brouard  6177:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6178:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6179:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);fflush(stdout);
                   6180:       }
                   6181:        
1.230     brouard  6182:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.222     brouard  6183:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   6184:        if(invalidvarcomb[k1]){
                   6185:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   6186:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   6187:         continue;
                   6188:        }
                   6189:      }
                   6190:      /* aij, bij */
1.241     brouard  6191:      fprintf(fichtm,"<br>- Logit model (yours is: 1+age+%s), for example: logit(pij)=log(pij/pii)= aij+ bij age + V1 age + etc. as a function of age: <a href=\"%s_%d-1-%d.svg\">%s_%d-1-%d.svg</a><br> \
                   6192: <img src=\"%s_%d-1-%d.svg\">",model,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres);
1.222     brouard  6193:      /* Pij */
1.241     brouard  6194:      fprintf(fichtm,"<br>\n- P<sub>ij</sub> or conditional probabilities to be observed in state j being in state i, %d (stepm) months before: <a href=\"%s_%d-2-%d.svg\">%s_%d-2-%d.svg</a><br> \
                   6195: <img src=\"%s_%d-2-%d.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres);     
1.222     brouard  6196:      /* Quasi-incidences */
                   6197:      fprintf(fichtm,"<br>\n- I<sub>ij</sub> or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
1.220     brouard  6198:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  6199:  incidence (rates) are the limit when h tends to zero of the ratio of the probability  <sub>h</sub>P<sub>ij</sub> \
1.241     brouard  6200: divided by h: <sub>h</sub>P<sub>ij</sub>/h : <a href=\"%s_%d-3-%d.svg\">%s_%d-3-%d.svg</a><br> \
                   6201: <img src=\"%s_%d-3-%d.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres); 
1.222     brouard  6202:      /* Survival functions (period) in state j */
                   6203:      for(cpt=1; cpt<=nlstate;cpt++){
1.241     brouard  6204:        fprintf(fichtm,"<br>\n- Survival functions in state %d. Or probability to survive in state %d being in state (1 to %d) at different ages. <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a><br> \
                   6205: <img src=\"%s_%d-%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres,subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres,subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.222     brouard  6206:      }
                   6207:      /* State specific survival functions (period) */
                   6208:      for(cpt=1; cpt<=nlstate;cpt++){
                   6209:        fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
1.220     brouard  6210:  Or probability to survive in various states (1 to %d) being in state %d at different ages.    \
1.241     brouard  6211:  <a href=\"%s_%d-%d-%d.svg\">%s_%d%d-%d.svg</a><br> <img src=\"%s_%d-%d-%d.svg\">", cpt, nlstate, cpt, subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres,subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres,subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.222     brouard  6212:      }
                   6213:      /* Period (stable) prevalence in each health state */
                   6214:      for(cpt=1; cpt<=nlstate;cpt++){
1.241     brouard  6215:        fprintf(fichtm,"<br>\n- 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-%d.svg\">%s_%d-%d-%d.svg</a><br> \
                   6216: <img src=\"%s_%d-%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,k1,nres,subdirf2(optionfilefiname,"P_"),cpt,k1,nres,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.222     brouard  6217:      }
                   6218:      if(backcast==1){
                   6219:        /* Period (stable) back prevalence in each health state */
                   6220:        for(cpt=1; cpt<=nlstate;cpt++){
1.241     brouard  6221:         fprintf(fichtm,"<br>\n- Convergence to period (stable) back 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-%d.svg\">%s_%d-%d-%d.svg</a><br> \
                   6222: <img src=\"%s_%d-%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"PB_"),cpt,k1,nres,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.222     brouard  6223:        }
1.217     brouard  6224:      }
1.222     brouard  6225:      if(prevfcast==1){
                   6226:        /* Projection of prevalence up to period (stable) prevalence in each health state */
                   6227:        for(cpt=1; cpt<=nlstate;cpt++){
1.241     brouard  6228:         fprintf(fichtm,"<br>\n- Projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f) up 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-%d.svg\">%s_%d-%d-%d.svg</a><br> \
                   6229: <img src=\"%s_%d-%d-%d.svg\">", dateprev1, dateprev2, cpt, cpt, nlstate, subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres,subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres,subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  6230:        }
                   6231:      }
1.220     brouard  6232:         
1.222     brouard  6233:      for(cpt=1; cpt<=nlstate;cpt++) {
1.241     brouard  6234:        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) (or area under each survival functions): <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a> <br> \
                   6235: <img src=\"%s_%d-%d-%d.svg\">",cpt,nlstate,subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres,subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres,subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.222     brouard  6236:      }
                   6237:      /* } /\* end i1 *\/ */
                   6238:    }/* End k1 */
                   6239:    fprintf(fichtm,"</ul>");
1.126     brouard  6240: 
1.222     brouard  6241:    fprintf(fichtm,"\
1.126     brouard  6242: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  6243:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  6244:  - 95%% confidence intervals and Wald tests of the estimated parameters are in the log file if optimization has been done (mle != 0).<br> \
1.197     brouard  6245: But because parameters are usually highly correlated (a higher incidence of disability \
                   6246: and a higher incidence of recovery can give very close observed transition) it might \
                   6247: be very useful to look not only at linear confidence intervals estimated from the \
                   6248: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   6249: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   6250: covariance matrix of the one-step probabilities. \
                   6251: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  6252: 
1.222     brouard  6253:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   6254:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   6255:    fprintf(fichtm,"\
1.126     brouard  6256:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  6257:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  6258: 
1.222     brouard  6259:    fprintf(fichtm,"\
1.126     brouard  6260:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  6261:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   6262:    fprintf(fichtm,"\
1.126     brouard  6263:  - 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): \
                   6264:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  6265:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  6266:    fprintf(fichtm,"\
1.126     brouard  6267:  - (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): \
                   6268:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  6269:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  6270:    fprintf(fichtm,"\
1.128     brouard  6271:  - 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",
1.222     brouard  6272:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   6273:    fprintf(fichtm,"\
1.128     brouard  6274:  - 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",
1.222     brouard  6275:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   6276:    fprintf(fichtm,"\
1.126     brouard  6277:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  6278:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  6279: 
                   6280: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   6281: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   6282: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   6283: /*     <br>",fileres,fileres,fileres,fileres); */
                   6284: /*  else  */
                   6285: /*    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); */
1.222     brouard  6286:    fflush(fichtm);
                   6287:    fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
1.126     brouard  6288: 
1.225     brouard  6289:    m=pow(2,cptcoveff);
1.222     brouard  6290:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  6291: 
1.222     brouard  6292:    jj1=0;
1.237     brouard  6293: 
1.241     brouard  6294:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.222     brouard  6295:    for(k1=1; k1<=m;k1++){
1.237     brouard  6296:      if(TKresult[nres]!= k1)
                   6297:        continue;
1.222     brouard  6298:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   6299:      jj1++;
1.126     brouard  6300:      if (cptcovn > 0) {
                   6301:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  6302:        for (cpt=1; cpt<=cptcoveff;cpt++)  /**< cptcoveff number of variables */
1.237     brouard  6303:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);
                   6304:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   6305:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6306:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6307:       }
                   6308: 
1.126     brouard  6309:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  6310: 
1.222     brouard  6311:        if(invalidvarcomb[k1]){
                   6312:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   6313:         continue;
                   6314:        }
1.126     brouard  6315:      }
                   6316:      for(cpt=1; cpt<=nlstate;cpt++) {
1.218     brouard  6317:        fprintf(fichtm,"\n<br>- Observed (cross-sectional) and period (incidence based) \
1.241     brouard  6318: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d-%d-%d.svg\"> %s_%d-%d-%d.svg</a>\n <br>\
                   6319: <img src=\"%s_%d-%d-%d.svg\">",cpt,subdirf2(optionfilefiname,"V_"),cpt,k1,nres,subdirf2(optionfilefiname,"V_"),cpt,k1,nres,subdirf2(optionfilefiname,"V_"),cpt,k1,nres);  
1.126     brouard  6320:      }
                   6321:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  6322: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   6323: true period expectancies (those weighted with period prevalences are also\
                   6324:  drawn in addition to the population based expectancies computed using\
1.241     brouard  6325:  observed and cahotic prevalences:  <a href=\"%s_%d-%d.svg\">%s_%d-%d.svg</a>\n<br>\
                   6326: <img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres,subdirf2(optionfilefiname,"E_"),k1,nres,subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  6327:      /* } /\* end i1 *\/ */
                   6328:    }/* End k1 */
1.241     brouard  6329:   }/* End nres */
1.222     brouard  6330:    fprintf(fichtm,"</ul>");
                   6331:    fflush(fichtm);
1.126     brouard  6332: }
                   6333: 
                   6334: /******************* Gnuplot file **************/
1.223     brouard  6335: void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , int prevfcast, int backcast, char pathc[], double p[]){
1.126     brouard  6336: 
                   6337:   char dirfileres[132],optfileres[132];
1.223     brouard  6338:   char gplotcondition[132];
1.237     brouard  6339:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,k4=0,ij=0, ijp=0, l=0;
1.211     brouard  6340:   int lv=0, vlv=0, kl=0;
1.130     brouard  6341:   int ng=0;
1.201     brouard  6342:   int vpopbased;
1.223     brouard  6343:   int ioffset; /* variable offset for columns */
1.235     brouard  6344:   int nres=0; /* Index of resultline */
1.219     brouard  6345: 
1.126     brouard  6346: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   6347: /*     printf("Problem with file %s",optionfilegnuplot); */
                   6348: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   6349: /*   } */
                   6350: 
                   6351:   /*#ifdef windows */
                   6352:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  6353:   /*#endif */
1.225     brouard  6354:   m=pow(2,cptcoveff);
1.126     brouard  6355: 
1.202     brouard  6356:   /* Contribution to likelihood */
                   6357:   /* Plot the probability implied in the likelihood */
1.223     brouard  6358:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   6359:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   6360:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   6361:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  6362: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  6363:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   6364: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  6365:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   6366:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   6367:   fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$13):6 t \"All sample, transitions colored by destination\" with dots lc variable; set out;\n",subdirf(fileresilk));
                   6368:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   6369:   fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$13):5 t \"All sample, transitions colored by origin\" with dots lc variable; set out;\n\n",subdirf(fileresilk));
                   6370:   for (i=1; i<= nlstate ; i ++) {
                   6371:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   6372:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   6373:     fprintf(ficgp,"  u  2:($5 == %d && $6==%d ? $10 : 1/0):($12/4.):6 t \"p%d%d\" with points pointtype 7 ps variable lc variable \\\n",i,1,i,1);
                   6374:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   6375:       fprintf(ficgp,",\\\n \"\" u  2:($5 == %d && $6==%d ? $10 : 1/0):($12/4.):6 t \"p%d%d\" with points pointtype 7 ps variable lc variable ",i,j,i,j);
                   6376:     }
                   6377:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   6378:   }
                   6379:   /* unset log; plot  "rrtest1_sorted_4/ILK_rrtest1_sorted_4.txt" u  2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with points lc variable */               
                   6380:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   6381:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   6382:   fprintf(ficgp,"\nset out;unset log\n");
                   6383:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  6384: 
1.126     brouard  6385:   strcpy(dirfileres,optionfilefiname);
                   6386:   strcpy(optfileres,"vpl");
1.223     brouard  6387:   /* 1eme*/
1.238     brouard  6388:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
                   6389:     for (k1=1; k1<= m ; k1 ++){ /* For each valid combination of covariate */
1.236     brouard  6390:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.238     brouard  6391:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
                   6392:        if(TKresult[nres]!= k1)
                   6393:          continue;
                   6394:        /* We are interested in selected combination by the resultline */
                   6395:        printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt);
                   6396:        fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
                   6397:        for (k=1; k<=cptcoveff; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   6398:          lv= decodtabm(k1,k,cptcoveff); /* Should be the value of the covariate corresponding to k1 combination */
                   6399:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6400:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6401:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6402:          vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
                   6403:          /* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
                   6404:          printf(" V%d=%d ",Tvaraff[k],vlv);
                   6405:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6406:        }
                   6407:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6408:          printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6409:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6410:        }       
                   6411:        printf("\n#\n");
                   6412:        fprintf(ficgp,"\n#\n");
                   6413:        if(invalidvarcomb[k1]){
                   6414:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6415:          continue;
                   6416:        }
1.235     brouard  6417:       
1.241     brouard  6418:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   6419:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
                   6420:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \nset ter svg size 640, 480\nplot [%.f:%.f] \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1,nres);
1.235     brouard  6421:       
1.238     brouard  6422:        for (i=1; i<= nlstate ; i ++) {
                   6423:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   6424:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   6425:        }
1.242     brouard  6426:        fprintf(ficgp,"\" t\"Period (stable) prevalence\" w l lt 0,\"%s\" every :::%d::%d u 1:($2==%d ? $3+1.96*$4 : 1/0) \"%%lf %%lf",subdirf2(fileresu,"VPL_"),k1-1,k1-1,nres);
1.238     brouard  6427:        for (i=1; i<= nlstate ; i ++) {
                   6428:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   6429:          else fprintf(ficgp," %%*lf (%%*lf)");
                   6430:        } 
1.242     brouard  6431:        fprintf(ficgp,"\" t\"95%% CI\" w l lt 1,\"%s\" every :::%d::%d u 1:($2==%d ? $3-1.96*$4 : 1/0) \"%%lf %%lf",subdirf2(fileresu,"VPL_"),k1-1,k1-1,nres); 
1.238     brouard  6432:        for (i=1; i<= nlstate ; i ++) {
                   6433:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   6434:          else fprintf(ficgp," %%*lf (%%*lf)");
                   6435:        }  
                   6436:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" every :::%d::%d u 1:($%d) t\"Observed prevalence\" w l lt 2",subdirf2(fileresu,"P_"),k1-1,k1-1,2+4*(cpt-1));
                   6437:        if(backcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
                   6438:          /* fprintf(ficgp,",\"%s\" every :::%d::%d u 1:($%d) t\"Backward stable prevalence\" w l lt 3",subdirf2(fileresu,"PLB_"),k1-1,k1-1,1+cpt); */
1.242     brouard  6439:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  6440:          if(cptcoveff ==0){
                   6441:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line ",        2+(cpt-1),  cpt );
                   6442:          }else{
                   6443:            kl=0;
                   6444:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   6445:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   6446:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6447:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6448:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6449:              vlv= nbcode[Tvaraff[k]][lv];
1.223     brouard  6450:              kl++;
1.238     brouard  6451:              /* kl=6+(cpt-1)*(nlstate+1)+1+(i-1); /\* 6+(1-1)*(2+1)+1+(1-1)=7, 6+(2-1)(2+1)+1+(1-1)=10 *\/ */
                   6452:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   6453:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   6454:              /* ''  u 6:(($1==1 && $2==0 && $3==2 && $4==0)? $9/(1.-$15) : 1/0):($5==2000? 3:2) t 'p.1' with line lc variable*/
                   6455:              if(k==cptcoveff){
                   6456:                fprintf(ficgp,"$%d==%d && $%d==%d)? $%d : 1/0) t 'Backward prevalence in state %d' ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv], \
1.242     brouard  6457:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  6458:              }else{
                   6459:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   6460:                kl++;
                   6461:              }
                   6462:            } /* end covariate */
                   6463:          } /* end if no covariate */
                   6464:        } /* end if backcast */
                   6465:        fprintf(ficgp,"\nset out \n");
                   6466:       } /* nres */
1.201     brouard  6467:     } /* k1 */
                   6468:   } /* cpt */
1.235     brouard  6469: 
                   6470:   
1.126     brouard  6471:   /*2 eme*/
1.238     brouard  6472:   for (k1=1; k1<= m ; k1 ++){  
                   6473:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6474:       if(TKresult[nres]!= k1)
                   6475:        continue;
                   6476:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
                   6477:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.225     brouard  6478:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
1.223     brouard  6479:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6480:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6481:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6482:        vlv= nbcode[Tvaraff[k]][lv];
                   6483:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  6484:       }
1.237     brouard  6485:       /* for(k=1; k <= ncovds; k++){ */
1.236     brouard  6486:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  6487:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.236     brouard  6488:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  6489:       }
1.211     brouard  6490:       fprintf(ficgp,"\n#\n");
1.223     brouard  6491:       if(invalidvarcomb[k1]){
                   6492:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6493:        continue;
                   6494:       }
1.219     brouard  6495:                        
1.241     brouard  6496:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  6497:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
                   6498:        if(vpopbased==0)
                   6499:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
                   6500:        else
                   6501:          fprintf(ficgp,"\nreplot ");
                   6502:        for (i=1; i<= nlstate+1 ; i ++) {
                   6503:          k=2*i;
                   6504:          fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && $4!=0 ?$4 : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),k1-1,k1-1, vpopbased);
                   6505:          for (j=1; j<= nlstate+1 ; j ++) {
                   6506:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   6507:            else fprintf(ficgp," %%*lf (%%*lf)");
                   6508:          }   
                   6509:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   6510:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
                   6511:          fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && $4!=0 ? $4-$5*2 : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),k1-1,k1-1,vpopbased);
                   6512:          for (j=1; j<= nlstate+1 ; j ++) {
                   6513:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   6514:            else fprintf(ficgp," %%*lf (%%*lf)");
                   6515:          }   
                   6516:          fprintf(ficgp,"\" t\"\" w l lt 0,");
                   6517:          fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && $4!=0 ? $4+$5*2 : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),k1-1,k1-1,vpopbased);
                   6518:          for (j=1; j<= nlstate+1 ; j ++) {
                   6519:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   6520:            else fprintf(ficgp," %%*lf (%%*lf)");
                   6521:          }   
                   6522:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   6523:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   6524:        } /* state */
                   6525:       } /* vpopbased */
                   6526:       fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
                   6527:     } /* end nres */
                   6528:   } /* k1 end 2 eme*/
                   6529:        
                   6530:        
                   6531:   /*3eme*/
                   6532:   for (k1=1; k1<= m ; k1 ++){
                   6533:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.240     brouard  6534:       if(TKresult[nres]!= k1)
1.238     brouard  6535:        continue;
                   6536: 
                   6537:       for (cpt=1; cpt<= nlstate ; cpt ++) {
                   6538:        fprintf(ficgp,"\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
                   6539:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6540:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6541:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6542:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6543:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6544:          vlv= nbcode[Tvaraff[k]][lv];
                   6545:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6546:        }
                   6547:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6548:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6549:        }       
                   6550:        fprintf(ficgp,"\n#\n");
                   6551:        if(invalidvarcomb[k1]){
                   6552:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6553:          continue;
                   6554:        }
                   6555:                        
                   6556:        /*       k=2+nlstate*(2*cpt-2); */
                   6557:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  6558:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.238     brouard  6559:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.201     brouard  6560: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:%d t \"e%d1\" w l",ageminpar,fage,subdirf2(fileresu,"E_"),k1-1,k1-1,k,cpt);
1.238     brouard  6561:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   6562:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   6563:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   6564:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   6565:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   6566:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  6567:                                
1.238     brouard  6568:        */
                   6569:        for (i=1; i< nlstate ; i ++) {
                   6570:          fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d%d\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+i,cpt,i+1);
                   6571:          /*    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);*/
1.219     brouard  6572:                                
1.238     brouard  6573:        } 
                   6574:        fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+nlstate,cpt);
                   6575:       }
                   6576:     } /* end nres */
                   6577:   } /* end kl 3eme */
1.126     brouard  6578:   
1.223     brouard  6579:   /* 4eme */
1.201     brouard  6580:   /* Survival functions (period) from state i in state j by initial state i */
1.238     brouard  6581:   for (k1=1; k1<=m; k1++){    /* For each covariate and each value */
                   6582:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6583:       if(TKresult[nres]!= k1)
1.223     brouard  6584:        continue;
1.238     brouard  6585:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
                   6586:        fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
                   6587:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6588:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6589:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6590:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6591:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6592:          vlv= nbcode[Tvaraff[k]][lv];
                   6593:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6594:        }
                   6595:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6596:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6597:        }       
                   6598:        fprintf(ficgp,"\n#\n");
                   6599:        if(invalidvarcomb[k1]){
                   6600:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6601:          continue;
1.223     brouard  6602:        }
1.238     brouard  6603:       
1.241     brouard  6604:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.238     brouard  6605:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   6606: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   6607:        k=3;
                   6608:        for (i=1; i<= nlstate ; i ++){
                   6609:          if(i==1){
                   6610:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   6611:          }else{
                   6612:            fprintf(ficgp,", '' ");
                   6613:          }
                   6614:          l=(nlstate+ndeath)*(i-1)+1;
                   6615:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   6616:          for (j=2; j<= nlstate+ndeath ; j ++)
                   6617:            fprintf(ficgp,"+$%d",k+l+j-1);
                   6618:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   6619:        } /* nlstate */
                   6620:        fprintf(ficgp,"\nset out\n");
                   6621:       } /* end cpt state*/ 
                   6622:     } /* end nres */
                   6623:   } /* end covariate k1 */  
                   6624: 
1.220     brouard  6625: /* 5eme */
1.201     brouard  6626:   /* Survival functions (period) from state i in state j by final state j */
1.238     brouard  6627:   for (k1=1; k1<= m ; k1++){ /* For each covariate combination if any */
                   6628:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6629:       if(TKresult[nres]!= k1)
1.227     brouard  6630:        continue;
1.238     brouard  6631:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
                   6632:        fprintf(ficgp,"\n#\n#\n# Survival functions in state j and all livestates from state i by final state j: 'lij' files, cov=%d state=%d",k1, cpt);
                   6633:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6634:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6635:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6636:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6637:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6638:          vlv= nbcode[Tvaraff[k]][lv];
                   6639:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6640:        }
                   6641:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6642:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6643:        }       
                   6644:        fprintf(ficgp,"\n#\n");
                   6645:        if(invalidvarcomb[k1]){
                   6646:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6647:          continue;
                   6648:        }
1.227     brouard  6649:       
1.241     brouard  6650:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.238     brouard  6651:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   6652: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   6653:        k=3;
                   6654:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   6655:          if(j==1)
                   6656:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   6657:          else
                   6658:            fprintf(ficgp,", '' ");
                   6659:          l=(nlstate+ndeath)*(cpt-1) +j;
                   6660:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   6661:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   6662:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   6663:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   6664:        } /* nlstate */
                   6665:        fprintf(ficgp,", '' ");
                   6666:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   6667:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   6668:          l=(nlstate+ndeath)*(cpt-1) +j;
                   6669:          if(j < nlstate)
                   6670:            fprintf(ficgp,"$%d +",k+l);
                   6671:          else
                   6672:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   6673:        }
                   6674:        fprintf(ficgp,"\nset out\n");
                   6675:       } /* end cpt state*/ 
                   6676:     } /* end covariate */  
                   6677:   } /* end nres */
1.227     brouard  6678:   
1.220     brouard  6679: /* 6eme */
1.202     brouard  6680:   /* CV preval stable (period) for each covariate */
1.237     brouard  6681:   for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   6682:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6683:     if(TKresult[nres]!= k1)
                   6684:       continue;
1.153     brouard  6685:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.227     brouard  6686:       
1.211     brouard  6687:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.225     brouard  6688:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.227     brouard  6689:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6690:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6691:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6692:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6693:        vlv= nbcode[Tvaraff[k]][lv];
                   6694:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  6695:       }
1.237     brouard  6696:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6697:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6698:       }        
1.211     brouard  6699:       fprintf(ficgp,"\n#\n");
1.223     brouard  6700:       if(invalidvarcomb[k1]){
1.227     brouard  6701:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6702:        continue;
1.223     brouard  6703:       }
1.227     brouard  6704:       
1.241     brouard  6705:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.126     brouard  6706:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  6707: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  6708:       k=3; /* Offset */
1.153     brouard  6709:       for (i=1; i<= nlstate ; i ++){
1.227     brouard  6710:        if(i==1)
                   6711:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   6712:        else
                   6713:          fprintf(ficgp,", '' ");
                   6714:        l=(nlstate+ndeath)*(i-1)+1;
                   6715:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   6716:        for (j=2; j<= nlstate ; j ++)
                   6717:          fprintf(ficgp,"+$%d",k+l+j-1);
                   6718:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  6719:       } /* nlstate */
1.201     brouard  6720:       fprintf(ficgp,"\nset out\n");
1.153     brouard  6721:     } /* end cpt state*/ 
                   6722:   } /* end covariate */  
1.227     brouard  6723:   
                   6724:   
1.220     brouard  6725: /* 7eme */
1.218     brouard  6726:   if(backcast == 1){
1.217     brouard  6727:     /* CV back preval stable (period) for each covariate */
1.237     brouard  6728:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   6729:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6730:       if(TKresult[nres]!= k1)
                   6731:        continue;
1.218     brouard  6732:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.227     brouard  6733:        fprintf(ficgp,"\n#\n#\n#CV Back preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
                   6734:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6735:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6736:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6737:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
1.223     brouard  6738:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.227     brouard  6739:          vlv= nbcode[Tvaraff[k]][lv];
                   6740:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6741:        }
1.237     brouard  6742:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6743:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6744:        }       
1.227     brouard  6745:        fprintf(ficgp,"\n#\n");
                   6746:        if(invalidvarcomb[k1]){
                   6747:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6748:          continue;
                   6749:        }
                   6750:        
1.241     brouard  6751:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.227     brouard  6752:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  6753: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  6754:        k=3; /* Offset */
                   6755:        for (i=1; i<= nlstate ; i ++){
                   6756:          if(i==1)
                   6757:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   6758:          else
                   6759:            fprintf(ficgp,", '' ");
                   6760:          /* l=(nlstate+ndeath)*(i-1)+1; */
                   6761:          l=(nlstate+ndeath)*(cpt-1)+1;
                   6762:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   6763:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l+(cpt-1)+i-1); /\* a vérifier *\/ */
                   6764:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+(cpt-1)+i-1); /* a vérifier */
                   6765:          /* for (j=2; j<= nlstate ; j ++) */
                   6766:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   6767:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
                   6768:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",i,cpt);
                   6769:        } /* nlstate */
                   6770:        fprintf(ficgp,"\nset out\n");
1.218     brouard  6771:       } /* end cpt state*/ 
                   6772:     } /* end covariate */  
                   6773:   } /* End if backcast */
                   6774:   
1.223     brouard  6775:   /* 8eme */
1.218     brouard  6776:   if(prevfcast==1){
                   6777:     /* Projection from cross-sectional to stable (period) for each covariate */
                   6778:     
1.237     brouard  6779:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   6780:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6781:       if(TKresult[nres]!= k1)
                   6782:        continue;
1.211     brouard  6783:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.227     brouard  6784:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to stable (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
                   6785:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   6786:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   6787:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6788:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6789:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6790:          vlv= nbcode[Tvaraff[k]][lv];
                   6791:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6792:        }
1.237     brouard  6793:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6794:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6795:        }       
1.227     brouard  6796:        fprintf(ficgp,"\n#\n");
                   6797:        if(invalidvarcomb[k1]){
                   6798:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6799:          continue;
                   6800:        }
                   6801:        
                   6802:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  6803:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.227     brouard  6804:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  6805: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  6806:        for (i=1; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   6807:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   6808:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   6809:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   6810:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   6811:          if(i==1){
                   6812:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   6813:          }else{
                   6814:            fprintf(ficgp,",\\\n '' ");
                   6815:          }
                   6816:          if(cptcoveff ==0){ /* No covariate */
                   6817:            ioffset=2; /* Age is in 2 */
                   6818:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   6819:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   6820:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   6821:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   6822:            fprintf(ficgp," u %d:(", ioffset); 
                   6823:            if(i==nlstate+1)
                   6824:              fprintf(ficgp," $%d/(1.-$%d)) t 'pw.%d' with line ",      \
                   6825:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   6826:            else
                   6827:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   6828:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   6829:          }else{ /* more than 2 covariates */
                   6830:            if(cptcoveff ==1){
                   6831:              ioffset=4; /* Age is in 4 */
                   6832:            }else{
                   6833:              ioffset=6; /* Age is in 6 */
                   6834:              /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   6835:              /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   6836:            }   
                   6837:            fprintf(ficgp," u %d:(",ioffset); 
                   6838:            kl=0;
                   6839:            strcpy(gplotcondition,"(");
                   6840:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
                   6841:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   6842:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6843:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6844:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6845:              vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   6846:              kl++;
                   6847:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   6848:              kl++;
                   6849:              if(k <cptcoveff && cptcoveff>1)
                   6850:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   6851:            }
                   6852:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   6853:            /* kl=6+(cpt-1)*(nlstate+1)+1+(i-1); /\* 6+(1-1)*(2+1)+1+(1-1)=7, 6+(2-1)(2+1)+1+(1-1)=10 *\/ */
                   6854:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   6855:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   6856:            /* ''  u 6:(($1==1 && $2==0 && $3==2 && $4==0)? $9/(1.-$15) : 1/0):($5==2000? 3:2) t 'p.1' with line lc variable*/
                   6857:            if(i==nlstate+1){
                   6858:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p.%d' with line ", gplotcondition, \
                   6859:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   6860:            }else{
                   6861:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   6862:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   6863:            }
                   6864:          } /* end if covariate */
                   6865:        } /* nlstate */
                   6866:        fprintf(ficgp,"\nset out\n");
1.223     brouard  6867:       } /* end cpt state*/
                   6868:     } /* end covariate */
                   6869:   } /* End if prevfcast */
1.227     brouard  6870:   
                   6871:   
1.238     brouard  6872:   /* 9eme writing MLE parameters */
                   6873:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  6874:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  6875:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  6876:     for(k=1; k <=(nlstate+ndeath); k++){
                   6877:       if (k != i) {
1.227     brouard  6878:        fprintf(ficgp,"#   current state %d\n",k);
                   6879:        for(j=1; j <=ncovmodel; j++){
                   6880:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   6881:          jk++; 
                   6882:        }
                   6883:        fprintf(ficgp,"\n");
1.126     brouard  6884:       }
                   6885:     }
1.223     brouard  6886:   }
1.187     brouard  6887:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  6888:   
1.145     brouard  6889:   /*goto avoid;*/
1.238     brouard  6890:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   6891:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  6892:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   6893:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   6894:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   6895:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   6896:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6897:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   6898:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6899:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   6900:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   6901:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6902:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   6903:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   6904:   fprintf(ficgp,"#\n");
1.223     brouard  6905:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  6906:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.237     brouard  6907:     fprintf(ficgp,"#model=%s \n",model);
1.238     brouard  6908:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.237     brouard  6909:     fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
                   6910:     for(jk=1; jk <=m; jk++)  /* For each combination of covariate */
                   6911:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   6912:       if(TKresult[nres]!= jk)
                   6913:        continue;
                   6914:       fprintf(ficgp,"# Combination of dummy  jk=%d and ",jk);
                   6915:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6916:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6917:       }        
                   6918:       fprintf(ficgp,"\n#\n");
1.241     brouard  6919:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng,nres);
1.223     brouard  6920:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   6921:       if (ng==1){
                   6922:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   6923:        fprintf(ficgp,"\nunset log y");
                   6924:       }else if (ng==2){
                   6925:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   6926:        fprintf(ficgp,"\nset log y");
                   6927:       }else if (ng==3){
                   6928:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   6929:        fprintf(ficgp,"\nset log y");
                   6930:       }else
                   6931:        fprintf(ficgp,"\nunset title ");
                   6932:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   6933:       i=1;
                   6934:       for(k2=1; k2<=nlstate; k2++) {
                   6935:        k3=i;
                   6936:        for(k=1; k<=(nlstate+ndeath); k++) {
                   6937:          if (k != k2){
                   6938:            switch( ng) {
                   6939:            case 1:
                   6940:              if(nagesqr==0)
                   6941:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   6942:              else /* nagesqr =1 */
                   6943:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   6944:              break;
                   6945:            case 2: /* ng=2 */
                   6946:              if(nagesqr==0)
                   6947:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   6948:              else /* nagesqr =1 */
                   6949:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   6950:              break;
                   6951:            case 3:
                   6952:              if(nagesqr==0)
                   6953:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   6954:              else /* nagesqr =1 */
                   6955:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   6956:              break;
                   6957:            }
                   6958:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  6959:            ijp=1; /* product no age */
                   6960:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   6961:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  6962:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.237     brouard  6963:              if(j==Tage[ij]) { /* Product by age */
                   6964:                if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
1.238     brouard  6965:                  if(DummyV[j]==0){
1.237     brouard  6966:                    fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   6967:                  }else{ /* quantitative */
                   6968:                    fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   6969:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   6970:                  }
                   6971:                  ij++;
                   6972:                }
                   6973:              }else if(j==Tprod[ijp]) { /* */ 
                   6974:                /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   6975:                if(ijp <=cptcovprod) { /* Product */
1.238     brouard  6976:                  if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   6977:                    if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
1.237     brouard  6978:                      /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(jk,j)],nbcode[Tvard[ijp][2]][codtabm(jk,j)]); */
                   6979:                      fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   6980:                    }else{ /* Vn is dummy and Vm is quanti */
                   6981:                      /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(jk,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   6982:                      fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   6983:                    }
                   6984:                  }else{ /* Vn*Vm Vn is quanti */
1.238     brouard  6985:                    if(DummyV[Tvard[ijp][2]]==0){
1.237     brouard  6986:                      fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   6987:                    }else{ /* Both quanti */
                   6988:                      fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   6989:                    }
                   6990:                  }
1.238     brouard  6991:                  ijp++;
1.237     brouard  6992:                }
                   6993:              } else{  /* simple covariate */
                   6994:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(jk,j)]); /\* Valgrind bug nbcode *\/ */
                   6995:                if(Dummy[j]==0){
                   6996:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   6997:                }else{ /* quantitative */
                   6998:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.223     brouard  6999:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   7000:                }
1.237     brouard  7001:              } /* end simple */
                   7002:            } /* end j */
1.223     brouard  7003:          }else{
                   7004:            i=i-ncovmodel;
                   7005:            if(ng !=1 ) /* For logit formula of log p11 is more difficult to get */
                   7006:              fprintf(ficgp," (1.");
                   7007:          }
1.227     brouard  7008:          
1.223     brouard  7009:          if(ng != 1){
                   7010:            fprintf(ficgp,")/(1");
1.227     brouard  7011:            
1.223     brouard  7012:            for(k1=1; k1 <=nlstate; k1++){ 
                   7013:              if(nagesqr==0)
                   7014:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                   7015:              else /* nagesqr =1 */
                   7016:                fprintf(ficgp,"+exp(p%d+p%d*x+p%d*x*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1,k3+(k1-1)*ncovmodel+1+nagesqr);
1.217     brouard  7017:               
1.223     brouard  7018:              ij=1;
                   7019:              for(j=3; j <=ncovmodel-nagesqr; j++){
1.237     brouard  7020:                if((j-2)==Tage[ij]) { /* Bug valgrind */
                   7021:                  if(ij <=cptcovage) { /* Bug valgrind */
1.223     brouard  7022:                    fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   7023:                    /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   7024:                    ij++;
                   7025:                  }
                   7026:                }
                   7027:                else
1.225     brouard  7028:                  fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);/* Valgrind bug nbcode */
1.223     brouard  7029:              }
                   7030:              fprintf(ficgp,")");
                   7031:            }
                   7032:            fprintf(ficgp,")");
                   7033:            if(ng ==2)
                   7034:              fprintf(ficgp," t \"p%d%d\" ", k2,k);
                   7035:            else /* ng= 3 */
                   7036:              fprintf(ficgp," t \"i%d%d\" ", k2,k);
                   7037:          }else{ /* end ng <> 1 */
                   7038:            if( k !=k2) /* logit p11 is hard to draw */
                   7039:              fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
                   7040:          }
                   7041:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   7042:            fprintf(ficgp,",");
                   7043:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   7044:            fprintf(ficgp,",");
                   7045:          i=i+ncovmodel;
                   7046:        } /* end k */
                   7047:       } /* end k2 */
                   7048:       fprintf(ficgp,"\n set out\n");
                   7049:     } /* end jk */
                   7050:   } /* end ng */
                   7051:   /* avoid: */
                   7052:   fflush(ficgp); 
1.126     brouard  7053: }  /* end gnuplot */
                   7054: 
                   7055: 
                   7056: /*************** Moving average **************/
1.219     brouard  7057: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  7058:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  7059:    
1.222     brouard  7060:    int i, cpt, cptcod;
                   7061:    int modcovmax =1;
                   7062:    int mobilavrange, mob;
                   7063:    int iage=0;
                   7064: 
                   7065:    double sum=0.;
                   7066:    double age;
                   7067:    double *sumnewp, *sumnewm;
                   7068:    double *agemingood, *agemaxgood; /* Currently identical for all covariates */
                   7069:   
                   7070:   
1.225     brouard  7071:    /* modcovmax=2*cptcoveff;/\* Max number of modalities. We suppose  */
1.222     brouard  7072:    /*             a covariate has 2 modalities, should be equal to ncovcombmax  *\/ */
                   7073: 
                   7074:    sumnewp = vector(1,ncovcombmax);
                   7075:    sumnewm = vector(1,ncovcombmax);
                   7076:    agemingood = vector(1,ncovcombmax); 
                   7077:    agemaxgood = vector(1,ncovcombmax);
                   7078: 
                   7079:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   7080:      sumnewm[cptcod]=0.;
                   7081:      sumnewp[cptcod]=0.;
                   7082:      agemingood[cptcod]=0;
                   7083:      agemaxgood[cptcod]=0;
                   7084:    }
                   7085:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   7086:   
                   7087:    if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   7088:      if(mobilav==1) mobilavrange=5; /* default */
                   7089:      else mobilavrange=mobilav;
                   7090:      for (age=bage; age<=fage; age++)
                   7091:        for (i=1; i<=nlstate;i++)
                   7092:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   7093:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   7094:      /* We keep the original values on the extreme ages bage, fage and for 
                   7095:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   7096:        we use a 5 terms etc. until the borders are no more concerned. 
                   7097:      */ 
                   7098:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   7099:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   7100:         for (i=1; i<=nlstate;i++){
                   7101:           for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   7102:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   7103:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   7104:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   7105:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   7106:             }
                   7107:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   7108:           }
                   7109:         }
                   7110:        }/* end age */
                   7111:      }/* end mob */
                   7112:    }else
                   7113:      return -1;
                   7114:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   7115:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   7116:      if(invalidvarcomb[cptcod]){
                   7117:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   7118:        continue;
                   7119:      }
1.219     brouard  7120: 
1.222     brouard  7121:      agemingood[cptcod]=fage-(mob-1)/2;
                   7122:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, finding the youngest wrong */
                   7123:        sumnewm[cptcod]=0.;
                   7124:        for (i=1; i<=nlstate;i++){
                   7125:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   7126:        }
                   7127:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   7128:         agemingood[cptcod]=age;
                   7129:        }else{ /* bad */
                   7130:         for (i=1; i<=nlstate;i++){
                   7131:           mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   7132:         } /* i */
                   7133:        } /* end bad */
                   7134:      }/* age */
                   7135:      sum=0.;
                   7136:      for (i=1; i<=nlstate;i++){
                   7137:        sum+=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   7138:      }
                   7139:      if(fabs(sum - 1.) > 1.e-3) { /* bad */
                   7140:        printf("For this combination of covariate cptcod=%d, we can't get a smoothed prevalence which sums to one at any descending age!\n",cptcod);
                   7141:        /* for (i=1; i<=nlstate;i++){ */
                   7142:        /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   7143:        /* } /\* i *\/ */
                   7144:      } /* end bad */
                   7145:      /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   7146:      /* From youngest, finding the oldest wrong */
                   7147:      agemaxgood[cptcod]=bage+(mob-1)/2;
                   7148:      for (age=bage+(mob-1)/2; age<=fage; age++){
                   7149:        sumnewm[cptcod]=0.;
                   7150:        for (i=1; i<=nlstate;i++){
                   7151:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   7152:        }
                   7153:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   7154:         agemaxgood[cptcod]=age;
                   7155:        }else{ /* bad */
                   7156:         for (i=1; i<=nlstate;i++){
                   7157:           mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   7158:         } /* i */
                   7159:        } /* end bad */
                   7160:      }/* age */
                   7161:      sum=0.;
                   7162:      for (i=1; i<=nlstate;i++){
                   7163:        sum+=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   7164:      }
                   7165:      if(fabs(sum - 1.) > 1.e-3) { /* bad */
                   7166:        printf("For this combination of covariate cptcod=%d, we can't get a smoothed prevalence which sums to one at any ascending age!\n",cptcod);
                   7167:        /* for (i=1; i<=nlstate;i++){ */
                   7168:        /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   7169:        /* } /\* i *\/ */
                   7170:      } /* end bad */
                   7171:                
                   7172:      for (age=bage; age<=fage; age++){
1.235     brouard  7173:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  7174:        sumnewp[cptcod]=0.;
                   7175:        sumnewm[cptcod]=0.;
                   7176:        for (i=1; i<=nlstate;i++){
                   7177:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   7178:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   7179:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   7180:        }
                   7181:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   7182:      }
                   7183:      /* printf("\n"); */
                   7184:      /* } */
                   7185:      /* brutal averaging */
                   7186:      for (i=1; i<=nlstate;i++){
                   7187:        for (age=1; age<=bage; age++){
                   7188:         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   7189:         /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
                   7190:        }       
                   7191:        for (age=fage; age<=AGESUP; age++){
                   7192:         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   7193:         /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
                   7194:        }
                   7195:      } /* end i status */
                   7196:      for (i=nlstate+1; i<=nlstate+ndeath;i++){
                   7197:        for (age=1; age<=AGESUP; age++){
                   7198:         /*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*/
                   7199:         mobaverage[(int)age][i][cptcod]=0.;
                   7200:        }
                   7201:      }
                   7202:    }/* end cptcod */
                   7203:    free_vector(sumnewm,1, ncovcombmax);
                   7204:    free_vector(sumnewp,1, ncovcombmax);
                   7205:    free_vector(agemaxgood,1, ncovcombmax);
                   7206:    free_vector(agemingood,1, ncovcombmax);
                   7207:    return 0;
                   7208:  }/* End movingaverage */
1.218     brouard  7209:  
1.126     brouard  7210: 
                   7211: /************** Forecasting ******************/
1.235     brouard  7212:  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){
1.126     brouard  7213:   /* proj1, year, month, day of starting projection 
                   7214:      agemin, agemax range of age
                   7215:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   7216:      anproj2 year of en of projection (same day and month as proj1).
                   7217:   */
1.235     brouard  7218:    int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  7219:   double agec; /* generic age */
                   7220:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   7221:   double *popeffectif,*popcount;
                   7222:   double ***p3mat;
1.218     brouard  7223:   /* double ***mobaverage; */
1.126     brouard  7224:   char fileresf[FILENAMELENGTH];
                   7225: 
                   7226:   agelim=AGESUP;
1.211     brouard  7227:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   7228:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   7229:      We still use firstpass and lastpass as another selection.
                   7230:   */
1.214     brouard  7231:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   7232:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  7233:  
1.201     brouard  7234:   strcpy(fileresf,"F_"); 
                   7235:   strcat(fileresf,fileresu);
1.126     brouard  7236:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   7237:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   7238:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   7239:   }
1.235     brouard  7240:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   7241:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  7242: 
1.225     brouard  7243:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  7244: 
                   7245: 
                   7246:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   7247:   if (stepm<=12) stepsize=1;
                   7248:   if(estepm < stepm){
                   7249:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   7250:   }
                   7251:   else  hstepm=estepm;   
                   7252: 
                   7253:   hstepm=hstepm/stepm; 
                   7254:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   7255:                                fractional in yp1 */
                   7256:   anprojmean=yp;
                   7257:   yp2=modf((yp1*12),&yp);
                   7258:   mprojmean=yp;
                   7259:   yp1=modf((yp2*30.5),&yp);
                   7260:   jprojmean=yp;
                   7261:   if(jprojmean==0) jprojmean=1;
                   7262:   if(mprojmean==0) jprojmean=1;
                   7263: 
1.227     brouard  7264:   i1=pow(2,cptcoveff);
1.126     brouard  7265:   if (cptcovn < 1){i1=1;}
                   7266:   
                   7267:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   7268:   
                   7269:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  7270:   
1.126     brouard  7271: /*           if (h==(int)(YEARM*yearp)){ */
1.235     brouard  7272:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   7273:   for(k=1; k<=i1;k++){
                   7274:     if(TKresult[nres]!= k)
                   7275:       continue;
1.227     brouard  7276:     if(invalidvarcomb[k]){
                   7277:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   7278:       continue;
                   7279:     }
                   7280:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   7281:     for(j=1;j<=cptcoveff;j++) {
                   7282:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7283:     }
1.235     brouard  7284:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  7285:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.235     brouard  7286:     }
1.227     brouard  7287:     fprintf(ficresf," yearproj age");
                   7288:     for(j=1; j<=nlstate+ndeath;j++){ 
                   7289:       for(i=1; i<=nlstate;i++)               
                   7290:        fprintf(ficresf," p%d%d",i,j);
                   7291:       fprintf(ficresf," wp.%d",j);
                   7292:     }
                   7293:     for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
                   7294:       fprintf(ficresf,"\n");
                   7295:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   7296:       for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   7297:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   7298:        nhstepm = nhstepm/hstepm; 
                   7299:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7300:        oldm=oldms;savm=savms;
1.235     brouard  7301:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.227     brouard  7302:        
                   7303:        for (h=0; h<=nhstepm; h++){
                   7304:          if (h*hstepm/YEARM*stepm ==yearp) {
                   7305:            fprintf(ficresf,"\n");
                   7306:            for(j=1;j<=cptcoveff;j++) 
                   7307:              fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7308:            fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   7309:          } 
                   7310:          for(j=1; j<=nlstate+ndeath;j++) {
                   7311:            ppij=0.;
                   7312:            for(i=1; i<=nlstate;i++) {
                   7313:              if (mobilav==1) 
                   7314:                ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][k];
                   7315:              else {
                   7316:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   7317:              }
                   7318:              if (h*hstepm/YEARM*stepm== yearp) {
                   7319:                fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   7320:              }
                   7321:            } /* end i */
                   7322:            if (h*hstepm/YEARM*stepm==yearp) {
                   7323:              fprintf(ficresf," %.3f", ppij);
                   7324:            }
                   7325:          }/* end j */
                   7326:        } /* end h */
                   7327:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7328:       } /* end agec */
                   7329:     } /* end yearp */
                   7330:   } /* end  k */
1.219     brouard  7331:        
1.126     brouard  7332:   fclose(ficresf);
1.215     brouard  7333:   printf("End of Computing forecasting \n");
                   7334:   fprintf(ficlog,"End of Computing forecasting\n");
                   7335: 
1.126     brouard  7336: }
                   7337: 
1.218     brouard  7338: /* /\************** Back Forecasting ******************\/ */
1.225     brouard  7339: /* void prevbackforecast(char fileres[], double anback1, double mback1, double jback1, double ageminpar, double agemax, double dateprev1, double dateprev2, int mobilav, double bage, double fage, int firstpass, int lastpass, double anback2, double p[], int cptcoveff){ */
1.218     brouard  7340: /*   /\* back1, year, month, day of starting backection  */
                   7341: /*      agemin, agemax range of age */
                   7342: /*      dateprev1 dateprev2 range of dates during which prevalence is computed */
                   7343: /*      anback2 year of en of backection (same day and month as back1). */
                   7344: /*   *\/ */
                   7345: /*   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1; */
                   7346: /*   double agec; /\* generic age *\/ */
                   7347: /*   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean; */
                   7348: /*   double *popeffectif,*popcount; */
                   7349: /*   double ***p3mat; */
                   7350: /*   /\* double ***mobaverage; *\/ */
                   7351: /*   char fileresfb[FILENAMELENGTH]; */
                   7352:        
                   7353: /*   agelim=AGESUP; */
                   7354: /*   /\* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people */
                   7355: /*      in each health status at the date of interview (if between dateprev1 and dateprev2). */
                   7356: /*      We still use firstpass and lastpass as another selection. */
                   7357: /*   *\/ */
                   7358: /*   /\* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ *\/ */
                   7359: /*   /\*             firstpass, lastpass,  stepm,  weightopt, model); *\/ */
                   7360: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   7361:        
                   7362: /*   strcpy(fileresfb,"FB_");  */
                   7363: /*   strcat(fileresfb,fileresu); */
                   7364: /*   if((ficresfb=fopen(fileresfb,"w"))==NULL) { */
                   7365: /*     printf("Problem with back forecast resultfile: %s\n", fileresfb); */
                   7366: /*     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb); */
                   7367: /*   } */
                   7368: /*   printf("Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
                   7369: /*   fprintf(ficlog,"Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
                   7370:        
1.225     brouard  7371: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.218     brouard  7372:        
                   7373: /*   /\* if (mobilav!=0) { *\/ */
                   7374: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   7375: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   7376: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7377: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7378: /*   /\*   } *\/ */
                   7379: /*   /\* } *\/ */
                   7380:        
                   7381: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   7382: /*   if (stepm<=12) stepsize=1; */
                   7383: /*   if(estepm < stepm){ */
                   7384: /*     printf ("Problem %d lower than %d\n",estepm, stepm); */
                   7385: /*   } */
                   7386: /*   else  hstepm=estepm;    */
                   7387:        
                   7388: /*   hstepm=hstepm/stepm;  */
                   7389: /*   yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   7390: /*                                fractional in yp1 *\/ */
                   7391: /*   anprojmean=yp; */
                   7392: /*   yp2=modf((yp1*12),&yp); */
                   7393: /*   mprojmean=yp; */
                   7394: /*   yp1=modf((yp2*30.5),&yp); */
                   7395: /*   jprojmean=yp; */
                   7396: /*   if(jprojmean==0) jprojmean=1; */
                   7397: /*   if(mprojmean==0) jprojmean=1; */
                   7398:        
1.225     brouard  7399: /*   i1=cptcoveff; */
1.218     brouard  7400: /*   if (cptcovn < 1){i1=1;} */
1.217     brouard  7401:   
1.218     brouard  7402: /*   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);  */
1.217     brouard  7403:   
1.218     brouard  7404: /*   fprintf(ficresfb,"#****** Routine prevbackforecast **\n"); */
                   7405:        
                   7406: /*     /\*           if (h==(int)(YEARM*yearp)){ *\/ */
                   7407: /*   for(cptcov=1, k=0;cptcov<=i1;cptcov++){ */
1.225     brouard  7408: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
1.218     brouard  7409: /*       k=k+1; */
                   7410: /*       fprintf(ficresfb,"\n#****** hbijx=probability over h years, hp.jx is weighted by observed prev \n#"); */
1.225     brouard  7411: /*       for(j=1;j<=cptcoveff;j++) { */
1.218     brouard  7412: /*                             fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   7413: /*       } */
                   7414: /*       fprintf(ficresfb," yearbproj age"); */
                   7415: /*       for(j=1; j<=nlstate+ndeath;j++){  */
                   7416: /*                             for(i=1; i<=nlstate;i++)               */
                   7417: /*           fprintf(ficresfb," p%d%d",i,j); */
                   7418: /*                             fprintf(ficresfb," p.%d",j); */
                   7419: /*       } */
                   7420: /*       for (yearp=0; yearp>=(anback2-anback1);yearp -=stepsize) {  */
                   7421: /*                             /\* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  *\/ */
                   7422: /*                             fprintf(ficresfb,"\n"); */
                   7423: /*                             fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp);    */
                   7424: /*                             for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   7425: /*                                     nhstepm=(int) rint((agelim-agec)*YEARM/stepm);  */
                   7426: /*                                     nhstepm = nhstepm/hstepm;  */
                   7427: /*                                     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7428: /*                                     oldm=oldms;savm=savms; */
                   7429: /*                                     hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm,oldm,savm, dnewm, doldm, dsavm, k);       */
                   7430: /*                                     for (h=0; h<=nhstepm; h++){ */
                   7431: /*                                             if (h*hstepm/YEARM*stepm ==yearp) { */
                   7432: /*               fprintf(ficresfb,"\n"); */
1.225     brouard  7433: /*               for(j=1;j<=cptcoveff;j++)  */
1.218     brouard  7434: /*                 fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   7435: /*                                                     fprintf(ficresfb,"%.f %.f ",anback1+yearp,agec+h*hstepm/YEARM*stepm); */
                   7436: /*                                             }  */
                   7437: /*                                             for(j=1; j<=nlstate+ndeath;j++) { */
                   7438: /*                                                     ppij=0.; */
                   7439: /*                                                     for(i=1; i<=nlstate;i++) { */
                   7440: /*                                                             if (mobilav==1)  */
                   7441: /*                                                                     ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod]; */
                   7442: /*                                                             else { */
                   7443: /*                                                                     ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod]; */
                   7444: /*                                                             } */
                   7445: /*                                                             if (h*hstepm/YEARM*stepm== yearp) { */
                   7446: /*                                                                     fprintf(ficresfb," %.3f", p3mat[i][j][h]); */
                   7447: /*                                                             } */
                   7448: /*                                                     } /\* end i *\/ */
                   7449: /*                                                     if (h*hstepm/YEARM*stepm==yearp) { */
                   7450: /*                                                             fprintf(ficresfb," %.3f", ppij); */
                   7451: /*                                                     } */
                   7452: /*                                             }/\* end j *\/ */
                   7453: /*                                     } /\* end h *\/ */
                   7454: /*                                     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7455: /*                             } /\* end agec *\/ */
                   7456: /*       } /\* end yearp *\/ */
                   7457: /*     } /\* end cptcod *\/ */
                   7458: /*   } /\* end  cptcov *\/ */
                   7459:        
                   7460: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   7461:        
                   7462: /*   fclose(ficresfb); */
                   7463: /*   printf("End of Computing Back forecasting \n"); */
                   7464: /*   fprintf(ficlog,"End of Computing Back forecasting\n"); */
1.217     brouard  7465:        
1.218     brouard  7466: /* } */
1.217     brouard  7467: 
1.126     brouard  7468: /************** Forecasting *****not tested NB*************/
1.227     brouard  7469: /* void populforecast(char fileres[], double anpyram,double mpyram,double jpyram,double ageminpar, double agemax,double dateprev1, double dateprev2s, int mobilav, double agedeb, double fage, int popforecast, char popfile[], double anpyram1,double p[], int i2){ */
1.126     brouard  7470:   
1.227     brouard  7471: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   7472: /*   int *popage; */
                   7473: /*   double calagedatem, agelim, kk1, kk2; */
                   7474: /*   double *popeffectif,*popcount; */
                   7475: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   7476: /*   /\* double ***mobaverage; *\/ */
                   7477: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  7478: 
1.227     brouard  7479: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7480: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7481: /*   agelim=AGESUP; */
                   7482: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  7483:   
1.227     brouard  7484: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  7485:   
                   7486:   
1.227     brouard  7487: /*   strcpy(filerespop,"POP_");  */
                   7488: /*   strcat(filerespop,fileresu); */
                   7489: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   7490: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   7491: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   7492: /*   } */
                   7493: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   7494: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  7495: 
1.227     brouard  7496: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  7497: 
1.227     brouard  7498: /*   /\* if (mobilav!=0) { *\/ */
                   7499: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   7500: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   7501: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7502: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7503: /*   /\*   } *\/ */
                   7504: /*   /\* } *\/ */
1.126     brouard  7505: 
1.227     brouard  7506: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   7507: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  7508:   
1.227     brouard  7509: /*   agelim=AGESUP; */
1.126     brouard  7510:   
1.227     brouard  7511: /*   hstepm=1; */
                   7512: /*   hstepm=hstepm/stepm;  */
1.218     brouard  7513:        
1.227     brouard  7514: /*   if (popforecast==1) { */
                   7515: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   7516: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   7517: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   7518: /*     }  */
                   7519: /*     popage=ivector(0,AGESUP); */
                   7520: /*     popeffectif=vector(0,AGESUP); */
                   7521: /*     popcount=vector(0,AGESUP); */
1.126     brouard  7522:     
1.227     brouard  7523: /*     i=1;    */
                   7524: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  7525:     
1.227     brouard  7526: /*     imx=i; */
                   7527: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   7528: /*   } */
1.218     brouard  7529:   
1.227     brouard  7530: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   7531: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   7532: /*       k=k+1; */
                   7533: /*       fprintf(ficrespop,"\n#******"); */
                   7534: /*       for(j=1;j<=cptcoveff;j++) { */
                   7535: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   7536: /*       } */
                   7537: /*       fprintf(ficrespop,"******\n"); */
                   7538: /*       fprintf(ficrespop,"# Age"); */
                   7539: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   7540: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  7541:       
1.227     brouard  7542: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   7543: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  7544:        
1.227     brouard  7545: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   7546: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   7547: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  7548:          
1.227     brouard  7549: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7550: /*       oldm=oldms;savm=savms; */
                   7551: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  7552:          
1.227     brouard  7553: /*       for (h=0; h<=nhstepm; h++){ */
                   7554: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   7555: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   7556: /*         }  */
                   7557: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   7558: /*           kk1=0.;kk2=0; */
                   7559: /*           for(i=1; i<=nlstate;i++) {               */
                   7560: /*             if (mobilav==1)  */
                   7561: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   7562: /*             else { */
                   7563: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   7564: /*             } */
                   7565: /*           } */
                   7566: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   7567: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   7568: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   7569: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   7570: /*           } */
                   7571: /*         } */
                   7572: /*         for(i=1; i<=nlstate;i++){ */
                   7573: /*           kk1=0.; */
                   7574: /*           for(j=1; j<=nlstate;j++){ */
                   7575: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   7576: /*           } */
                   7577: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   7578: /*         } */
1.218     brouard  7579:            
1.227     brouard  7580: /*         if (h==(int)(calagedatem+12*cpt)) */
                   7581: /*           for(j=1; j<=nlstate;j++)  */
                   7582: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   7583: /*       } */
                   7584: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7585: /*     } */
                   7586: /*       } */
1.218     brouard  7587:       
1.227     brouard  7588: /*       /\******\/ */
1.218     brouard  7589:       
1.227     brouard  7590: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   7591: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   7592: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   7593: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   7594: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  7595:          
1.227     brouard  7596: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7597: /*       oldm=oldms;savm=savms; */
                   7598: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   7599: /*       for (h=0; h<=nhstepm; h++){ */
                   7600: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   7601: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   7602: /*         }  */
                   7603: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   7604: /*           kk1=0.;kk2=0; */
                   7605: /*           for(i=1; i<=nlstate;i++) {               */
                   7606: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   7607: /*           } */
                   7608: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   7609: /*         } */
                   7610: /*       } */
                   7611: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7612: /*     } */
                   7613: /*       } */
                   7614: /*     }  */
                   7615: /*   } */
1.218     brouard  7616:   
1.227     brouard  7617: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  7618:   
1.227     brouard  7619: /*   if (popforecast==1) { */
                   7620: /*     free_ivector(popage,0,AGESUP); */
                   7621: /*     free_vector(popeffectif,0,AGESUP); */
                   7622: /*     free_vector(popcount,0,AGESUP); */
                   7623: /*   } */
                   7624: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7625: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7626: /*   fclose(ficrespop); */
                   7627: /* } /\* End of popforecast *\/ */
1.218     brouard  7628:  
1.126     brouard  7629: int fileappend(FILE *fichier, char *optionfich)
                   7630: {
                   7631:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   7632:     printf("Problem with file: %s\n", optionfich);
                   7633:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   7634:     return (0);
                   7635:   }
                   7636:   fflush(fichier);
                   7637:   return (1);
                   7638: }
                   7639: 
                   7640: 
                   7641: /**************** function prwizard **********************/
                   7642: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   7643: {
                   7644: 
                   7645:   /* Wizard to print covariance matrix template */
                   7646: 
1.164     brouard  7647:   char ca[32], cb[32];
                   7648:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  7649:   int numlinepar;
                   7650: 
                   7651:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7652:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7653:   for(i=1; i <=nlstate; i++){
                   7654:     jj=0;
                   7655:     for(j=1; j <=nlstate+ndeath; j++){
                   7656:       if(j==i) continue;
                   7657:       jj++;
                   7658:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   7659:       printf("%1d%1d",i,j);
                   7660:       fprintf(ficparo,"%1d%1d",i,j);
                   7661:       for(k=1; k<=ncovmodel;k++){
                   7662:        /*        printf(" %lf",param[i][j][k]); */
                   7663:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   7664:        printf(" 0.");
                   7665:        fprintf(ficparo," 0.");
                   7666:       }
                   7667:       printf("\n");
                   7668:       fprintf(ficparo,"\n");
                   7669:     }
                   7670:   }
                   7671:   printf("# Scales (for hessian or gradient estimation)\n");
                   7672:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   7673:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   7674:   for(i=1; i <=nlstate; i++){
                   7675:     jj=0;
                   7676:     for(j=1; j <=nlstate+ndeath; j++){
                   7677:       if(j==i) continue;
                   7678:       jj++;
                   7679:       fprintf(ficparo,"%1d%1d",i,j);
                   7680:       printf("%1d%1d",i,j);
                   7681:       fflush(stdout);
                   7682:       for(k=1; k<=ncovmodel;k++){
                   7683:        /*      printf(" %le",delti3[i][j][k]); */
                   7684:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   7685:        printf(" 0.");
                   7686:        fprintf(ficparo," 0.");
                   7687:       }
                   7688:       numlinepar++;
                   7689:       printf("\n");
                   7690:       fprintf(ficparo,"\n");
                   7691:     }
                   7692:   }
                   7693:   printf("# Covariance matrix\n");
                   7694: /* # 121 Var(a12)\n\ */
                   7695: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   7696: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   7697: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   7698: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   7699: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   7700: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   7701: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   7702:   fflush(stdout);
                   7703:   fprintf(ficparo,"# Covariance matrix\n");
                   7704:   /* # 121 Var(a12)\n\ */
                   7705:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   7706:   /* #   ...\n\ */
                   7707:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   7708:   
                   7709:   for(itimes=1;itimes<=2;itimes++){
                   7710:     jj=0;
                   7711:     for(i=1; i <=nlstate; i++){
                   7712:       for(j=1; j <=nlstate+ndeath; j++){
                   7713:        if(j==i) continue;
                   7714:        for(k=1; k<=ncovmodel;k++){
                   7715:          jj++;
                   7716:          ca[0]= k+'a'-1;ca[1]='\0';
                   7717:          if(itimes==1){
                   7718:            printf("#%1d%1d%d",i,j,k);
                   7719:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   7720:          }else{
                   7721:            printf("%1d%1d%d",i,j,k);
                   7722:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   7723:            /*  printf(" %.5le",matcov[i][j]); */
                   7724:          }
                   7725:          ll=0;
                   7726:          for(li=1;li <=nlstate; li++){
                   7727:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   7728:              if(lj==li) continue;
                   7729:              for(lk=1;lk<=ncovmodel;lk++){
                   7730:                ll++;
                   7731:                if(ll<=jj){
                   7732:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   7733:                  if(ll<jj){
                   7734:                    if(itimes==1){
                   7735:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7736:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7737:                    }else{
                   7738:                      printf(" 0.");
                   7739:                      fprintf(ficparo," 0.");
                   7740:                    }
                   7741:                  }else{
                   7742:                    if(itimes==1){
                   7743:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   7744:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   7745:                    }else{
                   7746:                      printf(" 0.");
                   7747:                      fprintf(ficparo," 0.");
                   7748:                    }
                   7749:                  }
                   7750:                }
                   7751:              } /* end lk */
                   7752:            } /* end lj */
                   7753:          } /* end li */
                   7754:          printf("\n");
                   7755:          fprintf(ficparo,"\n");
                   7756:          numlinepar++;
                   7757:        } /* end k*/
                   7758:       } /*end j */
                   7759:     } /* end i */
                   7760:   } /* end itimes */
                   7761: 
                   7762: } /* end of prwizard */
                   7763: /******************* Gompertz Likelihood ******************************/
                   7764: double gompertz(double x[])
                   7765: { 
                   7766:   double A,B,L=0.0,sump=0.,num=0.;
                   7767:   int i,n=0; /* n is the size of the sample */
                   7768: 
1.220     brouard  7769:   for (i=1;i<=imx ; i++) {
1.126     brouard  7770:     sump=sump+weight[i];
                   7771:     /*    sump=sump+1;*/
                   7772:     num=num+1;
                   7773:   }
                   7774:  
                   7775:  
                   7776:   /* for (i=0; i<=imx; i++) 
                   7777:      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]);*/
                   7778: 
                   7779:   for (i=1;i<=imx ; i++)
                   7780:     {
                   7781:       if (cens[i] == 1 && wav[i]>1)
                   7782:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   7783:       
                   7784:       if (cens[i] == 0 && wav[i]>1)
                   7785:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   7786:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   7787:       
                   7788:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   7789:       if (wav[i] > 1 ) { /* ??? */
                   7790:        L=L+A*weight[i];
                   7791:        /*      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]);*/
                   7792:       }
                   7793:     }
                   7794: 
                   7795:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   7796:  
                   7797:   return -2*L*num/sump;
                   7798: }
                   7799: 
1.136     brouard  7800: #ifdef GSL
                   7801: /******************* Gompertz_f Likelihood ******************************/
                   7802: double gompertz_f(const gsl_vector *v, void *params)
                   7803: { 
                   7804:   double A,B,LL=0.0,sump=0.,num=0.;
                   7805:   double *x= (double *) v->data;
                   7806:   int i,n=0; /* n is the size of the sample */
                   7807: 
                   7808:   for (i=0;i<=imx-1 ; i++) {
                   7809:     sump=sump+weight[i];
                   7810:     /*    sump=sump+1;*/
                   7811:     num=num+1;
                   7812:   }
                   7813:  
                   7814:  
                   7815:   /* for (i=0; i<=imx; i++) 
                   7816:      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]);*/
                   7817:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   7818:   for (i=1;i<=imx ; i++)
                   7819:     {
                   7820:       if (cens[i] == 1 && wav[i]>1)
                   7821:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   7822:       
                   7823:       if (cens[i] == 0 && wav[i]>1)
                   7824:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   7825:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   7826:       
                   7827:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   7828:       if (wav[i] > 1 ) { /* ??? */
                   7829:        LL=LL+A*weight[i];
                   7830:        /*      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]);*/
                   7831:       }
                   7832:     }
                   7833: 
                   7834:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   7835:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   7836:  
                   7837:   return -2*LL*num/sump;
                   7838: }
                   7839: #endif
                   7840: 
1.126     brouard  7841: /******************* Printing html file ***********/
1.201     brouard  7842: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  7843:                  int lastpass, int stepm, int weightopt, char model[],\
                   7844:                  int imx,  double p[],double **matcov,double agemortsup){
                   7845:   int i,k;
                   7846: 
                   7847:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   7848:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   7849:   for (i=1;i<=2;i++) 
                   7850:     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]));
1.199     brouard  7851:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  7852:   fprintf(fichtm,"</ul>");
                   7853: 
                   7854: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   7855: 
                   7856:  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>");
                   7857: 
                   7858:  for (k=agegomp;k<(agemortsup-2);k++) 
                   7859:    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]);
                   7860: 
                   7861:  
                   7862:   fflush(fichtm);
                   7863: }
                   7864: 
                   7865: /******************* Gnuplot file **************/
1.201     brouard  7866: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  7867: 
                   7868:   char dirfileres[132],optfileres[132];
1.164     brouard  7869: 
1.126     brouard  7870:   int ng;
                   7871: 
                   7872: 
                   7873:   /*#ifdef windows */
                   7874:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   7875:     /*#endif */
                   7876: 
                   7877: 
                   7878:   strcpy(dirfileres,optionfilefiname);
                   7879:   strcpy(optfileres,"vpl");
1.199     brouard  7880:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  7881:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  7882:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  7883:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  7884:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   7885: 
                   7886: } 
                   7887: 
1.136     brouard  7888: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   7889: {
1.126     brouard  7890: 
1.136     brouard  7891:   /*-------- data file ----------*/
                   7892:   FILE *fic;
                   7893:   char dummy[]="                         ";
1.240     brouard  7894:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  7895:   int lstra;
1.136     brouard  7896:   int linei, month, year,iout;
                   7897:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  7898:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  7899:   char *stratrunc;
1.223     brouard  7900: 
1.240     brouard  7901:   DummyV=ivector(1,NCOVMAX); /* 1 to 3 */
                   7902:   FixedV=ivector(1,NCOVMAX); /* 1 to 3 */
1.126     brouard  7903: 
1.240     brouard  7904:   for(v=1; v <=ncovcol;v++){
                   7905:     DummyV[v]=0;
                   7906:     FixedV[v]=0;
                   7907:   }
                   7908:   for(v=ncovcol+1; v <=ncovcol+nqv;v++){
                   7909:     DummyV[v]=1;
                   7910:     FixedV[v]=0;
                   7911:   }
                   7912:   for(v=ncovcol+nqv+1; v <=ncovcol+nqv+ntv;v++){
                   7913:     DummyV[v]=0;
                   7914:     FixedV[v]=1;
                   7915:   }
                   7916:   for(v=ncovcol+nqv+ntv+1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   7917:     DummyV[v]=1;
                   7918:     FixedV[v]=1;
                   7919:   }
                   7920:   for(v=1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   7921:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   7922:     fprintf(ficlog,"Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   7923:   }
1.126     brouard  7924: 
1.136     brouard  7925:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  7926:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   7927:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  7928:   }
1.126     brouard  7929: 
1.136     brouard  7930:   i=1;
                   7931:   linei=0;
                   7932:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   7933:     linei=linei+1;
                   7934:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   7935:       if(line[j] == '\t')
                   7936:        line[j] = ' ';
                   7937:     }
                   7938:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   7939:       ;
                   7940:     };
                   7941:     line[j+1]=0;  /* Trims blanks at end of line */
                   7942:     if(line[0]=='#'){
                   7943:       fprintf(ficlog,"Comment line\n%s\n",line);
                   7944:       printf("Comment line\n%s\n",line);
                   7945:       continue;
                   7946:     }
                   7947:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  7948:     strcpy(line, linetmp);
1.223     brouard  7949:     
                   7950:     /* Loops on waves */
                   7951:     for (j=maxwav;j>=1;j--){
                   7952:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  7953:        cutv(stra, strb, line, ' '); 
                   7954:        if(strb[0]=='.') { /* Missing value */
                   7955:          lval=-1;
                   7956:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
                   7957:          cotvar[j][ntv+iv][i]=-1; /* For performance reasons */
                   7958:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   7959:            printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d th quantitative value out of %d measured at wave %d. If missing, you should remove this individual or impute a value.  Exiting.\n", strb, linei,i,line,iv, nqtv, j);
                   7960:            fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d th quantitative value out of %d measured at wave %d. If missing, you should remove this individual or impute a value.  Exiting.\n", strb, linei,i,line,iv, nqtv, j);fflush(ficlog);
                   7961:            return 1;
                   7962:          }
                   7963:        }else{
                   7964:          errno=0;
                   7965:          /* what_kind_of_number(strb); */
                   7966:          dval=strtod(strb,&endptr); 
                   7967:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   7968:          /* if(strb != endptr && *endptr == '\0') */
                   7969:          /*    dval=dlval; */
                   7970:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   7971:          if( strb[0]=='\0' || (*endptr != '\0')){
                   7972:            printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d th quantitative value out of %d measured at wave %d. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line,iv, nqtv, j,maxwav);
                   7973:            fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d th quantitative value out of %d measured at wave %d. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line, iv, nqtv, j,maxwav);fflush(ficlog);
                   7974:            return 1;
                   7975:          }
                   7976:          cotqvar[j][iv][i]=dval; 
                   7977:          cotvar[j][ntv+iv][i]=dval; 
                   7978:        }
                   7979:        strcpy(line,stra);
1.223     brouard  7980:       }/* end loop ntqv */
1.225     brouard  7981:       
1.223     brouard  7982:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  7983:        cutv(stra, strb, line, ' '); 
                   7984:        if(strb[0]=='.') { /* Missing value */
                   7985:          lval=-1;
                   7986:        }else{
                   7987:          errno=0;
                   7988:          lval=strtol(strb,&endptr,10); 
                   7989:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   7990:          if( strb[0]=='\0' || (*endptr != '\0')){
                   7991:            printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d th dummy covariate out of %d measured at wave %d. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line,iv, ntv, j,maxwav);
                   7992:            fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d dummy covariate out of %d measured wave %d. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line,iv, ntv,j,maxwav);fflush(ficlog);
                   7993:            return 1;
                   7994:          }
                   7995:        }
                   7996:        if(lval <-1 || lval >1){
                   7997:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.223     brouard  7998:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   7999:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  8000:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   8001:  build V1=0 V2=0 for the reference value (1),\n                                \
                   8002:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  8003:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  8004:  output of IMaCh is often meaningless.\n                               \
1.223     brouard  8005:  Exiting.\n",lval,linei, i,line,j);
1.238     brouard  8006:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.223     brouard  8007:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   8008:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  8009:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   8010:  build V1=0 V2=0 for the reference value (1),\n                                \
                   8011:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  8012:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  8013:  output of IMaCh is often meaningless.\n                               \
1.223     brouard  8014:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.238     brouard  8015:          return 1;
                   8016:        }
                   8017:        cotvar[j][iv][i]=(double)(lval);
                   8018:        strcpy(line,stra);
1.223     brouard  8019:       }/* end loop ntv */
1.225     brouard  8020:       
1.223     brouard  8021:       /* Statuses  at wave */
1.137     brouard  8022:       cutv(stra, strb, line, ' '); 
1.223     brouard  8023:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  8024:        lval=-1;
1.136     brouard  8025:       }else{
1.238     brouard  8026:        errno=0;
                   8027:        lval=strtol(strb,&endptr,10); 
                   8028:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   8029:        if( strb[0]=='\0' || (*endptr != '\0')){
                   8030:          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);
                   8031:          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);
                   8032:          return 1;
                   8033:        }
1.136     brouard  8034:       }
1.225     brouard  8035:       
1.136     brouard  8036:       s[j][i]=lval;
1.225     brouard  8037:       
1.223     brouard  8038:       /* Date of Interview */
1.136     brouard  8039:       strcpy(line,stra);
                   8040:       cutv(stra, strb,line,' ');
1.169     brouard  8041:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  8042:       }
1.169     brouard  8043:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  8044:        month=99;
                   8045:        year=9999;
1.136     brouard  8046:       }else{
1.225     brouard  8047:        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);
                   8048:        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);
                   8049:        return 1;
1.136     brouard  8050:       }
                   8051:       anint[j][i]= (double) year; 
                   8052:       mint[j][i]= (double)month; 
                   8053:       strcpy(line,stra);
1.223     brouard  8054:     } /* End loop on waves */
1.225     brouard  8055:     
1.223     brouard  8056:     /* Date of death */
1.136     brouard  8057:     cutv(stra, strb,line,' '); 
1.169     brouard  8058:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  8059:     }
1.169     brouard  8060:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  8061:       month=99;
                   8062:       year=9999;
                   8063:     }else{
1.141     brouard  8064:       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);
1.225     brouard  8065:       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);
                   8066:       return 1;
1.136     brouard  8067:     }
                   8068:     andc[i]=(double) year; 
                   8069:     moisdc[i]=(double) month; 
                   8070:     strcpy(line,stra);
                   8071:     
1.223     brouard  8072:     /* Date of birth */
1.136     brouard  8073:     cutv(stra, strb,line,' '); 
1.169     brouard  8074:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  8075:     }
1.169     brouard  8076:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  8077:       month=99;
                   8078:       year=9999;
                   8079:     }else{
1.141     brouard  8080:       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);
                   8081:       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);
1.225     brouard  8082:       return 1;
1.136     brouard  8083:     }
                   8084:     if (year==9999) {
1.141     brouard  8085:       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);
                   8086:       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);
1.225     brouard  8087:       return 1;
                   8088:       
1.136     brouard  8089:     }
                   8090:     annais[i]=(double)(year);
                   8091:     moisnais[i]=(double)(month); 
                   8092:     strcpy(line,stra);
1.225     brouard  8093:     
1.223     brouard  8094:     /* Sample weight */
1.136     brouard  8095:     cutv(stra, strb,line,' '); 
                   8096:     errno=0;
                   8097:     dval=strtod(strb,&endptr); 
                   8098:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  8099:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   8100:       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);
1.136     brouard  8101:       fflush(ficlog);
                   8102:       return 1;
                   8103:     }
                   8104:     weight[i]=dval; 
                   8105:     strcpy(line,stra);
1.225     brouard  8106:     
1.223     brouard  8107:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   8108:       cutv(stra, strb, line, ' '); 
                   8109:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  8110:        lval=-1;
1.223     brouard  8111:       }else{
1.225     brouard  8112:        errno=0;
                   8113:        /* what_kind_of_number(strb); */
                   8114:        dval=strtod(strb,&endptr);
                   8115:        /* if(strb != endptr && *endptr == '\0') */
                   8116:        /*   dval=dlval; */
                   8117:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   8118:        if( strb[0]=='\0' || (*endptr != '\0')){
                   8119:          printf("Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d th quantitative value (out of %d) constant for all waves. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line, iv, nqv, maxwav);
                   8120:          fprintf(ficlog,"Error reading data around '%s' at line number %d for individual %d, '%s'\nShould be the %d th quantitative value (out of %d) constant for all waves. Setting maxwav=%d might be wrong.  Exiting.\n", strb, linei,i,line, iv, nqv, maxwav);fflush(ficlog);
                   8121:          return 1;
                   8122:        }
                   8123:        coqvar[iv][i]=dval; 
1.226     brouard  8124:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  8125:       }
                   8126:       strcpy(line,stra);
                   8127:     }/* end loop nqv */
1.136     brouard  8128:     
1.223     brouard  8129:     /* Covariate values */
1.136     brouard  8130:     for (j=ncovcol;j>=1;j--){
                   8131:       cutv(stra, strb,line,' '); 
1.223     brouard  8132:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  8133:        lval=-1;
1.136     brouard  8134:       }else{
1.225     brouard  8135:        errno=0;
                   8136:        lval=strtol(strb,&endptr,10); 
                   8137:        if( strb[0]=='\0' || (*endptr != '\0')){
                   8138:          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);
                   8139:          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);
                   8140:          return 1;
                   8141:        }
1.136     brouard  8142:       }
                   8143:       if(lval <-1 || lval >1){
1.225     brouard  8144:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  8145:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   8146:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  8147:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   8148:  build V1=0 V2=0 for the reference value (1),\n                                \
                   8149:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  8150:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  8151:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  8152:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  8153:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  8154:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   8155:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  8156:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   8157:  build V1=0 V2=0 for the reference value (1),\n                                \
                   8158:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  8159:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  8160:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  8161:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  8162:        return 1;
1.136     brouard  8163:       }
                   8164:       covar[j][i]=(double)(lval);
                   8165:       strcpy(line,stra);
                   8166:     }  
                   8167:     lstra=strlen(stra);
1.225     brouard  8168:     
1.136     brouard  8169:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   8170:       stratrunc = &(stra[lstra-9]);
                   8171:       num[i]=atol(stratrunc);
                   8172:     }
                   8173:     else
                   8174:       num[i]=atol(stra);
                   8175:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   8176:       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;}*/
                   8177:     
                   8178:     i=i+1;
                   8179:   } /* End loop reading  data */
1.225     brouard  8180:   
1.136     brouard  8181:   *imax=i-1; /* Number of individuals */
                   8182:   fclose(fic);
1.225     brouard  8183:   
1.136     brouard  8184:   return (0);
1.164     brouard  8185:   /* endread: */
1.225     brouard  8186:   printf("Exiting readdata: ");
                   8187:   fclose(fic);
                   8188:   return (1);
1.223     brouard  8189: }
1.126     brouard  8190: 
1.234     brouard  8191: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  8192:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  8193:   while (*p2 == ' ')
1.234     brouard  8194:     p2++; 
                   8195:   /* while ((*p1++ = *p2++) !=0) */
                   8196:   /*   ; */
                   8197:   /* do */
                   8198:   /*   while (*p2 == ' ') */
                   8199:   /*     p2++; */
                   8200:   /* while (*p1++ == *p2++); */
                   8201:   *stri=p2; 
1.145     brouard  8202: }
                   8203: 
1.235     brouard  8204: int decoderesult ( char resultline[], int nres)
1.230     brouard  8205: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   8206: {
1.235     brouard  8207:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  8208:   char resultsav[MAXLINE];
1.234     brouard  8209:   int resultmodel[MAXLINE];
                   8210:   int modelresult[MAXLINE];
1.230     brouard  8211:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   8212: 
1.234     brouard  8213:   removefirstspace(&resultline);
1.233     brouard  8214:   printf("decoderesult:%s\n",resultline);
1.230     brouard  8215: 
                   8216:   if (strstr(resultline,"v") !=0){
                   8217:     printf("Error. 'v' must be in upper case 'V' result: %s ",resultline);
                   8218:     fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultline);fflush(ficlog);
                   8219:     return 1;
                   8220:   }
                   8221:   trimbb(resultsav, resultline);
                   8222:   if (strlen(resultsav) >1){
                   8223:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' */
                   8224:   }
1.234     brouard  8225:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
                   8226:     printf("ERROR: the number of variable in the resultline, %d, differs from the number of variable used in the model line, %d.\n",j, cptcovs);
                   8227:     fprintf(ficlog,"ERROR: the number of variable in the resultline, %d, differs from the number of variable used in the model line, %d.\n",j, cptcovs);
                   8228:   }
                   8229:   for(k=1; k<=j;k++){ /* Loop on any covariate of the result line */
                   8230:     if(nbocc(resultsav,'=') >1){
                   8231:        cutl(stra,strb,resultsav,' '); /* keeps in strb after the first ' ' 
                   8232:                                      resultsav= V4=1 V5=25.1 V3=0 strb=V3=0 stra= V4=1 V5=25.1 */
                   8233:        cutl(strc,strd,strb,'=');  /* strb:V4=1 strc=1 strd=V4 */
                   8234:     }else
                   8235:       cutl(strc,strd,resultsav,'=');
1.230     brouard  8236:     Tvalsel[k]=atof(strc); /* 1 */
1.234     brouard  8237:     
1.230     brouard  8238:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
                   8239:     Tvarsel[k]=atoi(strc);
                   8240:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   8241:     /* cptcovsel++;     */
                   8242:     if (nbocc(stra,'=') >0)
                   8243:       strcpy(resultsav,stra); /* and analyzes it */
                   8244:   }
1.235     brouard  8245:   /* Checking for missing or useless values in comparison of current model needs */
1.236     brouard  8246:   for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8247:     if(Typevar[k1]==0){ /* Single covariate in model */
1.234     brouard  8248:       match=0;
1.236     brouard  8249:       for(k2=1; k2 <=j;k2++){/* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.237     brouard  8250:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar[1]=5 == Tvarsel[2]=5   */
1.236     brouard  8251:          modelresult[k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.234     brouard  8252:          match=1;
                   8253:          break;
                   8254:        }
                   8255:       }
                   8256:       if(match == 0){
                   8257:        printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
                   8258:       }
                   8259:     }
                   8260:   }
1.235     brouard  8261:   /* Checking for missing or useless values in comparison of current model needs */
                   8262:   for(k2=1; k2 <=j;k2++){ /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  8263:     match=0;
1.235     brouard  8264:     for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8265:       if(Typevar[k1]==0){ /* Single */
1.237     brouard  8266:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4   */
1.235     brouard  8267:          resultmodel[k1]=k2;  /* resultmodel[2]=1 resultmodel[1]=2  resultmodel[3]=3  resultmodel[6]=4 resultmodel[9]=5 */
1.234     brouard  8268:          ++match;
                   8269:        }
                   8270:       }
                   8271:     }
                   8272:     if(match == 0){
                   8273:       printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
                   8274:     }else if(match > 1){
                   8275:       printf("Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
                   8276:     }
                   8277:   }
1.235     brouard  8278:       
1.234     brouard  8279:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  8280:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8281:   /* result line V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   8282:   /* should give a combination of dummy V4=1, V3=0, V1=1 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 5 + (1offset) = 6*/
                   8283:   /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   8284:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   8285:   /*    1 0 0 0 */
                   8286:   /*    2 1 0 0 */
                   8287:   /*    3 0 1 0 */ 
                   8288:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 */
                   8289:   /*    5 0 0 1 */
                   8290:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 */
                   8291:   /*    7 0 1 1 */
                   8292:   /*    8 1 1 1 */
1.237     brouard  8293:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   8294:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   8295:   /* V5*age V5 known which value for nres?  */
                   8296:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.235     brouard  8297:   for(k1=1, k=0, k4=0, k4q=0; k1 <=cptcovt;k1++){ /* model line */
                   8298:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Single dummy */
1.237     brouard  8299:       k3= resultmodel[k1]; /* resultmodel[2(V4)] = 1=k3 */
1.235     brouard  8300:       k2=(int)Tvarsel[k3]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
                   8301:       k+=Tvalsel[k3]*pow(2,k4);  /*  Tvalsel[1]=1  */
1.237     brouard  8302:       Tresult[nres][k4+1]=Tvalsel[k3];/* Tresult[nres][1]=1(V4=1)  Tresult[nres][2]=0(V3=0) */
                   8303:       Tvresult[nres][k4+1]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   8304:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.235     brouard  8305:       printf("Decoderesult Dummy k=%d, V(k2=V%d)= Tvalsel[%d]=%d, 2**(%d)\n",k, k2, k3, (int)Tvalsel[k3], k4);
                   8306:       k4++;;
                   8307:     }  else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Single quantitative */
                   8308:       k3q= resultmodel[k1]; /* resultmodel[2] = 1=k3 */
                   8309:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
1.237     brouard  8310:       Tqresult[nres][k4q+1]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   8311:       Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
                   8312:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.235     brouard  8313:       printf("Decoderesult Quantitative nres=%d, V(k2q=V%d)= Tvalsel[%d]=%d, Tvarsel[%d]=%f\n",nres, k2q, k3q, Tvarsel[k3q], k3q, Tvalsel[k3q]);
                   8314:       k4q++;;
                   8315:     }
                   8316:   }
1.234     brouard  8317:   
1.235     brouard  8318:   TKresult[nres]=++k; /* Combination for the nresult and the model */
1.230     brouard  8319:   return (0);
                   8320: }
1.235     brouard  8321: 
1.230     brouard  8322: int decodemodel( char model[], int lastobs)
                   8323:  /**< This routine decodes the model and returns:
1.224     brouard  8324:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   8325:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   8326:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   8327:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   8328:        * - cptcovage number of covariates with age*products =2
                   8329:        * - cptcovs number of simple covariates
                   8330:        * - 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
                   8331:        *     which is a new column after the 9 (ncovcol) variables. 
                   8332:        * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   8333:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   8334:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   8335:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   8336:        */
1.136     brouard  8337: {
1.238     brouard  8338:   int i, j, k, ks, v;
1.227     brouard  8339:   int  j1, k1, k2, k3, k4;
1.136     brouard  8340:   char modelsav[80];
1.145     brouard  8341:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  8342:   char *strpt;
1.136     brouard  8343: 
1.145     brouard  8344:   /*removespace(model);*/
1.136     brouard  8345:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  8346:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  8347:     if (strstr(model,"AGE") !=0){
1.192     brouard  8348:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   8349:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  8350:       return 1;
                   8351:     }
1.141     brouard  8352:     if (strstr(model,"v") !=0){
                   8353:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   8354:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   8355:       return 1;
                   8356:     }
1.187     brouard  8357:     strcpy(modelsav,model); 
                   8358:     if ((strpt=strstr(model,"age*age")) !=0){
                   8359:       printf(" strpt=%s, model=%s\n",strpt, model);
                   8360:       if(strpt != model){
1.234     brouard  8361:        printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  8362:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  8363:  corresponding column of parameters.\n",model);
1.234     brouard  8364:        fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  8365:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  8366:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  8367:        return 1;
1.225     brouard  8368:       }
1.187     brouard  8369:       nagesqr=1;
                   8370:       if (strstr(model,"+age*age") !=0)
1.234     brouard  8371:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  8372:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  8373:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  8374:       else 
1.234     brouard  8375:        substrchaine(modelsav, model, "age*age");
1.187     brouard  8376:     }else
                   8377:       nagesqr=0;
                   8378:     if (strlen(modelsav) >1){
                   8379:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   8380:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.224     brouard  8381:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.187     brouard  8382:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  8383:                     * cst, age and age*age 
                   8384:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   8385:       /* including age products which are counted in cptcovage.
                   8386:        * but the covariates which are products must be treated 
                   8387:        * separately: ncovn=4- 2=2 (V1+V3). */
1.187     brouard  8388:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   8389:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.225     brouard  8390:       
                   8391:       
1.187     brouard  8392:       /*   Design
                   8393:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   8394:        *  <          ncovcol=8                >
                   8395:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   8396:        *   k=  1    2      3       4     5       6      7        8
                   8397:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   8398:        *  covar[k,i], value of kth covariate if not including age for individual i:
1.224     brouard  8399:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   8400:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  8401:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   8402:        *  Tage[++cptcovage]=k
                   8403:        *       if products, new covar are created after ncovcol with k1
                   8404:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   8405:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   8406:        *  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
                   8407:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   8408:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   8409:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   8410:        *  <          ncovcol=8                >
                   8411:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   8412:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   8413:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   8414:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   8415:        * p Tprod[1]@2={                         6, 5}
                   8416:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   8417:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   8418:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   8419:        *How to reorganize?
                   8420:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   8421:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   8422:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   8423:        * Struct []
                   8424:        */
1.225     brouard  8425:       
1.187     brouard  8426:       /* This loop fills the array Tvar from the string 'model'.*/
                   8427:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   8428:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   8429:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   8430:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   8431:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   8432:       /*       k=1 Tvar[1]=2 (from V2) */
                   8433:       /*       k=5 Tvar[5] */
                   8434:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  8435:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  8436:       /*       } */
1.198     brouard  8437:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  8438:       /*
                   8439:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  8440:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   8441:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   8442:       }
1.187     brouard  8443:       cptcovage=0;
                   8444:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
1.234     brouard  8445:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
1.225     brouard  8446:                                         modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
1.234     brouard  8447:        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
                   8448:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   8449:        /*scanf("%d",i);*/
                   8450:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   8451:          cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   8452:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   8453:            /* covar is not filled and then is empty */
                   8454:            cptcovprod--;
                   8455:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   8456:            Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
                   8457:            Typevar[k]=1;  /* 1 for age product */
                   8458:            cptcovage++; /* Sums the number of covariates which include age as a product */
                   8459:            Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   8460:            /*printf("stre=%s ", stre);*/
                   8461:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   8462:            cptcovprod--;
                   8463:            cutl(stre,strb,strc,'V');
                   8464:            Tvar[k]=atoi(stre);
                   8465:            Typevar[k]=1;  /* 1 for age product */
                   8466:            cptcovage++;
                   8467:            Tage[cptcovage]=k;
                   8468:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   8469:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   8470:            cptcovn++;
                   8471:            cptcovprodnoage++;k1++;
                   8472:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   8473:            Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* For model-covariate k tells which data-covariate to use but
                   8474:                                                because this model-covariate is a construction we invent a new column
                   8475:                                                which is after existing variables ncovcol+nqv+ntv+nqtv + k1
                   8476:                                                If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   8477:                                                Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
                   8478:            Typevar[k]=2;  /* 2 for double fixed dummy covariates */
                   8479:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   8480:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
                   8481:            Tposprod[k]=k1; /* Tpsprod[3]=1, Tposprod[2]=5 */
                   8482:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   8483:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   8484:            k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   8485:            /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   8486:            /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
1.225     brouard  8487:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
1.234     brouard  8488:            /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   8489:            for (i=1; i<=lastobs;i++){
                   8490:              /* Computes the new covariate which is a product of
                   8491:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   8492:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   8493:            }
                   8494:          } /* End age is not in the model */
                   8495:        } /* End if model includes a product */
                   8496:        else { /* no more sum */
                   8497:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   8498:          /*  scanf("%d",i);*/
                   8499:          cutl(strd,strc,strb,'V');
                   8500:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   8501:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   8502:          Tvar[k]=atoi(strd);
                   8503:          Typevar[k]=0;  /* 0 for simple covariates */
                   8504:        }
                   8505:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  8506:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  8507:                                  scanf("%d",i);*/
1.187     brouard  8508:       } /* end of loop + on total covariates */
                   8509:     } /* end if strlen(modelsave == 0) age*age might exist */
                   8510:   } /* end if strlen(model == 0) */
1.136     brouard  8511:   
                   8512:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   8513:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  8514:   
1.136     brouard  8515:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  8516:      printf("cptcovprod=%d ", cptcovprod);
                   8517:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   8518:      scanf("%d ",i);*/
                   8519: 
                   8520: 
1.230     brouard  8521: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   8522:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  8523: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   8524:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   8525:    k =           1    2   3     4       5       6      7      8        9
                   8526:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
                   8527:    Typevar[k]=   0    0   0     2       1       0      2      1        1
1.227     brouard  8528:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   8529:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   8530:          Tmodelind[combination of covar]=k;
1.225     brouard  8531: */  
                   8532: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  8533:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  8534:   /* Tvar[k] is the value n of Vn with n varying for 1 to nvcol, or p  Vp=Vn*Vm for product */
1.226     brouard  8535:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.227     brouard  8536:   printf("Model=%s\n\
                   8537: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   8538: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   8539: Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product\n",model);
                   8540:   fprintf(ficlog,"Model=%s\n\
                   8541: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   8542: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   8543: Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product\n",model);
1.240     brouard  8544:   for(k=1;k<=cptcovt; k++){ Fixed[k]=0; Dummy[k]=0;}
1.234     brouard  8545:   for(k=1, ncovf=0, nsd=0, nsq=0, ncovv=0, ncova=0, ncoveff=0, nqfveff=0, ntveff=0, nqtveff=0;k<=cptcovt; k++){ /* or cptocvt */
                   8546:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  8547:       Fixed[k]= 0;
                   8548:       Dummy[k]= 0;
1.225     brouard  8549:       ncoveff++;
1.232     brouard  8550:       ncovf++;
1.234     brouard  8551:       nsd++;
                   8552:       modell[k].maintype= FTYPE;
                   8553:       TvarsD[nsd]=Tvar[k];
                   8554:       TvarsDind[nsd]=k;
                   8555:       TvarF[ncovf]=Tvar[k];
                   8556:       TvarFind[ncovf]=k;
                   8557:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8558:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8559:     }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /* Product of fixed dummy (<=ncovcol) covariates */
                   8560:       Fixed[k]= 0;
                   8561:       Dummy[k]= 0;
                   8562:       ncoveff++;
                   8563:       ncovf++;
                   8564:       modell[k].maintype= FTYPE;
                   8565:       TvarF[ncovf]=Tvar[k];
                   8566:       TvarFind[ncovf]=k;
1.230     brouard  8567:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  8568:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.240     brouard  8569:     }else if( Tvar[k] <=ncovcol+nqv && Typevar[k]==0){/* Remind that product Vn*Vm are added in k Only simple fixed quantitative variable */
1.227     brouard  8570:       Fixed[k]= 0;
                   8571:       Dummy[k]= 1;
1.230     brouard  8572:       nqfveff++;
1.234     brouard  8573:       modell[k].maintype= FTYPE;
                   8574:       modell[k].subtype= FQ;
                   8575:       nsq++;
                   8576:       TvarsQ[nsq]=Tvar[k];
                   8577:       TvarsQind[nsq]=k;
1.232     brouard  8578:       ncovf++;
1.234     brouard  8579:       TvarF[ncovf]=Tvar[k];
                   8580:       TvarFind[ncovf]=k;
1.231     brouard  8581:       TvarFQ[nqfveff]=Tvar[k]-ncovcol; /* TvarFQ[1]=V2-1=1st in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
1.230     brouard  8582:       TvarFQind[nqfveff]=k; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
1.242     brouard  8583:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.227     brouard  8584:       Fixed[k]= 1;
                   8585:       Dummy[k]= 0;
1.225     brouard  8586:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  8587:       modell[k].maintype= VTYPE;
                   8588:       modell[k].subtype= VD;
                   8589:       nsd++;
                   8590:       TvarsD[nsd]=Tvar[k];
                   8591:       TvarsDind[nsd]=k;
                   8592:       ncovv++; /* Only simple time varying variables */
                   8593:       TvarV[ncovv]=Tvar[k];
1.242     brouard  8594:       TvarVind[ncovv]=k; /* TvarVind[2]=2  TvarVind[3]=3 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Any time varying singele */
1.231     brouard  8595:       TvarVD[ntveff]=Tvar[k]; /* TvarVD[1]=V4  TvarVD[2]=V3 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple time varying dummy variable */
                   8596:       TvarVDind[ntveff]=k; /* TvarVDind[1]=2 TvarVDind[2]=3 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple time varying dummy variable */
1.228     brouard  8597:       printf("Quasi Tmodelind[%d]=%d,Tvar[Tmodelind[%d]]=V%d, ncovcol=%d, nqv=%d,Tvar[k]- ncovcol-nqv=%d\n",ntveff,k,ntveff,Tvar[k], ncovcol, nqv,Tvar[k]- ncovcol-nqv);
                   8598:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  8599:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.234     brouard  8600:       Fixed[k]= 1;
                   8601:       Dummy[k]= 1;
                   8602:       nqtveff++;
                   8603:       modell[k].maintype= VTYPE;
                   8604:       modell[k].subtype= VQ;
                   8605:       ncovv++; /* Only simple time varying variables */
                   8606:       nsq++;
                   8607:       TvarsQ[nsq]=Tvar[k];
                   8608:       TvarsQind[nsq]=k;
                   8609:       TvarV[ncovv]=Tvar[k];
1.242     brouard  8610:       TvarVind[ncovv]=k; /* TvarVind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Any time varying singele */
1.231     brouard  8611:       TvarVQ[nqtveff]=Tvar[k]; /* TvarVQ[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple time varying quantitative variable */
                   8612:       TvarVQind[nqtveff]=k; /* TvarVQind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple time varying quantitative variable */
1.234     brouard  8613:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   8614:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
                   8615:       printf("Quasi TmodelQind[%d]=%d,Tvar[TmodelQind[%d]]=V%d, ncovcol=%d, nqv=%d, ntv=%d,Tvar[k]- ncovcol-nqv-ntv=%d\n",nqtveff,k,nqtveff,Tvar[k], ncovcol, nqv, ntv, Tvar[k]- ncovcol-nqv-ntv);
1.228     brouard  8616:       printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv);
1.227     brouard  8617:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  8618:       ncova++;
                   8619:       TvarA[ncova]=Tvar[k];
                   8620:       TvarAind[ncova]=k;
1.231     brouard  8621:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  8622:        Fixed[k]= 2;
                   8623:        Dummy[k]= 2;
                   8624:        modell[k].maintype= ATYPE;
                   8625:        modell[k].subtype= APFD;
                   8626:        /* ncoveff++; */
1.227     brouard  8627:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  8628:        Fixed[k]= 2;
                   8629:        Dummy[k]= 3;
                   8630:        modell[k].maintype= ATYPE;
                   8631:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
                   8632:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  8633:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  8634:        Fixed[k]= 3;
                   8635:        Dummy[k]= 2;
                   8636:        modell[k].maintype= ATYPE;
                   8637:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
                   8638:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  8639:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  8640:        Fixed[k]= 3;
                   8641:        Dummy[k]= 3;
                   8642:        modell[k].maintype= ATYPE;
                   8643:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
                   8644:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  8645:       }
                   8646:     }else if (Typevar[k] == 2) {  /* product without age */
                   8647:       k1=Tposprod[k];
                   8648:       if(Tvard[k1][1] <=ncovcol){
1.240     brouard  8649:        if(Tvard[k1][2] <=ncovcol){
                   8650:          Fixed[k]= 1;
                   8651:          Dummy[k]= 0;
                   8652:          modell[k].maintype= FTYPE;
                   8653:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
                   8654:          ncovf++; /* Fixed variables without age */
                   8655:          TvarF[ncovf]=Tvar[k];
                   8656:          TvarFind[ncovf]=k;
                   8657:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   8658:          Fixed[k]= 0;  /* or 2 ?*/
                   8659:          Dummy[k]= 1;
                   8660:          modell[k].maintype= FTYPE;
                   8661:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
                   8662:          ncovf++; /* Varying variables without age */
                   8663:          TvarF[ncovf]=Tvar[k];
                   8664:          TvarFind[ncovf]=k;
                   8665:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   8666:          Fixed[k]= 1;
                   8667:          Dummy[k]= 0;
                   8668:          modell[k].maintype= VTYPE;
                   8669:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
                   8670:          ncovv++; /* Varying variables without age */
                   8671:          TvarV[ncovv]=Tvar[k];
                   8672:          TvarVind[ncovv]=k;
                   8673:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   8674:          Fixed[k]= 1;
                   8675:          Dummy[k]= 1;
                   8676:          modell[k].maintype= VTYPE;
                   8677:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
                   8678:          ncovv++; /* Varying variables without age */
                   8679:          TvarV[ncovv]=Tvar[k];
                   8680:          TvarVind[ncovv]=k;
                   8681:        }
1.227     brouard  8682:       }else if(Tvard[k1][1] <=ncovcol+nqv){
1.240     brouard  8683:        if(Tvard[k1][2] <=ncovcol){
                   8684:          Fixed[k]= 0;  /* or 2 ?*/
                   8685:          Dummy[k]= 1;
                   8686:          modell[k].maintype= FTYPE;
                   8687:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
                   8688:          ncovf++; /* Fixed variables without age */
                   8689:          TvarF[ncovf]=Tvar[k];
                   8690:          TvarFind[ncovf]=k;
                   8691:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   8692:          Fixed[k]= 1;
                   8693:          Dummy[k]= 1;
                   8694:          modell[k].maintype= VTYPE;
                   8695:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
                   8696:          ncovv++; /* Varying variables without age */
                   8697:          TvarV[ncovv]=Tvar[k];
                   8698:          TvarVind[ncovv]=k;
                   8699:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   8700:          Fixed[k]= 1;
                   8701:          Dummy[k]= 1;
                   8702:          modell[k].maintype= VTYPE;
                   8703:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
                   8704:          ncovv++; /* Varying variables without age */
                   8705:          TvarV[ncovv]=Tvar[k];
                   8706:          TvarVind[ncovv]=k;
                   8707:          ncovv++; /* Varying variables without age */
                   8708:          TvarV[ncovv]=Tvar[k];
                   8709:          TvarVind[ncovv]=k;
                   8710:        }
1.227     brouard  8711:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){
1.240     brouard  8712:        if(Tvard[k1][2] <=ncovcol){
                   8713:          Fixed[k]= 1;
                   8714:          Dummy[k]= 1;
                   8715:          modell[k].maintype= VTYPE;
                   8716:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
                   8717:          ncovv++; /* Varying variables without age */
                   8718:          TvarV[ncovv]=Tvar[k];
                   8719:          TvarVind[ncovv]=k;
                   8720:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   8721:          Fixed[k]= 1;
                   8722:          Dummy[k]= 1;
                   8723:          modell[k].maintype= VTYPE;
                   8724:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
                   8725:          ncovv++; /* Varying variables without age */
                   8726:          TvarV[ncovv]=Tvar[k];
                   8727:          TvarVind[ncovv]=k;
                   8728:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   8729:          Fixed[k]= 1;
                   8730:          Dummy[k]= 0;
                   8731:          modell[k].maintype= VTYPE;
                   8732:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
                   8733:          ncovv++; /* Varying variables without age */
                   8734:          TvarV[ncovv]=Tvar[k];
                   8735:          TvarVind[ncovv]=k;
                   8736:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   8737:          Fixed[k]= 1;
                   8738:          Dummy[k]= 1;
                   8739:          modell[k].maintype= VTYPE;
                   8740:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
                   8741:          ncovv++; /* Varying variables without age */
                   8742:          TvarV[ncovv]=Tvar[k];
                   8743:          TvarVind[ncovv]=k;
                   8744:        }
1.227     brouard  8745:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  8746:        if(Tvard[k1][2] <=ncovcol){
                   8747:          Fixed[k]= 1;
                   8748:          Dummy[k]= 1;
                   8749:          modell[k].maintype= VTYPE;
                   8750:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
                   8751:          ncovv++; /* Varying variables without age */
                   8752:          TvarV[ncovv]=Tvar[k];
                   8753:          TvarVind[ncovv]=k;
                   8754:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   8755:          Fixed[k]= 1;
                   8756:          Dummy[k]= 1;
                   8757:          modell[k].maintype= VTYPE;
                   8758:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
                   8759:          ncovv++; /* Varying variables without age */
                   8760:          TvarV[ncovv]=Tvar[k];
                   8761:          TvarVind[ncovv]=k;
                   8762:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   8763:          Fixed[k]= 1;
                   8764:          Dummy[k]= 1;
                   8765:          modell[k].maintype= VTYPE;
                   8766:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
                   8767:          ncovv++; /* Varying variables without age */
                   8768:          TvarV[ncovv]=Tvar[k];
                   8769:          TvarVind[ncovv]=k;
                   8770:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   8771:          Fixed[k]= 1;
                   8772:          Dummy[k]= 1;
                   8773:          modell[k].maintype= VTYPE;
                   8774:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
                   8775:          ncovv++; /* Varying variables without age */
                   8776:          TvarV[ncovv]=Tvar[k];
                   8777:          TvarVind[ncovv]=k;
                   8778:        }
1.227     brouard  8779:       }else{
1.240     brouard  8780:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   8781:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   8782:       } /*end k1*/
1.225     brouard  8783:     }else{
1.226     brouard  8784:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   8785:       fprintf(ficlog,"Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
1.225     brouard  8786:     }
1.227     brouard  8787:     printf("Decodemodel, k=%d, Tvar[%d]=V%d,Typevar=%d, Fixed=%d, Dummy=%d\n",k, k,Tvar[k],Typevar[k],Fixed[k],Dummy[k]);
1.231     brouard  8788:     printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype);
1.227     brouard  8789:     fprintf(ficlog,"Decodemodel, k=%d, Tvar[%d]=V%d,Typevar=%d, Fixed=%d, Dummy=%d\n",k, k,Tvar[k],Typevar[k],Fixed[k],Dummy[k]);
                   8790:   }
                   8791:   /* Searching for doublons in the model */
                   8792:   for(k1=1; k1<= cptcovt;k1++){
                   8793:     for(k2=1; k2 <k1;k2++){
                   8794:       if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){
1.234     brouard  8795:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   8796:          if(Tvar[k1]==Tvar[k2]){
                   8797:            printf("Error duplication in the model=%s at positions (+) %d and %d, Tvar[%d]=V%d, Tvar[%d]=V%d, Typevar=%d, Fixed=%d, Dummy=%d\n", model, k1,k2, k1, Tvar[k1], k2, Tvar[k2],Typevar[k1],Fixed[Tvar[k1]],Dummy[Tvar[k1]]);
                   8798:            fprintf(ficlog,"Error duplication in the model=%s at positions (+) %d and %d, Tvar[%d]=V%d, Tvar[%d]=V%d, Typevar=%d, Fixed=%d, Dummy=%d\n", model, k1,k2, k1, Tvar[k1], k2, Tvar[k2],Typevar[k1],Fixed[Tvar[k1]],Dummy[Tvar[k1]]); fflush(ficlog);
                   8799:            return(1);
                   8800:          }
                   8801:        }else if (Typevar[k1] ==2){
                   8802:          k3=Tposprod[k1];
                   8803:          k4=Tposprod[k2];
                   8804:          if( ((Tvard[k3][1]== Tvard[k4][1])&&(Tvard[k3][2]== Tvard[k4][2])) || ((Tvard[k3][1]== Tvard[k4][2])&&(Tvard[k3][2]== Tvard[k4][1])) ){
                   8805:            printf("Error duplication in the model=%s at positions (+) %d and %d, V%d*V%d, Typevar=%d, Fixed=%d, Dummy=%d\n",model, k1,k2, Tvard[k3][1], Tvard[k3][2],Typevar[k1],Fixed[Tvar[k1]],Dummy[Tvar[k1]]);
                   8806:            fprintf(ficlog,"Error duplication in the model=%s at positions (+) %d and %d, V%d*V%d, Typevar=%d, Fixed=%d, Dummy=%d\n",model, k1,k2, Tvard[k3][1], Tvard[k3][2],Typevar[k1],Fixed[Tvar[k1]],Dummy[Tvar[k1]]); fflush(ficlog);
                   8807:            return(1);
                   8808:          }
                   8809:        }
1.227     brouard  8810:       }
                   8811:     }
1.225     brouard  8812:   }
                   8813:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   8814:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  8815:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   8816:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.137     brouard  8817:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  8818:   /*endread:*/
1.225     brouard  8819:   printf("Exiting decodemodel: ");
                   8820:   return (1);
1.136     brouard  8821: }
                   8822: 
1.169     brouard  8823: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136     brouard  8824: {
                   8825:   int i, m;
1.218     brouard  8826:   int firstone=0;
                   8827:   
1.136     brouard  8828:   for (i=1; i<=imx; i++) {
                   8829:     for(m=2; (m<= maxwav); m++) {
                   8830:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   8831:        anint[m][i]=9999;
1.216     brouard  8832:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   8833:          s[m][i]=-1;
1.136     brouard  8834:       }
                   8835:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169     brouard  8836:        *nberr = *nberr + 1;
1.218     brouard  8837:        if(firstone == 0){
                   8838:          firstone=1;
                   8839:        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 can be biased (%d) because status is a death state %d at wave %d. Wave dropped.\nOther similar cases in log file\n",(int)moisdc[i],(int)andc[i],num[i],i, *nberr,s[m][i],m);
                   8840:        }
                   8841:        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 can be biased (%d) because status is a death state %d at wave %d. Wave dropped.\n",(int)moisdc[i],(int)andc[i],num[i],i, *nberr,s[m][i],m);
1.136     brouard  8842:        s[m][i]=-1;
                   8843:       }
                   8844:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  8845:        (*nberr)++;
1.136     brouard  8846:        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]); 
                   8847:        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]); 
                   8848:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   8849:       }
                   8850:     }
                   8851:   }
                   8852: 
                   8853:   for (i=1; i<=imx; i++)  {
                   8854:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   8855:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  8856:       if(s[m][i] >0  || s[m][i]==-1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){ /* What if s[m][i]=-1 */
1.136     brouard  8857:        if (s[m][i] >= nlstate+1) {
1.169     brouard  8858:          if(agedc[i]>0){
                   8859:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  8860:              agev[m][i]=agedc[i];
1.214     brouard  8861:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  8862:            }else {
1.136     brouard  8863:              if ((int)andc[i]!=9999){
                   8864:                nbwarn++;
                   8865:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   8866:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   8867:                agev[m][i]=-1;
                   8868:              }
                   8869:            }
1.169     brouard  8870:          } /* agedc > 0 */
1.214     brouard  8871:        } /* end if */
1.136     brouard  8872:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   8873:                                 years but with the precision of a month */
                   8874:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   8875:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   8876:            agev[m][i]=1;
                   8877:          else if(agev[m][i] < *agemin){ 
                   8878:            *agemin=agev[m][i];
                   8879:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   8880:          }
                   8881:          else if(agev[m][i] >*agemax){
                   8882:            *agemax=agev[m][i];
1.156     brouard  8883:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  8884:          }
                   8885:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   8886:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  8887:        } /* en if 9*/
1.136     brouard  8888:        else { /* =9 */
1.214     brouard  8889:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  8890:          agev[m][i]=1;
                   8891:          s[m][i]=-1;
                   8892:        }
                   8893:       }
1.214     brouard  8894:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  8895:        agev[m][i]=1;
1.214     brouard  8896:       else{
                   8897:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   8898:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   8899:        agev[m][i]=0;
                   8900:       }
                   8901:     } /* End for lastpass */
                   8902:   }
1.136     brouard  8903:     
                   8904:   for (i=1; i<=imx; i++)  {
                   8905:     for(m=firstpass; (m<=lastpass); m++){
                   8906:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  8907:        (*nberr)++;
1.136     brouard  8908:        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);     
                   8909:        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);     
                   8910:        return 1;
                   8911:       }
                   8912:     }
                   8913:   }
                   8914: 
                   8915:   /*for (i=1; i<=imx; i++){
                   8916:   for (m=firstpass; (m<lastpass); m++){
                   8917:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   8918: }
                   8919: 
                   8920: }*/
                   8921: 
                   8922: 
1.139     brouard  8923:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   8924:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  8925: 
                   8926:   return (0);
1.164     brouard  8927:  /* endread:*/
1.136     brouard  8928:     printf("Exiting calandcheckages: ");
                   8929:     return (1);
                   8930: }
                   8931: 
1.172     brouard  8932: #if defined(_MSC_VER)
                   8933: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   8934: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   8935: //#include "stdafx.h"
                   8936: //#include <stdio.h>
                   8937: //#include <tchar.h>
                   8938: //#include <windows.h>
                   8939: //#include <iostream>
                   8940: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   8941: 
                   8942: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   8943: 
                   8944: BOOL IsWow64()
                   8945: {
                   8946:        BOOL bIsWow64 = FALSE;
                   8947: 
                   8948:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   8949:        //  (HANDLE, PBOOL);
                   8950: 
                   8951:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   8952: 
                   8953:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   8954:        const char funcName[] = "IsWow64Process";
                   8955:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   8956:                GetProcAddress(module, funcName);
                   8957: 
                   8958:        if (NULL != fnIsWow64Process)
                   8959:        {
                   8960:                if (!fnIsWow64Process(GetCurrentProcess(),
                   8961:                        &bIsWow64))
                   8962:                        //throw std::exception("Unknown error");
                   8963:                        printf("Unknown error\n");
                   8964:        }
                   8965:        return bIsWow64 != FALSE;
                   8966: }
                   8967: #endif
1.177     brouard  8968: 
1.191     brouard  8969: void syscompilerinfo(int logged)
1.167     brouard  8970:  {
                   8971:    /* #include "syscompilerinfo.h"*/
1.185     brouard  8972:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   8973:    /* /GS /W3 /Gy
                   8974:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   8975:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   8976:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  8977:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   8978:    */ 
                   8979:    /* 64 bits */
1.185     brouard  8980:    /*
                   8981:      /GS /W3 /Gy
                   8982:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   8983:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   8984:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   8985:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   8986:    /* Optimization are useless and O3 is slower than O2 */
                   8987:    /*
                   8988:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   8989:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   8990:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   8991:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   8992:    */
1.186     brouard  8993:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  8994:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   8995:       /PDB:"visual studio
                   8996:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   8997:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   8998:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   8999:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   9000:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   9001:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   9002:       uiAccess='false'"
                   9003:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   9004:       /NOLOGO /TLBID:1
                   9005:    */
1.177     brouard  9006: #if defined __INTEL_COMPILER
1.178     brouard  9007: #if defined(__GNUC__)
                   9008:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   9009: #endif
1.177     brouard  9010: #elif defined(__GNUC__) 
1.179     brouard  9011: #ifndef  __APPLE__
1.174     brouard  9012: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  9013: #endif
1.177     brouard  9014:    struct utsname sysInfo;
1.178     brouard  9015:    int cross = CROSS;
                   9016:    if (cross){
                   9017:           printf("Cross-");
1.191     brouard  9018:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  9019:    }
1.174     brouard  9020: #endif
                   9021: 
1.171     brouard  9022: #include <stdint.h>
1.178     brouard  9023: 
1.191     brouard  9024:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  9025: #if defined(__clang__)
1.191     brouard  9026:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  9027: #endif
                   9028: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  9029:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  9030: #endif
                   9031: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  9032:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  9033: #endif
                   9034: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  9035:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  9036: #endif
                   9037: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  9038:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  9039: #endif
                   9040: #if defined(_MSC_VER)
1.191     brouard  9041:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  9042: #endif
                   9043: #if defined(__PGI)
1.191     brouard  9044:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  9045: #endif
                   9046: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  9047:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  9048: #endif
1.191     brouard  9049:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  9050:    
1.167     brouard  9051: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   9052: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   9053:     // Windows (x64 and x86)
1.191     brouard  9054:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  9055: #elif __unix__ // all unices, not all compilers
                   9056:     // Unix
1.191     brouard  9057:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  9058: #elif __linux__
                   9059:     // linux
1.191     brouard  9060:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  9061: #elif __APPLE__
1.174     brouard  9062:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  9063:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  9064: #endif
                   9065: 
                   9066: /*  __MINGW32__          */
                   9067: /*  __CYGWIN__  */
                   9068: /* __MINGW64__  */
                   9069: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   9070: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   9071: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   9072: /* _WIN64  // Defined for applications for Win64. */
                   9073: /* _M_X64 // Defined for compilations that target x64 processors. */
                   9074: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  9075: 
1.167     brouard  9076: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  9077:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  9078: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  9079:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  9080: #else
1.191     brouard  9081:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  9082: #endif
                   9083: 
1.169     brouard  9084: #if defined(__GNUC__)
                   9085: # if defined(__GNUC_PATCHLEVEL__)
                   9086: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   9087:                             + __GNUC_MINOR__ * 100 \
                   9088:                             + __GNUC_PATCHLEVEL__)
                   9089: # else
                   9090: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   9091:                             + __GNUC_MINOR__ * 100)
                   9092: # endif
1.174     brouard  9093:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  9094:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  9095: 
                   9096:    if (uname(&sysInfo) != -1) {
                   9097:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  9098:         if(logged) fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.176     brouard  9099:    }
                   9100:    else
                   9101:       perror("uname() error");
1.179     brouard  9102:    //#ifndef __INTEL_COMPILER 
                   9103: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  9104:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  9105:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  9106: #endif
1.169     brouard  9107: #endif
1.172     brouard  9108: 
                   9109:    //   void main()
                   9110:    //   {
1.169     brouard  9111: #if defined(_MSC_VER)
1.174     brouard  9112:    if (IsWow64()){
1.191     brouard  9113:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   9114:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  9115:    }
                   9116:    else{
1.191     brouard  9117:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   9118:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  9119:    }
1.172     brouard  9120:    //     printf("\nPress Enter to continue...");
                   9121:    //     getchar();
                   9122:    //   }
                   9123: 
1.169     brouard  9124: #endif
                   9125:    
1.167     brouard  9126: 
1.219     brouard  9127: }
1.136     brouard  9128: 
1.219     brouard  9129: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.180     brouard  9130:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.235     brouard  9131:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  9132:   /* double ftolpl = 1.e-10; */
1.180     brouard  9133:   double age, agebase, agelim;
1.203     brouard  9134:   double tot;
1.180     brouard  9135: 
1.202     brouard  9136:   strcpy(filerespl,"PL_");
                   9137:   strcat(filerespl,fileresu);
                   9138:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
                   9139:     printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   9140:     fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   9141:   }
1.227     brouard  9142:   printf("\nComputing period (stable) prevalence: result on file '%s' \n", filerespl);
                   9143:   fprintf(ficlog,"\nComputing period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  9144:   pstamp(ficrespl);
1.203     brouard  9145:   fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  9146:   fprintf(ficrespl,"#Age ");
                   9147:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   9148:   fprintf(ficrespl,"\n");
1.180     brouard  9149:   
1.219     brouard  9150:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  9151: 
1.219     brouard  9152:   agebase=ageminpar;
                   9153:   agelim=agemaxpar;
1.180     brouard  9154: 
1.227     brouard  9155:   /* i1=pow(2,ncoveff); */
1.234     brouard  9156:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  9157:   if (cptcovn < 1){i1=1;}
1.180     brouard  9158: 
1.238     brouard  9159:   for(k=1; k<=i1;k++){ /* For each combination k of dummy covariates in the model */
                   9160:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9161:       if(TKresult[nres]!= k)
                   9162:        continue;
1.235     brouard  9163: 
1.238     brouard  9164:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   9165:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   9166:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   9167:       /* k=k+1; */
                   9168:       /* to clean */
                   9169:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   9170:       fprintf(ficrespl,"#******");
                   9171:       printf("#******");
                   9172:       fprintf(ficlog,"#******");
                   9173:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
                   9174:        fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); /* Here problem for varying dummy*/
                   9175:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9176:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9177:       }
                   9178:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   9179:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9180:        fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9181:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9182:       }
                   9183:       fprintf(ficrespl,"******\n");
                   9184:       printf("******\n");
                   9185:       fprintf(ficlog,"******\n");
                   9186:       if(invalidvarcomb[k]){
                   9187:        printf("\nCombination (%d) ignored because no case \n",k); 
                   9188:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   9189:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   9190:        continue;
                   9191:       }
1.219     brouard  9192: 
1.238     brouard  9193:       fprintf(ficrespl,"#Age ");
                   9194:       for(j=1;j<=cptcoveff;j++) {
                   9195:        fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9196:       }
                   9197:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   9198:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  9199:     
1.238     brouard  9200:       for (age=agebase; age<=agelim; age++){
                   9201:        /* for (age=agebase; age<=agebase; age++){ */
                   9202:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres);
                   9203:        fprintf(ficrespl,"%.0f ",age );
                   9204:        for(j=1;j<=cptcoveff;j++)
                   9205:          fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9206:        tot=0.;
                   9207:        for(i=1; i<=nlstate;i++){
                   9208:          tot +=  prlim[i][i];
                   9209:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   9210:        }
                   9211:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   9212:       } /* Age */
                   9213:       /* was end of cptcod */
                   9214:     } /* cptcov */
                   9215:   } /* nres */
1.219     brouard  9216:   return 0;
1.180     brouard  9217: }
                   9218: 
1.218     brouard  9219: int back_prevalence_limit(double *p, double **bprlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp, double dateprev1,double dateprev2, int firstpass, int lastpass, int mobilavproj){
                   9220:        /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   9221:        
                   9222:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   9223:    * at any age between ageminpar and agemaxpar
                   9224:         */
1.235     brouard  9225:   int i, j, k, i1, nres=0 ;
1.217     brouard  9226:   /* double ftolpl = 1.e-10; */
                   9227:   double age, agebase, agelim;
                   9228:   double tot;
1.218     brouard  9229:   /* double ***mobaverage; */
                   9230:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  9231: 
                   9232:   strcpy(fileresplb,"PLB_");
                   9233:   strcat(fileresplb,fileresu);
                   9234:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
                   9235:     printf("Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
                   9236:     fprintf(ficlog,"Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
                   9237:   }
                   9238:   printf("Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
                   9239:   fprintf(ficlog,"Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
                   9240:   pstamp(ficresplb);
                   9241:   fprintf(ficresplb,"# Period (stable) back prevalence. Precision given by ftolpl=%g \n", ftolpl);
                   9242:   fprintf(ficresplb,"#Age ");
                   9243:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   9244:   fprintf(ficresplb,"\n");
                   9245:   
1.218     brouard  9246:   
                   9247:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   9248:   
                   9249:   agebase=ageminpar;
                   9250:   agelim=agemaxpar;
                   9251:   
                   9252:   
1.227     brouard  9253:   i1=pow(2,cptcoveff);
1.218     brouard  9254:   if (cptcovn < 1){i1=1;}
1.227     brouard  9255:   
1.238     brouard  9256:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9257:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
                   9258:       if(TKresult[nres]!= k)
                   9259:        continue;
                   9260:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   9261:       fprintf(ficresplb,"#******");
                   9262:       printf("#******");
                   9263:       fprintf(ficlog,"#******");
                   9264:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
                   9265:        fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9266:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9267:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9268:       }
                   9269:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   9270:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9271:        fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9272:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9273:       }
                   9274:       fprintf(ficresplb,"******\n");
                   9275:       printf("******\n");
                   9276:       fprintf(ficlog,"******\n");
                   9277:       if(invalidvarcomb[k]){
                   9278:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   9279:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   9280:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   9281:        continue;
                   9282:       }
1.218     brouard  9283:     
1.238     brouard  9284:       fprintf(ficresplb,"#Age ");
                   9285:       for(j=1;j<=cptcoveff;j++) {
                   9286:        fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9287:       }
                   9288:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   9289:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  9290:     
                   9291:     
1.238     brouard  9292:       for (age=agebase; age<=agelim; age++){
                   9293:        /* for (age=agebase; age<=agebase; age++){ */
                   9294:        if(mobilavproj > 0){
                   9295:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   9296:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  9297:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  9298:        }else if (mobilavproj == 0){
                   9299:          printf("There is no chance to get back prevalence limit if data aren't non zero and summing to 1, please try a non null mobil_average(=%d) parameter or mobil_average=-1 if you want to try at your own risk.\n",mobilavproj);
                   9300:          fprintf(ficlog,"There is no chance to get back prevalence limit if data aren't non zero and summing to 1, please try a non null mobil_average(=%d) parameter or mobil_average=-1 if you want to try at your own risk.\n",mobilavproj);
                   9301:          exit(1);
                   9302:        }else{
                   9303:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  9304:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.238     brouard  9305:        }
                   9306:        fprintf(ficresplb,"%.0f ",age );
                   9307:        for(j=1;j<=cptcoveff;j++)
                   9308:          fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9309:        tot=0.;
                   9310:        for(i=1; i<=nlstate;i++){
                   9311:          tot +=  bprlim[i][i];
                   9312:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   9313:        }
                   9314:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   9315:       } /* Age */
                   9316:       /* was end of cptcod */
                   9317:     } /* end of any combination */
                   9318:   } /* end of nres */  
1.218     brouard  9319:   /* hBijx(p, bage, fage); */
                   9320:   /* fclose(ficrespijb); */
                   9321:   
                   9322:   return 0;
1.217     brouard  9323: }
1.218     brouard  9324:  
1.180     brouard  9325: int hPijx(double *p, int bage, int fage){
                   9326:     /*------------- h Pij x at various ages ------------*/
                   9327: 
                   9328:   int stepsize;
                   9329:   int agelim;
                   9330:   int hstepm;
                   9331:   int nhstepm;
1.235     brouard  9332:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  9333: 
                   9334:   double agedeb;
                   9335:   double ***p3mat;
                   9336: 
1.201     brouard  9337:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  9338:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   9339:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   9340:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   9341:     }
                   9342:     printf("Computing pij: result on file '%s' \n", filerespij);
                   9343:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   9344:   
                   9345:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9346:     /*if (stepm<=24) stepsize=2;*/
                   9347: 
                   9348:     agelim=AGESUP;
                   9349:     hstepm=stepsize*YEARM; /* Every year of age */
                   9350:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
1.218     brouard  9351:                
1.180     brouard  9352:     /* hstepm=1;   aff par mois*/
                   9353:     pstamp(ficrespij);
                   9354:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
1.227     brouard  9355:     i1= pow(2,cptcoveff);
1.218     brouard  9356:                /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   9357:                /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   9358:                /*      k=k+1;  */
1.235     brouard  9359:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9360:     for(k=1; k<=i1;k++){
                   9361:       if(TKresult[nres]!= k)
                   9362:        continue;
1.183     brouard  9363:       fprintf(ficrespij,"\n#****** ");
1.227     brouard  9364:       for(j=1;j<=cptcoveff;j++) 
1.198     brouard  9365:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  9366:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   9367:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9368:        fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9369:       }
1.183     brouard  9370:       fprintf(ficrespij,"******\n");
                   9371:       
                   9372:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   9373:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   9374:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   9375:        
                   9376:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  9377:        
1.183     brouard  9378:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9379:        oldm=oldms;savm=savms;
1.235     brouard  9380:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
1.183     brouard  9381:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   9382:        for(i=1; i<=nlstate;i++)
                   9383:          for(j=1; j<=nlstate+ndeath;j++)
                   9384:            fprintf(ficrespij," %1d-%1d",i,j);
                   9385:        fprintf(ficrespij,"\n");
                   9386:        for (h=0; h<=nhstepm; h++){
                   9387:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   9388:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  9389:          for(i=1; i<=nlstate;i++)
                   9390:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  9391:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  9392:          fprintf(ficrespij,"\n");
                   9393:        }
1.183     brouard  9394:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9395:        fprintf(ficrespij,"\n");
                   9396:       }
1.180     brouard  9397:       /*}*/
                   9398:     }
1.218     brouard  9399:     return 0;
1.180     brouard  9400: }
1.218     brouard  9401:  
                   9402:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  9403:     /*------------- h Bij x at various ages ------------*/
                   9404: 
                   9405:   int stepsize;
1.218     brouard  9406:   /* int agelim; */
                   9407:        int ageminl;
1.217     brouard  9408:   int hstepm;
                   9409:   int nhstepm;
1.238     brouard  9410:   int h, i, i1, j, k, nres;
1.218     brouard  9411:        
1.217     brouard  9412:   double agedeb;
                   9413:   double ***p3mat;
1.218     brouard  9414:        
                   9415:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   9416:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   9417:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   9418:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   9419:   }
                   9420:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   9421:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   9422:   
                   9423:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9424:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  9425:   
1.218     brouard  9426:   /* agelim=AGESUP; */
                   9427:   ageminl=30;
                   9428:   hstepm=stepsize*YEARM; /* Every year of age */
                   9429:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   9430:   
                   9431:   /* hstepm=1;   aff par mois*/
                   9432:   pstamp(ficrespijb);
                   9433:   fprintf(ficrespijb,"#****** h Pij x Back Probability to be in state i at age x-h being in j at x ");
1.227     brouard  9434:   i1= pow(2,cptcoveff);
1.218     brouard  9435:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   9436:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   9437:   /*   k=k+1;  */
1.238     brouard  9438:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9439:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
                   9440:       if(TKresult[nres]!= k)
                   9441:        continue;
                   9442:       fprintf(ficrespijb,"\n#****** ");
                   9443:       for(j=1;j<=cptcoveff;j++)
                   9444:        fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9445:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   9446:        fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9447:       }
                   9448:       fprintf(ficrespijb,"******\n");
                   9449:       if(invalidvarcomb[k]){
                   9450:        fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   9451:        continue;
                   9452:       }
                   9453:       
                   9454:       /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   9455:       for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   9456:        /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   9457:        nhstepm=(int) rint((agedeb-ageminl)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
                   9458:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 */
                   9459:        
                   9460:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
                   9461:        
                   9462:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9463:        /* oldm=oldms;savm=savms; */
                   9464:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   9465:        hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k);
                   9466:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
                   9467:        fprintf(ficrespijb,"# Cov Agex agex-h hpijx with i,j=");
1.217     brouard  9468:        for(i=1; i<=nlstate;i++)
                   9469:          for(j=1; j<=nlstate+ndeath;j++)
1.238     brouard  9470:            fprintf(ficrespijb," %1d-%1d",i,j);
1.217     brouard  9471:        fprintf(ficrespijb,"\n");
1.238     brouard  9472:        for (h=0; h<=nhstepm; h++){
                   9473:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   9474:          fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   9475:          /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
                   9476:          for(i=1; i<=nlstate;i++)
                   9477:            for(j=1; j<=nlstate+ndeath;j++)
                   9478:              fprintf(ficrespijb," %.5f", p3mat[i][j][h]);
                   9479:          fprintf(ficrespijb,"\n");
                   9480:        }
                   9481:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9482:        fprintf(ficrespijb,"\n");
                   9483:       } /* end age deb */
                   9484:     } /* end combination */
                   9485:   } /* end nres */
1.218     brouard  9486:   return 0;
                   9487:  } /*  hBijx */
1.217     brouard  9488: 
1.180     brouard  9489: 
1.136     brouard  9490: /***********************************************/
                   9491: /**************** Main Program *****************/
                   9492: /***********************************************/
                   9493: 
                   9494: int main(int argc, char *argv[])
                   9495: {
                   9496: #ifdef GSL
                   9497:   const gsl_multimin_fminimizer_type *T;
                   9498:   size_t iteri = 0, it;
                   9499:   int rval = GSL_CONTINUE;
                   9500:   int status = GSL_SUCCESS;
                   9501:   double ssval;
                   9502: #endif
                   9503:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164     brouard  9504:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
1.209     brouard  9505:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  9506:   int jj, ll, li, lj, lk;
1.136     brouard  9507:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  9508:   int num_filled;
1.136     brouard  9509:   int itimes;
                   9510:   int NDIM=2;
                   9511:   int vpopbased=0;
1.235     brouard  9512:   int nres=0;
1.136     brouard  9513: 
1.164     brouard  9514:   char ca[32], cb[32];
1.136     brouard  9515:   /*  FILE *fichtm; *//* Html File */
                   9516:   /* FILE *ficgp;*/ /*Gnuplot File */
                   9517:   struct stat info;
1.191     brouard  9518:   double agedeb=0.;
1.194     brouard  9519: 
                   9520:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  9521:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  9522: 
1.165     brouard  9523:   double fret;
1.191     brouard  9524:   double dum=0.; /* Dummy variable */
1.136     brouard  9525:   double ***p3mat;
1.218     brouard  9526:   /* double ***mobaverage; */
1.164     brouard  9527: 
                   9528:   char line[MAXLINE];
1.197     brouard  9529:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   9530: 
1.234     brouard  9531:   char  modeltemp[MAXLINE];
1.230     brouard  9532:   char resultline[MAXLINE];
                   9533:   
1.136     brouard  9534:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  9535:   char *tok, *val; /* pathtot */
1.136     brouard  9536:   int firstobs=1, lastobs=10;
1.195     brouard  9537:   int c,  h , cpt, c2;
1.191     brouard  9538:   int jl=0;
                   9539:   int i1, j1, jk, stepsize=0;
1.194     brouard  9540:   int count=0;
                   9541: 
1.164     brouard  9542:   int *tab; 
1.136     brouard  9543:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.217     brouard  9544:   int backcast=0;
1.136     brouard  9545:   int mobilav=0,popforecast=0;
1.191     brouard  9546:   int hstepm=0, nhstepm=0;
1.136     brouard  9547:   int agemortsup;
                   9548:   float  sumlpop=0.;
                   9549:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   9550:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   9551: 
1.191     brouard  9552:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  9553:   double ftolpl=FTOL;
                   9554:   double **prlim;
1.217     brouard  9555:   double **bprlim;
1.136     brouard  9556:   double ***param; /* Matrix of parameters */
                   9557:   double  *p;
                   9558:   double **matcov; /* Matrix of covariance */
1.203     brouard  9559:   double **hess; /* Hessian matrix */
1.136     brouard  9560:   double ***delti3; /* Scale */
                   9561:   double *delti; /* Scale */
                   9562:   double ***eij, ***vareij;
                   9563:   double **varpl; /* Variances of prevalence limits by age */
                   9564:   double *epj, vepp;
1.164     brouard  9565: 
1.136     brouard  9566:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
1.217     brouard  9567:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000;
                   9568: 
1.136     brouard  9569:   double **ximort;
1.145     brouard  9570:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  9571:   int *dcwave;
                   9572: 
1.164     brouard  9573:   char z[1]="c";
1.136     brouard  9574: 
                   9575:   /*char  *strt;*/
                   9576:   char strtend[80];
1.126     brouard  9577: 
1.164     brouard  9578: 
1.126     brouard  9579: /*   setlocale (LC_ALL, ""); */
                   9580: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   9581: /*   textdomain (PACKAGE); */
                   9582: /*   setlocale (LC_CTYPE, ""); */
                   9583: /*   setlocale (LC_MESSAGES, ""); */
                   9584: 
                   9585:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  9586:   rstart_time = time(NULL);  
                   9587:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   9588:   start_time = *localtime(&rstart_time);
1.126     brouard  9589:   curr_time=start_time;
1.157     brouard  9590:   /*tml = *localtime(&start_time.tm_sec);*/
                   9591:   /* strcpy(strstart,asctime(&tml)); */
                   9592:   strcpy(strstart,asctime(&start_time));
1.126     brouard  9593: 
                   9594: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  9595: /*  tp.tm_sec = tp.tm_sec +86400; */
                   9596: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  9597: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   9598: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   9599: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  9600: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  9601: /*   strt=asctime(&tmg); */
                   9602: /*   printf("Time(after) =%s",strstart);  */
                   9603: /*  (void) time (&time_value);
                   9604: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   9605: *  tm = *localtime(&time_value);
                   9606: *  strstart=asctime(&tm);
                   9607: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   9608: */
                   9609: 
                   9610:   nberr=0; /* Number of errors and warnings */
                   9611:   nbwarn=0;
1.184     brouard  9612: #ifdef WIN32
                   9613:   _getcwd(pathcd, size);
                   9614: #else
1.126     brouard  9615:   getcwd(pathcd, size);
1.184     brouard  9616: #endif
1.191     brouard  9617:   syscompilerinfo(0);
1.196     brouard  9618:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  9619:   if(argc <=1){
                   9620:     printf("\nEnter the parameter file name: ");
1.205     brouard  9621:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   9622:       printf("ERROR Empty parameter file name\n");
                   9623:       goto end;
                   9624:     }
1.126     brouard  9625:     i=strlen(pathr);
                   9626:     if(pathr[i-1]=='\n')
                   9627:       pathr[i-1]='\0';
1.156     brouard  9628:     i=strlen(pathr);
1.205     brouard  9629:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  9630:       pathr[i-1]='\0';
1.205     brouard  9631:     }
                   9632:     i=strlen(pathr);
                   9633:     if( i==0 ){
                   9634:       printf("ERROR Empty parameter file name\n");
                   9635:       goto end;
                   9636:     }
                   9637:     for (tok = pathr; tok != NULL; ){
1.126     brouard  9638:       printf("Pathr |%s|\n",pathr);
                   9639:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   9640:       printf("val= |%s| pathr=%s\n",val,pathr);
                   9641:       strcpy (pathtot, val);
                   9642:       if(pathr[0] == '\0') break; /* Dirty */
                   9643:     }
                   9644:   }
                   9645:   else{
                   9646:     strcpy(pathtot,argv[1]);
                   9647:   }
                   9648:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   9649:   /*cygwin_split_path(pathtot,path,optionfile);
                   9650:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   9651:   /* cutv(path,optionfile,pathtot,'\\');*/
                   9652: 
                   9653:   /* Split argv[0], imach program to get pathimach */
                   9654:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   9655:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   9656:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   9657:  /*   strcpy(pathimach,argv[0]); */
                   9658:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   9659:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   9660:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  9661: #ifdef WIN32
                   9662:   _chdir(path); /* Can be a relative path */
                   9663:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   9664: #else
1.126     brouard  9665:   chdir(path); /* Can be a relative path */
1.184     brouard  9666:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   9667: #endif
                   9668:   printf("Current directory %s!\n",pathcd);
1.126     brouard  9669:   strcpy(command,"mkdir ");
                   9670:   strcat(command,optionfilefiname);
                   9671:   if((outcmd=system(command)) != 0){
1.169     brouard  9672:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  9673:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   9674:     /* fclose(ficlog); */
                   9675: /*     exit(1); */
                   9676:   }
                   9677: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   9678: /*     perror("mkdir"); */
                   9679: /*   } */
                   9680: 
                   9681:   /*-------- arguments in the command line --------*/
                   9682: 
1.186     brouard  9683:   /* Main Log file */
1.126     brouard  9684:   strcat(filelog, optionfilefiname);
                   9685:   strcat(filelog,".log");    /* */
                   9686:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   9687:     printf("Problem with logfile %s\n",filelog);
                   9688:     goto end;
                   9689:   }
                   9690:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  9691:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  9692:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   9693:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   9694:  path=%s \n\
                   9695:  optionfile=%s\n\
                   9696:  optionfilext=%s\n\
1.156     brouard  9697:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  9698: 
1.197     brouard  9699:   syscompilerinfo(1);
1.167     brouard  9700: 
1.126     brouard  9701:   printf("Local time (at start):%s",strstart);
                   9702:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   9703:   fflush(ficlog);
                   9704: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  9705: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  9706: 
                   9707:   /* */
                   9708:   strcpy(fileres,"r");
                   9709:   strcat(fileres, optionfilefiname);
1.201     brouard  9710:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  9711:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  9712:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  9713: 
1.186     brouard  9714:   /* Main ---------arguments file --------*/
1.126     brouard  9715: 
                   9716:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  9717:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   9718:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  9719:     fflush(ficlog);
1.149     brouard  9720:     /* goto end; */
                   9721:     exit(70); 
1.126     brouard  9722:   }
                   9723: 
                   9724: 
                   9725: 
                   9726:   strcpy(filereso,"o");
1.201     brouard  9727:   strcat(filereso,fileresu);
1.126     brouard  9728:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   9729:     printf("Problem with Output resultfile: %s\n", filereso);
                   9730:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   9731:     fflush(ficlog);
                   9732:     goto end;
                   9733:   }
                   9734: 
                   9735:   /* Reads comments: lines beginning with '#' */
                   9736:   numlinepar=0;
1.197     brouard  9737: 
                   9738:     /* First parameter line */
                   9739:   while(fgets(line, MAXLINE, ficpar)) {
                   9740:     /* If line starts with a # it is a comment */
                   9741:     if (line[0] == '#') {
                   9742:       numlinepar++;
                   9743:       fputs(line,stdout);
                   9744:       fputs(line,ficparo);
                   9745:       fputs(line,ficlog);
                   9746:       continue;
                   9747:     }else
                   9748:       break;
                   9749:   }
                   9750:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   9751:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   9752:     if (num_filled != 5) {
                   9753:       printf("Should be 5 parameters\n");
                   9754:     }
1.126     brouard  9755:     numlinepar++;
1.197     brouard  9756:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   9757:   }
                   9758:   /* Second parameter line */
                   9759:   while(fgets(line, MAXLINE, ficpar)) {
                   9760:     /* If line starts with a # it is a comment */
                   9761:     if (line[0] == '#') {
                   9762:       numlinepar++;
                   9763:       fputs(line,stdout);
                   9764:       fputs(line,ficparo);
                   9765:       fputs(line,ficlog);
                   9766:       continue;
                   9767:     }else
                   9768:       break;
                   9769:   }
1.223     brouard  9770:   if((num_filled=sscanf(line,"ftol=%lf stepm=%d ncovcol=%d nqv=%d ntv=%d nqtv=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", \
                   9771:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   9772:     if (num_filled != 11) {
                   9773:       printf("Not 11 parameters, for example:ftol=1.e-8 stepm=12 ncovcol=2 nqv=1 ntv=2 nqtv=1  nlstate=2 ndeath=1 maxwav=3 mle=1 weight=1\n");
1.209     brouard  9774:       printf("but line=%s\n",line);
1.197     brouard  9775:     }
1.223     brouard  9776:     printf("ftol=%e stepm=%d ncovcol=%d nqv=%d ntv=%d nqtv=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n",ftol, stepm, ncovcol, nqv, ntv, nqtv, nlstate, ndeath, maxwav, mle, weightopt);
1.126     brouard  9777:   }
1.203     brouard  9778:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  9779:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  9780:   /* Third parameter line */
                   9781:   while(fgets(line, MAXLINE, ficpar)) {
                   9782:     /* If line starts with a # it is a comment */
                   9783:     if (line[0] == '#') {
                   9784:       numlinepar++;
                   9785:       fputs(line,stdout);
                   9786:       fputs(line,ficparo);
                   9787:       fputs(line,ficlog);
                   9788:       continue;
                   9789:     }else
                   9790:       break;
                   9791:   }
1.201     brouard  9792:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
                   9793:     if (num_filled == 0)
                   9794:             model[0]='\0';
                   9795:     else if (num_filled != 1){
1.197     brouard  9796:       printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   9797:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   9798:       model[0]='\0';
                   9799:       goto end;
                   9800:     }
                   9801:     else{
                   9802:       if (model[0]=='+'){
                   9803:        for(i=1; i<=strlen(model);i++)
                   9804:          modeltemp[i-1]=model[i];
1.201     brouard  9805:        strcpy(model,modeltemp); 
1.197     brouard  9806:       }
                   9807:     }
1.199     brouard  9808:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  9809:     printf("model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  9810:   }
                   9811:   /* 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=1+age+%s\n",title, datafile, &lastobs, &firstpass,&lastpass,&ftol, &stepm, &ncovcol, &nlstate,&ndeath, &maxwav, &mle, &weightopt,model); */
                   9812:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   9813:   /* 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=1+age+%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate,ndeath, maxwav, mle, weightopt,model); */
1.223     brouard  9814:   fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nqv=%d ntv=%d nqtv=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=1+age+%s.\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol, nqv, ntv, nqtv, nlstate,ndeath,maxwav, mle, weightopt,model);
                   9815:   fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nqv=%d ntv=%d nqtv=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=1+age+%s.\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol, nqv, ntv, nqtv, nlstate,ndeath,maxwav, mle, weightopt,model);
1.126     brouard  9816:   fflush(ficlog);
1.190     brouard  9817:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   9818:   if(model[0]=='#'){
1.187     brouard  9819:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
                   9820:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
                   9821:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");         \
                   9822:     if(mle != -1){
                   9823:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
                   9824:       exit(1);
                   9825:     }
                   9826:   }
1.126     brouard  9827:   while((c=getc(ficpar))=='#' && c!= EOF){
                   9828:     ungetc(c,ficpar);
                   9829:     fgets(line, MAXLINE, ficpar);
                   9830:     numlinepar++;
1.195     brouard  9831:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   9832:       z[0]=line[1];
                   9833:     }
                   9834:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  9835:     fputs(line, stdout);
                   9836:     //puts(line);
1.126     brouard  9837:     fputs(line,ficparo);
                   9838:     fputs(line,ficlog);
                   9839:   }
                   9840:   ungetc(c,ficpar);
                   9841: 
                   9842:    
1.145     brouard  9843:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
1.225     brouard  9844:   coqvar=matrix(1,nqv,1,n);  /**< Fixed quantitative covariate */
1.233     brouard  9845:   cotvar=ma3x(1,maxwav,1,ntv+nqtv,1,n);  /**< Time varying covariate (dummy and quantitative)*/
1.225     brouard  9846:   cotqvar=ma3x(1,maxwav,1,nqtv,1,n);  /**< Time varying quantitative covariate */
1.136     brouard  9847:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   9848:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   9849:      v1+v2*age+v2*v3 makes cptcovn = 3
                   9850:   */
                   9851:   if (strlen(model)>1) 
1.187     brouard  9852:     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,age*age makes 3*/
1.145     brouard  9853:   else
1.187     brouard  9854:     ncovmodel=2; /* Constant and age */
1.133     brouard  9855:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   9856:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  9857:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   9858:     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);
                   9859:     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);
                   9860:     fflush(stdout);
                   9861:     fclose (ficlog);
                   9862:     goto end;
                   9863:   }
1.126     brouard  9864:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   9865:   delti=delti3[1][1];
                   9866:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   9867:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   9868:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  9869:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   9870:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  9871:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   9872:     fclose (ficparo);
                   9873:     fclose (ficlog);
                   9874:     goto end;
                   9875:     exit(0);
1.220     brouard  9876:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  9877:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  9878:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   9879:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  9880:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   9881:     matcov=matrix(1,npar,1,npar);
1.203     brouard  9882:     hess=matrix(1,npar,1,npar);
1.220     brouard  9883:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  9884:     /* Read guessed parameters */
1.126     brouard  9885:     /* Reads comments: lines beginning with '#' */
                   9886:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9887:       ungetc(c,ficpar);
                   9888:       fgets(line, MAXLINE, ficpar);
                   9889:       numlinepar++;
1.141     brouard  9890:       fputs(line,stdout);
1.126     brouard  9891:       fputs(line,ficparo);
                   9892:       fputs(line,ficlog);
                   9893:     }
                   9894:     ungetc(c,ficpar);
                   9895:     
                   9896:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   9897:     for(i=1; i <=nlstate; i++){
1.234     brouard  9898:       j=0;
1.126     brouard  9899:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  9900:        if(jj==i) continue;
                   9901:        j++;
                   9902:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   9903:        if ((i1 != i) || (j1 != jj)){
                   9904:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  9905: It might be a problem of design; if ncovcol and the model are correct\n \
                   9906: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  9907:          exit(1);
                   9908:        }
                   9909:        fprintf(ficparo,"%1d%1d",i1,j1);
                   9910:        if(mle==1)
                   9911:          printf("%1d%1d",i,jj);
                   9912:        fprintf(ficlog,"%1d%1d",i,jj);
                   9913:        for(k=1; k<=ncovmodel;k++){
                   9914:          fscanf(ficpar," %lf",&param[i][j][k]);
                   9915:          if(mle==1){
                   9916:            printf(" %lf",param[i][j][k]);
                   9917:            fprintf(ficlog," %lf",param[i][j][k]);
                   9918:          }
                   9919:          else
                   9920:            fprintf(ficlog," %lf",param[i][j][k]);
                   9921:          fprintf(ficparo," %lf",param[i][j][k]);
                   9922:        }
                   9923:        fscanf(ficpar,"\n");
                   9924:        numlinepar++;
                   9925:        if(mle==1)
                   9926:          printf("\n");
                   9927:        fprintf(ficlog,"\n");
                   9928:        fprintf(ficparo,"\n");
1.126     brouard  9929:       }
                   9930:     }  
                   9931:     fflush(ficlog);
1.234     brouard  9932:     
1.145     brouard  9933:     /* Reads scales values */
1.126     brouard  9934:     p=param[1][1];
                   9935:     
                   9936:     /* Reads comments: lines beginning with '#' */
                   9937:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9938:       ungetc(c,ficpar);
                   9939:       fgets(line, MAXLINE, ficpar);
                   9940:       numlinepar++;
1.141     brouard  9941:       fputs(line,stdout);
1.126     brouard  9942:       fputs(line,ficparo);
                   9943:       fputs(line,ficlog);
                   9944:     }
                   9945:     ungetc(c,ficpar);
                   9946: 
                   9947:     for(i=1; i <=nlstate; i++){
                   9948:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  9949:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   9950:        if ( (i1-i) * (j1-j) != 0){
                   9951:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   9952:          exit(1);
                   9953:        }
                   9954:        printf("%1d%1d",i,j);
                   9955:        fprintf(ficparo,"%1d%1d",i1,j1);
                   9956:        fprintf(ficlog,"%1d%1d",i1,j1);
                   9957:        for(k=1; k<=ncovmodel;k++){
                   9958:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   9959:          printf(" %le",delti3[i][j][k]);
                   9960:          fprintf(ficparo," %le",delti3[i][j][k]);
                   9961:          fprintf(ficlog," %le",delti3[i][j][k]);
                   9962:        }
                   9963:        fscanf(ficpar,"\n");
                   9964:        numlinepar++;
                   9965:        printf("\n");
                   9966:        fprintf(ficparo,"\n");
                   9967:        fprintf(ficlog,"\n");
1.126     brouard  9968:       }
                   9969:     }
                   9970:     fflush(ficlog);
1.234     brouard  9971:     
1.145     brouard  9972:     /* Reads covariance matrix */
1.126     brouard  9973:     delti=delti3[1][1];
1.220     brouard  9974:                
                   9975:                
1.126     brouard  9976:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
1.220     brouard  9977:                
1.126     brouard  9978:     /* Reads comments: lines beginning with '#' */
                   9979:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9980:       ungetc(c,ficpar);
                   9981:       fgets(line, MAXLINE, ficpar);
                   9982:       numlinepar++;
1.141     brouard  9983:       fputs(line,stdout);
1.126     brouard  9984:       fputs(line,ficparo);
                   9985:       fputs(line,ficlog);
                   9986:     }
                   9987:     ungetc(c,ficpar);
1.220     brouard  9988:                
1.126     brouard  9989:     matcov=matrix(1,npar,1,npar);
1.203     brouard  9990:     hess=matrix(1,npar,1,npar);
1.131     brouard  9991:     for(i=1; i <=npar; i++)
                   9992:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  9993:                
1.194     brouard  9994:     /* Scans npar lines */
1.126     brouard  9995:     for(i=1; i <=npar; i++){
1.226     brouard  9996:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  9997:       if(count != 3){
1.226     brouard  9998:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  9999: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   10000: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  10001:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  10002: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   10003: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  10004:        exit(1);
1.220     brouard  10005:       }else{
1.226     brouard  10006:        if(mle==1)
                   10007:          printf("%1d%1d%d",i1,j1,jk);
                   10008:       }
                   10009:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   10010:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  10011:       for(j=1; j <=i; j++){
1.226     brouard  10012:        fscanf(ficpar," %le",&matcov[i][j]);
                   10013:        if(mle==1){
                   10014:          printf(" %.5le",matcov[i][j]);
                   10015:        }
                   10016:        fprintf(ficlog," %.5le",matcov[i][j]);
                   10017:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  10018:       }
                   10019:       fscanf(ficpar,"\n");
                   10020:       numlinepar++;
                   10021:       if(mle==1)
1.220     brouard  10022:                                printf("\n");
1.126     brouard  10023:       fprintf(ficlog,"\n");
                   10024:       fprintf(ficparo,"\n");
                   10025:     }
1.194     brouard  10026:     /* End of read covariance matrix npar lines */
1.126     brouard  10027:     for(i=1; i <=npar; i++)
                   10028:       for(j=i+1;j<=npar;j++)
1.226     brouard  10029:        matcov[i][j]=matcov[j][i];
1.126     brouard  10030:     
                   10031:     if(mle==1)
                   10032:       printf("\n");
                   10033:     fprintf(ficlog,"\n");
                   10034:     
                   10035:     fflush(ficlog);
                   10036:     
                   10037:     /*-------- Rewriting parameter file ----------*/
                   10038:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   10039:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   10040:     strcat(rfileres,".");    /* */
                   10041:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   10042:     if((ficres =fopen(rfileres,"w"))==NULL) {
1.201     brouard  10043:       printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   10044:       fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
1.126     brouard  10045:     }
                   10046:     fprintf(ficres,"#%s\n",version);
                   10047:   }    /* End of mle != -3 */
1.218     brouard  10048:   
1.186     brouard  10049:   /*  Main data
                   10050:    */
1.126     brouard  10051:   n= lastobs;
                   10052:   num=lvector(1,n);
                   10053:   moisnais=vector(1,n);
                   10054:   annais=vector(1,n);
                   10055:   moisdc=vector(1,n);
                   10056:   andc=vector(1,n);
1.220     brouard  10057:   weight=vector(1,n);
1.126     brouard  10058:   agedc=vector(1,n);
                   10059:   cod=ivector(1,n);
1.220     brouard  10060:   for(i=1;i<=n;i++){
1.234     brouard  10061:     num[i]=0;
                   10062:     moisnais[i]=0;
                   10063:     annais[i]=0;
                   10064:     moisdc[i]=0;
                   10065:     andc[i]=0;
                   10066:     agedc[i]=0;
                   10067:     cod[i]=0;
                   10068:     weight[i]=1.0; /* Equal weights, 1 by default */
                   10069:   }
1.126     brouard  10070:   mint=matrix(1,maxwav,1,n);
                   10071:   anint=matrix(1,maxwav,1,n);
1.131     brouard  10072:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  10073:   tab=ivector(1,NCOVMAX);
1.144     brouard  10074:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  10075:   ncodemaxwundef=ivector(1,NCOVMAX); /* Number of code per covariate; if - 1 O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.126     brouard  10076: 
1.136     brouard  10077:   /* Reads data from file datafile */
                   10078:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   10079:     goto end;
                   10080: 
                   10081:   /* Calculation of the number of parameters from char model */
1.234     brouard  10082:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  10083:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   10084:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   10085:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   10086:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  10087:   */
                   10088:   
                   10089:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   10090:   TvarsDind=ivector(1,NCOVMAX); /*  */
                   10091:   TvarsD=ivector(1,NCOVMAX); /*  */
                   10092:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   10093:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  10094:   TvarF=ivector(1,NCOVMAX); /*  */
                   10095:   TvarFind=ivector(1,NCOVMAX); /*  */
                   10096:   TvarV=ivector(1,NCOVMAX); /*  */
                   10097:   TvarVind=ivector(1,NCOVMAX); /*  */
                   10098:   TvarA=ivector(1,NCOVMAX); /*  */
                   10099:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  10100:   TvarFD=ivector(1,NCOVMAX); /*  */
                   10101:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   10102:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   10103:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   10104:   TvarVD=ivector(1,NCOVMAX); /*  */
                   10105:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   10106:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   10107:   TvarVQind=ivector(1,NCOVMAX); /*  */
                   10108: 
1.230     brouard  10109:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  10110:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  10111:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   10112:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   10113:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.137     brouard  10114:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   10115:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   10116:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   10117:   */
                   10118:   /* For model-covariate k tells which data-covariate to use but
                   10119:     because this model-covariate is a construction we invent a new column
                   10120:     ncovcol + k1
                   10121:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   10122:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  10123:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   10124:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  10125:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   10126:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  10127:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  10128:   */
1.145     brouard  10129:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   10130:   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
1.141     brouard  10131:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   10132:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  10133:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  10134:                         4 covariates (3 plus signs)
                   10135:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   10136:                      */  
1.230     brouard  10137:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  10138:                                * individual dummy, fixed or varying:
                   10139:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   10140:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  10141:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   10142:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   10143:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   10144:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   10145:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  10146:                                * individual quantitative, fixed or varying:
                   10147:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   10148:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   10149:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.186     brouard  10150: /* Main decodemodel */
                   10151: 
1.187     brouard  10152: 
1.223     brouard  10153:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  10154:     goto end;
                   10155: 
1.137     brouard  10156:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   10157:     nbwarn++;
                   10158:     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); 
                   10159:     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); 
                   10160:   }
1.136     brouard  10161:     /*  if(mle==1){*/
1.137     brouard  10162:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   10163:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  10164:   }
                   10165: 
                   10166:     /*-calculation of age at interview from date of interview and age at death -*/
                   10167:   agev=matrix(1,maxwav,1,imx);
                   10168: 
                   10169:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   10170:     goto end;
                   10171: 
1.126     brouard  10172: 
1.136     brouard  10173:   agegomp=(int)agemin;
                   10174:   free_vector(moisnais,1,n);
                   10175:   free_vector(annais,1,n);
1.126     brouard  10176:   /* free_matrix(mint,1,maxwav,1,n);
                   10177:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  10178:   /* free_vector(moisdc,1,n); */
                   10179:   /* free_vector(andc,1,n); */
1.145     brouard  10180:   /* */
                   10181:   
1.126     brouard  10182:   wav=ivector(1,imx);
1.214     brouard  10183:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   10184:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   10185:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   10186:   dh=imatrix(1,lastpass-firstpass+2,1,imx); /* We are adding a wave if status is unknown at last wave but death occurs after last wave.*/
                   10187:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   10188:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  10189:    
                   10190:   /* Concatenates waves */
1.214     brouard  10191:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   10192:      Death is a valid wave (if date is known).
                   10193:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   10194:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   10195:      and mw[mi+1][i]. dh depends on stepm.
                   10196:   */
                   10197: 
1.126     brouard  10198:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.145     brouard  10199:   /* */
                   10200:  
1.215     brouard  10201:   free_vector(moisdc,1,n);
                   10202:   free_vector(andc,1,n);
                   10203: 
1.126     brouard  10204:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   10205:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   10206:   ncodemax[1]=1;
1.145     brouard  10207:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  10208:   cptcoveff=0;
1.220     brouard  10209:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
                   10210:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.227     brouard  10211:   }
                   10212:   
                   10213:   ncovcombmax=pow(2,cptcoveff);
                   10214:   invalidvarcomb=ivector(1, ncovcombmax); 
                   10215:   for(i=1;i<ncovcombmax;i++)
                   10216:     invalidvarcomb[i]=0;
                   10217:   
1.211     brouard  10218:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  10219:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  10220:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  10221:   
1.200     brouard  10222:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  10223:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  10224:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  10225:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   10226:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   10227:    * (currently 0 or 1) in the data.
                   10228:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   10229:    * corresponding modality (h,j).
                   10230:    */
                   10231: 
1.145     brouard  10232:   h=0;
                   10233:   /*if (cptcovn > 0) */
1.126     brouard  10234:   m=pow(2,cptcoveff);
                   10235:  
1.144     brouard  10236:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  10237:           * For k=4 covariates, h goes from 1 to m=2**k
                   10238:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   10239:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.186     brouard  10240:           *     h\k   1     2     3     4
1.143     brouard  10241:           *______________________________  
                   10242:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   10243:           *     2     2     1     1     1
                   10244:           *     3 i=2 1     2     1     1
                   10245:           *     4     2     2     1     1
                   10246:           *     5 i=3 1 i=2 1     2     1
                   10247:           *     6     2     1     2     1
                   10248:           *     7 i=4 1     2     2     1
                   10249:           *     8     2     2     2     1
1.197     brouard  10250:           *     9 i=5 1 i=3 1 i=2 1     2
                   10251:           *    10     2     1     1     2
                   10252:           *    11 i=6 1     2     1     2
                   10253:           *    12     2     2     1     2
                   10254:           *    13 i=7 1 i=4 1     2     2    
                   10255:           *    14     2     1     2     2
                   10256:           *    15 i=8 1     2     2     2
                   10257:           *    16     2     2     2     2
1.143     brouard  10258:           */
1.212     brouard  10259:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  10260:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   10261:      * and the value of each covariate?
                   10262:      * V1=1, V2=1, V3=2, V4=1 ?
                   10263:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   10264:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   10265:      * In order to get the real value in the data, we use nbcode
                   10266:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   10267:      * We are keeping this crazy system in order to be able (in the future?) 
                   10268:      * to have more than 2 values (0 or 1) for a covariate.
                   10269:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   10270:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   10271:      *              bbbbbbbb
                   10272:      *              76543210     
                   10273:      *   h-1        00000101 (6-1=5)
1.219     brouard  10274:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  10275:      *           &
                   10276:      *     1        00000001 (1)
1.219     brouard  10277:      *              00000000        = 1 & ((h-1) >> (k-1))
                   10278:      *          +1= 00000001 =1 
1.211     brouard  10279:      *
                   10280:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   10281:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   10282:      *    >>k'            11
                   10283:      *          &   00000001
                   10284:      *            = 00000001
                   10285:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   10286:      * Reverse h=6 and m=16?
                   10287:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   10288:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   10289:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   10290:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   10291:      * V3=decodtabm(14,3,2**4)=2
                   10292:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   10293:      *(h-1) >> (j-1)    0011 =13 >> 2
                   10294:      *          &1 000000001
                   10295:      *           = 000000001
                   10296:      *         +1= 000000010 =2
                   10297:      *                  2211
                   10298:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   10299:      *                  V3=2
1.220     brouard  10300:                 * codtabm and decodtabm are identical
1.211     brouard  10301:      */
                   10302: 
1.145     brouard  10303: 
                   10304:  free_ivector(Ndum,-1,NCOVMAX);
                   10305: 
                   10306: 
1.126     brouard  10307:     
1.186     brouard  10308:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  10309:   strcpy(optionfilegnuplot,optionfilefiname);
                   10310:   if(mle==-3)
1.201     brouard  10311:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  10312:   strcat(optionfilegnuplot,".gp");
                   10313: 
                   10314:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   10315:     printf("Problem with file %s",optionfilegnuplot);
                   10316:   }
                   10317:   else{
1.204     brouard  10318:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  10319:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  10320:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   10321:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  10322:   }
                   10323:   /*  fclose(ficgp);*/
1.186     brouard  10324: 
                   10325: 
                   10326:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  10327: 
                   10328:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   10329:   if(mle==-3)
1.201     brouard  10330:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  10331:   strcat(optionfilehtm,".htm");
                   10332:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  10333:     printf("Problem with %s \n",optionfilehtm);
                   10334:     exit(0);
1.126     brouard  10335:   }
                   10336: 
                   10337:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   10338:   strcat(optionfilehtmcov,"-cov.htm");
                   10339:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   10340:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   10341:   }
                   10342:   else{
                   10343:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   10344: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  10345: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  10346:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   10347:   }
                   10348: 
1.213     brouard  10349:   fprintf(fichtm,"<html><head>\n<head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n<title>IMaCh %s</title></head>\n <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n<font size=\"3\">Sponsored by Copyright (C)  2002-2015 <a href=http://www.ined.fr>INED</a>-EUROREVES-Institut de longévité-2013-2016-Japan Society for the Promotion of Sciences 日本学術振興会 (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - <a href=https://software.intel.com/en-us>Intel Software 2015-2018</a></font><br>  \
1.204     brouard  10350: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   10351: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  10352: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  10353: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  10354: \n\
                   10355: <hr  size=\"2\" color=\"#EC5E5E\">\
                   10356:  <ul><li><h4>Parameter files</h4>\n\
                   10357:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   10358:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   10359:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   10360:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   10361:  - Date and time at start: %s</ul>\n",\
                   10362:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   10363:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   10364:          fileres,fileres,\
                   10365:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   10366:   fflush(fichtm);
                   10367: 
                   10368:   strcpy(pathr,path);
                   10369:   strcat(pathr,optionfilefiname);
1.184     brouard  10370: #ifdef WIN32
                   10371:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   10372: #else
1.126     brouard  10373:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  10374: #endif
                   10375:          
1.126     brouard  10376:   
1.220     brouard  10377:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   10378:                 and for any valid combination of covariates
1.126     brouard  10379:      and prints on file fileres'p'. */
1.227     brouard  10380:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
                   10381:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  10382: 
                   10383:   fprintf(fichtm,"\n");
                   10384:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   10385: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   10386: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   10387:          imx,agemin,agemax,jmin,jmax,jmean);
                   10388:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.220     brouard  10389:        oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   10390:        newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   10391:        savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   10392:        oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  10393: 
1.126     brouard  10394:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   10395:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   10396:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   10397: 
                   10398:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  10399:   /* For mortality only */
1.126     brouard  10400:   if (mle==-3){
1.136     brouard  10401:     ximort=matrix(1,NDIM,1,NDIM); 
1.220     brouard  10402:                for(i=1;i<=NDIM;i++)
                   10403:                        for(j=1;j<=NDIM;j++)
                   10404:                                ximort[i][j]=0.;
1.186     brouard  10405:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  10406:     cens=ivector(1,n);
                   10407:     ageexmed=vector(1,n);
                   10408:     agecens=vector(1,n);
                   10409:     dcwave=ivector(1,n);
1.223     brouard  10410:                
1.126     brouard  10411:     for (i=1; i<=imx; i++){
                   10412:       dcwave[i]=-1;
                   10413:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  10414:        if (s[m][i]>nlstate) {
                   10415:          dcwave[i]=m;
                   10416:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   10417:          break;
                   10418:        }
1.126     brouard  10419:     }
1.226     brouard  10420:     
1.126     brouard  10421:     for (i=1; i<=imx; i++) {
                   10422:       if (wav[i]>0){
1.226     brouard  10423:        ageexmed[i]=agev[mw[1][i]][i];
                   10424:        j=wav[i];
                   10425:        agecens[i]=1.; 
                   10426:        
                   10427:        if (ageexmed[i]> 1 && wav[i] > 0){
                   10428:          agecens[i]=agev[mw[j][i]][i];
                   10429:          cens[i]= 1;
                   10430:        }else if (ageexmed[i]< 1) 
                   10431:          cens[i]= -1;
                   10432:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   10433:          cens[i]=0 ;
1.126     brouard  10434:       }
                   10435:       else cens[i]=-1;
                   10436:     }
                   10437:     
                   10438:     for (i=1;i<=NDIM;i++) {
                   10439:       for (j=1;j<=NDIM;j++)
1.226     brouard  10440:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  10441:     }
                   10442:     
1.145     brouard  10443:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  10444:     /*printf("%lf %lf", p[1], p[2]);*/
                   10445:     
                   10446:     
1.136     brouard  10447: #ifdef GSL
                   10448:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  10449: #else
1.126     brouard  10450:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  10451: #endif
1.201     brouard  10452:     strcpy(filerespow,"POW-MORT_"); 
                   10453:     strcat(filerespow,fileresu);
1.126     brouard  10454:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   10455:       printf("Problem with resultfile: %s\n", filerespow);
                   10456:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   10457:     }
1.136     brouard  10458: #ifdef GSL
                   10459:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  10460: #else
1.126     brouard  10461:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  10462: #endif
1.126     brouard  10463:     /*  for (i=1;i<=nlstate;i++)
                   10464:        for(j=1;j<=nlstate+ndeath;j++)
                   10465:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   10466:     */
                   10467:     fprintf(ficrespow,"\n");
1.136     brouard  10468: #ifdef GSL
                   10469:     /* gsl starts here */ 
                   10470:     T = gsl_multimin_fminimizer_nmsimplex;
                   10471:     gsl_multimin_fminimizer *sfm = NULL;
                   10472:     gsl_vector *ss, *x;
                   10473:     gsl_multimin_function minex_func;
                   10474: 
                   10475:     /* Initial vertex size vector */
                   10476:     ss = gsl_vector_alloc (NDIM);
                   10477:     
                   10478:     if (ss == NULL){
                   10479:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   10480:     }
                   10481:     /* Set all step sizes to 1 */
                   10482:     gsl_vector_set_all (ss, 0.001);
                   10483: 
                   10484:     /* Starting point */
1.126     brouard  10485:     
1.136     brouard  10486:     x = gsl_vector_alloc (NDIM);
                   10487:     
                   10488:     if (x == NULL){
                   10489:       gsl_vector_free(ss);
                   10490:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   10491:     }
                   10492:   
                   10493:     /* Initialize method and iterate */
                   10494:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  10495:     /*     gsl_vector_set(x, 0, 0.0268); */
                   10496:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  10497:     gsl_vector_set(x, 0, p[1]);
                   10498:     gsl_vector_set(x, 1, p[2]);
                   10499: 
                   10500:     minex_func.f = &gompertz_f;
                   10501:     minex_func.n = NDIM;
                   10502:     minex_func.params = (void *)&p; /* ??? */
                   10503:     
                   10504:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   10505:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   10506:     
                   10507:     printf("Iterations beginning .....\n\n");
                   10508:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   10509: 
                   10510:     iteri=0;
                   10511:     while (rval == GSL_CONTINUE){
                   10512:       iteri++;
                   10513:       status = gsl_multimin_fminimizer_iterate(sfm);
                   10514:       
                   10515:       if (status) printf("error: %s\n", gsl_strerror (status));
                   10516:       fflush(0);
                   10517:       
                   10518:       if (status) 
                   10519:         break;
                   10520:       
                   10521:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   10522:       ssval = gsl_multimin_fminimizer_size (sfm);
                   10523:       
                   10524:       if (rval == GSL_SUCCESS)
                   10525:         printf ("converged to a local maximum at\n");
                   10526:       
                   10527:       printf("%5d ", iteri);
                   10528:       for (it = 0; it < NDIM; it++){
                   10529:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   10530:       }
                   10531:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   10532:     }
                   10533:     
                   10534:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   10535:     
                   10536:     gsl_vector_free(x); /* initial values */
                   10537:     gsl_vector_free(ss); /* inital step size */
                   10538:     for (it=0; it<NDIM; it++){
                   10539:       p[it+1]=gsl_vector_get(sfm->x,it);
                   10540:       fprintf(ficrespow," %.12lf", p[it]);
                   10541:     }
                   10542:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   10543: #endif
                   10544: #ifdef POWELL
                   10545:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   10546: #endif  
1.126     brouard  10547:     fclose(ficrespow);
                   10548:     
1.203     brouard  10549:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  10550: 
                   10551:     for(i=1; i <=NDIM; i++)
                   10552:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  10553:                                matcov[i][j]=matcov[j][i];
1.126     brouard  10554:     
                   10555:     printf("\nCovariance matrix\n ");
1.203     brouard  10556:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  10557:     for(i=1; i <=NDIM; i++) {
                   10558:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  10559:                                printf("%f ",matcov[i][j]);
                   10560:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  10561:       }
1.203     brouard  10562:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  10563:     }
                   10564:     
                   10565:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  10566:     for (i=1;i<=NDIM;i++) {
1.126     brouard  10567:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  10568:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   10569:     }
1.126     brouard  10570:     lsurv=vector(1,AGESUP);
                   10571:     lpop=vector(1,AGESUP);
                   10572:     tpop=vector(1,AGESUP);
                   10573:     lsurv[agegomp]=100000;
                   10574:     
                   10575:     for (k=agegomp;k<=AGESUP;k++) {
                   10576:       agemortsup=k;
                   10577:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   10578:     }
                   10579:     
                   10580:     for (k=agegomp;k<agemortsup;k++)
                   10581:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   10582:     
                   10583:     for (k=agegomp;k<agemortsup;k++){
                   10584:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   10585:       sumlpop=sumlpop+lpop[k];
                   10586:     }
                   10587:     
                   10588:     tpop[agegomp]=sumlpop;
                   10589:     for (k=agegomp;k<(agemortsup-3);k++){
                   10590:       /*  tpop[k+1]=2;*/
                   10591:       tpop[k+1]=tpop[k]-lpop[k];
                   10592:     }
                   10593:     
                   10594:     
                   10595:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   10596:     for (k=agegomp;k<(agemortsup-2);k++) 
                   10597:       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]);
                   10598:     
                   10599:     
                   10600:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  10601:                ageminpar=50;
                   10602:                agemaxpar=100;
1.194     brouard  10603:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   10604:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   10605: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   10606: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   10607:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   10608: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   10609: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  10610:     }else{
                   10611:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   10612:                        fprintf(ficlog,"Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
1.201     brouard  10613:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  10614:                }
1.201     brouard  10615:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  10616:                     stepm, weightopt,\
                   10617:                     model,imx,p,matcov,agemortsup);
                   10618:     
                   10619:     free_vector(lsurv,1,AGESUP);
                   10620:     free_vector(lpop,1,AGESUP);
                   10621:     free_vector(tpop,1,AGESUP);
1.220     brouard  10622:     free_matrix(ximort,1,NDIM,1,NDIM);
1.136     brouard  10623:     free_ivector(cens,1,n);
                   10624:     free_vector(agecens,1,n);
                   10625:     free_ivector(dcwave,1,n);
1.220     brouard  10626: #ifdef GSL
1.136     brouard  10627: #endif
1.186     brouard  10628:   } /* Endof if mle==-3 mortality only */
1.205     brouard  10629:   /* Standard  */
                   10630:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   10631:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   10632:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  10633:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  10634:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   10635:     for (k=1; k<=npar;k++)
                   10636:       printf(" %d %8.5f",k,p[k]);
                   10637:     printf("\n");
1.205     brouard  10638:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   10639:       /* mlikeli uses func not funcone */
                   10640:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   10641:     }
                   10642:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   10643:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   10644:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   10645:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   10646:     }
                   10647:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  10648:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   10649:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   10650:     for (k=1; k<=npar;k++)
                   10651:       printf(" %d %8.5f",k,p[k]);
                   10652:     printf("\n");
                   10653:     
                   10654:     /*--------- results files --------------*/
1.224     brouard  10655:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nqv=%d ntv=%d nqtv=%d nlstate=%d ndeath=%d maxwav=%d mle= 0 weight=%d\nmodel=1+age+%s.\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nqv, ntv, nqtv, nlstate, ndeath, maxwav, weightopt,model);
1.126     brouard  10656:     
                   10657:     
                   10658:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10659:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10660:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10661:     for(i=1,jk=1; i <=nlstate; i++){
                   10662:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  10663:        if (k != i) {
                   10664:          printf("%d%d ",i,k);
                   10665:          fprintf(ficlog,"%d%d ",i,k);
                   10666:          fprintf(ficres,"%1d%1d ",i,k);
                   10667:          for(j=1; j <=ncovmodel; j++){
                   10668:            printf("%12.7f ",p[jk]);
                   10669:            fprintf(ficlog,"%12.7f ",p[jk]);
                   10670:            fprintf(ficres,"%12.7f ",p[jk]);
                   10671:            jk++; 
                   10672:          }
                   10673:          printf("\n");
                   10674:          fprintf(ficlog,"\n");
                   10675:          fprintf(ficres,"\n");
                   10676:        }
1.126     brouard  10677:       }
                   10678:     }
1.203     brouard  10679:     if(mle != 0){
                   10680:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  10681:       ftolhess=ftol; /* Usually correct */
1.203     brouard  10682:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   10683:       printf("Parameters and 95%% confidence intervals\n W is simply the result of the division of the parameter by the square root of covariance of the parameter.\n And Wald-based confidence intervals plus and minus 1.96 * W .\n But be careful that parameters are highly correlated because incidence of disability is highly correlated to incidence of recovery.\n It might be better to visualize the covariance matrix. See the page 'Matrix of variance-covariance of one-step probabilities' and its graphs.\n");
                   10684:       fprintf(ficlog, "Parameters, Wald tests and Wald-based confidence intervals\n W is simply the result of the division of the parameter by the square root of covariance of the parameter.\n And Wald-based confidence intervals plus and minus 1.96 * W \n  It might be better to visualize the covariance matrix. See the page 'Matrix of variance-covariance of one-step probabilities' and its graphs.\n");
                   10685:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  10686:        for(k=1; k <=(nlstate+ndeath); k++){
                   10687:          if (k != i) {
                   10688:            printf("%d%d ",i,k);
                   10689:            fprintf(ficlog,"%d%d ",i,k);
                   10690:            for(j=1; j <=ncovmodel; j++){
                   10691:              printf("%12.7f W=%8.3f CI=[%12.7f ; %12.7f] ",p[jk], p[jk]/sqrt(matcov[jk][jk]), p[jk]-1.96*sqrt(matcov[jk][jk]),p[jk]+1.96*sqrt(matcov[jk][jk]));
                   10692:              fprintf(ficlog,"%12.7f W=%8.3f CI=[%12.7f ; %12.7f] ",p[jk], p[jk]/sqrt(matcov[jk][jk]), p[jk]-1.96*sqrt(matcov[jk][jk]),p[jk]+1.96*sqrt(matcov[jk][jk]));
                   10693:              jk++; 
                   10694:            }
                   10695:            printf("\n");
                   10696:            fprintf(ficlog,"\n");
                   10697:          }
                   10698:        }
1.193     brouard  10699:       }
1.203     brouard  10700:     } /* end of hesscov and Wald tests */
1.225     brouard  10701:     
1.203     brouard  10702:     /*  */
1.126     brouard  10703:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   10704:     printf("# Scales (for hessian or gradient estimation)\n");
                   10705:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   10706:     for(i=1,jk=1; i <=nlstate; i++){
                   10707:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  10708:        if (j!=i) {
                   10709:          fprintf(ficres,"%1d%1d",i,j);
                   10710:          printf("%1d%1d",i,j);
                   10711:          fprintf(ficlog,"%1d%1d",i,j);
                   10712:          for(k=1; k<=ncovmodel;k++){
                   10713:            printf(" %.5e",delti[jk]);
                   10714:            fprintf(ficlog," %.5e",delti[jk]);
                   10715:            fprintf(ficres," %.5e",delti[jk]);
                   10716:            jk++;
                   10717:          }
                   10718:          printf("\n");
                   10719:          fprintf(ficlog,"\n");
                   10720:          fprintf(ficres,"\n");
                   10721:        }
1.126     brouard  10722:       }
                   10723:     }
                   10724:     
                   10725:     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");
1.203     brouard  10726:     if(mle >= 1) /* To big for the screen */
1.126     brouard  10727:       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");
                   10728:     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");
                   10729:     /* # 121 Var(a12)\n\ */
                   10730:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10731:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   10732:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   10733:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   10734:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   10735:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   10736:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   10737:     
                   10738:     
                   10739:     /* Just to have a covariance matrix which will be more understandable
                   10740:        even is we still don't want to manage dictionary of variables
                   10741:     */
                   10742:     for(itimes=1;itimes<=2;itimes++){
                   10743:       jj=0;
                   10744:       for(i=1; i <=nlstate; i++){
1.225     brouard  10745:        for(j=1; j <=nlstate+ndeath; j++){
                   10746:          if(j==i) continue;
                   10747:          for(k=1; k<=ncovmodel;k++){
                   10748:            jj++;
                   10749:            ca[0]= k+'a'-1;ca[1]='\0';
                   10750:            if(itimes==1){
                   10751:              if(mle>=1)
                   10752:                printf("#%1d%1d%d",i,j,k);
                   10753:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   10754:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   10755:            }else{
                   10756:              if(mle>=1)
                   10757:                printf("%1d%1d%d",i,j,k);
                   10758:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   10759:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   10760:            }
                   10761:            ll=0;
                   10762:            for(li=1;li <=nlstate; li++){
                   10763:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   10764:                if(lj==li) continue;
                   10765:                for(lk=1;lk<=ncovmodel;lk++){
                   10766:                  ll++;
                   10767:                  if(ll<=jj){
                   10768:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   10769:                    if(ll<jj){
                   10770:                      if(itimes==1){
                   10771:                        if(mle>=1)
                   10772:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10773:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10774:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10775:                      }else{
                   10776:                        if(mle>=1)
                   10777:                          printf(" %.5e",matcov[jj][ll]); 
                   10778:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   10779:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   10780:                      }
                   10781:                    }else{
                   10782:                      if(itimes==1){
                   10783:                        if(mle>=1)
                   10784:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   10785:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   10786:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   10787:                      }else{
                   10788:                        if(mle>=1)
                   10789:                          printf(" %.7e",matcov[jj][ll]); 
                   10790:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   10791:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   10792:                      }
                   10793:                    }
                   10794:                  }
                   10795:                } /* end lk */
                   10796:              } /* end lj */
                   10797:            } /* end li */
                   10798:            if(mle>=1)
                   10799:              printf("\n");
                   10800:            fprintf(ficlog,"\n");
                   10801:            fprintf(ficres,"\n");
                   10802:            numlinepar++;
                   10803:          } /* end k*/
                   10804:        } /*end j */
1.126     brouard  10805:       } /* end i */
                   10806:     } /* end itimes */
                   10807:     
                   10808:     fflush(ficlog);
                   10809:     fflush(ficres);
1.225     brouard  10810:     while(fgets(line, MAXLINE, ficpar)) {
                   10811:       /* If line starts with a # it is a comment */
                   10812:       if (line[0] == '#') {
                   10813:        numlinepar++;
                   10814:        fputs(line,stdout);
                   10815:        fputs(line,ficparo);
                   10816:        fputs(line,ficlog);
                   10817:        continue;
                   10818:       }else
                   10819:        break;
                   10820:     }
                   10821:     
1.209     brouard  10822:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   10823:     /*   ungetc(c,ficpar); */
                   10824:     /*   fgets(line, MAXLINE, ficpar); */
                   10825:     /*   fputs(line,stdout); */
                   10826:     /*   fputs(line,ficparo); */
                   10827:     /* } */
                   10828:     /* ungetc(c,ficpar); */
1.126     brouard  10829:     
                   10830:     estepm=0;
1.209     brouard  10831:     if((num_filled=sscanf(line,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm, &ftolpl)) !=EOF){
1.225     brouard  10832:       
                   10833:       if (num_filled != 6) {
                   10834:        printf("Error: Not 6 parameters in line, for example:agemin=60 agemax=95 bage=55 fage=95 estepm=24 ftolpl=6e-4\n, your line=%s . Probably you are running an older format.\n",line);
                   10835:        fprintf(ficlog,"Error: Not 6 parameters in line, for example:agemin=60 agemax=95 bage=55 fage=95 estepm=24 ftolpl=6e-4\n, your line=%s . Probably you are running an older format.\n",line);
                   10836:        goto end;
                   10837:       }
                   10838:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   10839:     }
                   10840:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   10841:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   10842:     
1.209     brouard  10843:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  10844:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   10845:     if (fage <= 2) {
                   10846:       bage = ageminpar;
                   10847:       fage = agemaxpar;
                   10848:     }
                   10849:     
                   10850:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  10851:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   10852:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  10853:                
1.186     brouard  10854:     /* Other stuffs, more or less useful */    
1.126     brouard  10855:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10856:       ungetc(c,ficpar);
                   10857:       fgets(line, MAXLINE, ficpar);
1.141     brouard  10858:       fputs(line,stdout);
1.126     brouard  10859:       fputs(line,ficparo);
                   10860:     }
                   10861:     ungetc(c,ficpar);
                   10862:     
                   10863:     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);
                   10864:     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);
                   10865:     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);
                   10866:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   10867:     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);
                   10868:     
                   10869:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10870:       ungetc(c,ficpar);
                   10871:       fgets(line, MAXLINE, ficpar);
1.141     brouard  10872:       fputs(line,stdout);
1.126     brouard  10873:       fputs(line,ficparo);
                   10874:     }
                   10875:     ungetc(c,ficpar);
                   10876:     
                   10877:     
                   10878:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   10879:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   10880:     
                   10881:     fscanf(ficpar,"pop_based=%d\n",&popbased);
1.193     brouard  10882:     fprintf(ficlog,"pop_based=%d\n",popbased);
1.126     brouard  10883:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   10884:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   10885:     
                   10886:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10887:       ungetc(c,ficpar);
                   10888:       fgets(line, MAXLINE, ficpar);
1.141     brouard  10889:       fputs(line,stdout);
1.238     brouard  10890:       fputs(line,ficres);
1.126     brouard  10891:       fputs(line,ficparo);
                   10892:     }
                   10893:     ungetc(c,ficpar);
                   10894:     
                   10895:     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);
                   10896:     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);
                   10897:     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);
                   10898:     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);
                   10899:     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);
                   10900:     /* day and month of proj2 are not used but only year anproj2.*/
                   10901:     
1.217     brouard  10902:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10903:       ungetc(c,ficpar);
                   10904:       fgets(line, MAXLINE, ficpar);
                   10905:       fputs(line,stdout);
                   10906:       fputs(line,ficparo);
1.238     brouard  10907:       fputs(line,ficres);
1.217     brouard  10908:     }
                   10909:     ungetc(c,ficpar);
                   10910:     
                   10911:     fscanf(ficpar,"backcast=%d starting-back-date=%lf/%lf/%lf final-back-date=%lf/%lf/%lf mobil_average=%d\n",&backcast,&jback1,&mback1,&anback1,&jback2,&mback2,&anback2,&mobilavproj);
1.223     brouard  10912:     fprintf(ficparo,"backcast=%d starting-back-date=%.lf/%.lf/%.lf final-back-date=%.lf/%.lf/%.lf mobil_average=%d\n",backcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
                   10913:     fprintf(ficlog,"backcast=%d starting-back-date=%.lf/%.lf/%.lf final-back-date=%.lf/%.lf/%.lf mobil_average=%d\n",backcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
                   10914:     fprintf(ficres,"backcast=%d starting-back-date=%.lf/%.lf/%.lf final-back-date=%.lf/%.lf/%.lf mobil_average=%d\n",backcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
1.217     brouard  10915:     /* day and month of proj2 are not used but only year anproj2.*/
1.126     brouard  10916:     
1.230     brouard  10917:     /* Results */
1.235     brouard  10918:     nresult=0;
1.230     brouard  10919:     while(fgets(line, MAXLINE, ficpar)) {
                   10920:       /* If line starts with a # it is a comment */
                   10921:       if (line[0] == '#') {
                   10922:        numlinepar++;
                   10923:        fputs(line,stdout);
                   10924:        fputs(line,ficparo);
                   10925:        fputs(line,ficlog);
1.238     brouard  10926:        fputs(line,ficres);
1.230     brouard  10927:        continue;
                   10928:       }else
                   10929:        break;
                   10930:     }
1.240     brouard  10931:     if (!feof(ficpar))
1.230     brouard  10932:     while((num_filled=sscanf(line,"result:%[^\n]\n",resultline)) !=EOF){
1.240     brouard  10933:       if (num_filled == 0){
1.230     brouard  10934:        resultline[0]='\0';
1.240     brouard  10935:       break;
                   10936:       } else if (num_filled != 1){
1.230     brouard  10937:        printf("ERROR %d: result line should be at minimum 'result=' %s\n",num_filled, line);
                   10938:       }
1.235     brouard  10939:       nresult++; /* Sum of resultlines */
                   10940:       printf("Result %d: result=%s\n",nresult, resultline);
                   10941:       if(nresult > MAXRESULTLINES){
                   10942:        printf("ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\n",MAXRESULTLINES,nresult);
                   10943:        fprintf(ficlog,"ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\n",MAXRESULTLINES,nresult);
                   10944:        goto end;
                   10945:       }
                   10946:       decoderesult(resultline, nresult); /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.238     brouard  10947:       fprintf(ficparo,"result: %s\n",resultline);
                   10948:       fprintf(ficres,"result: %s\n",resultline);
                   10949:       fprintf(ficlog,"result: %s\n",resultline);
1.230     brouard  10950:       while(fgets(line, MAXLINE, ficpar)) {
                   10951:        /* If line starts with a # it is a comment */
                   10952:        if (line[0] == '#') {
                   10953:          numlinepar++;
                   10954:          fputs(line,stdout);
                   10955:          fputs(line,ficparo);
1.238     brouard  10956:          fputs(line,ficres);
1.230     brouard  10957:          fputs(line,ficlog);
                   10958:          continue;
                   10959:        }else
                   10960:          break;
                   10961:       }
                   10962:       if (feof(ficpar))
                   10963:        break;
                   10964:       else{ /* Processess output results for this combination of covariate values */
                   10965:       }                                   
1.240     brouard  10966:     } /* end while */
1.230     brouard  10967: 
                   10968: 
1.126     brouard  10969:     
1.230     brouard  10970:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  10971:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  10972:     
                   10973:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  10974:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  10975:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  10976: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   10977: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  10978:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  10979: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   10980: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  10981:     }else{
1.218     brouard  10982:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p);
1.220     brouard  10983:     }
                   10984:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.225     brouard  10985:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,prevfcast,backcast, estepm, \
                   10986:                 jprev1,mprev1,anprev1,dateprev1,jprev2,mprev2,anprev2,dateprev2);
1.220     brouard  10987:                
1.225     brouard  10988:     /*------------ free_vector  -------------*/
                   10989:     /*  chdir(path); */
1.220     brouard  10990:                
1.215     brouard  10991:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   10992:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   10993:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   10994:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.126     brouard  10995:     free_lvector(num,1,n);
                   10996:     free_vector(agedc,1,n);
                   10997:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   10998:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   10999:     fclose(ficparo);
                   11000:     fclose(ficres);
1.220     brouard  11001:                
                   11002:                
1.186     brouard  11003:     /* Other results (useful)*/
1.220     brouard  11004:                
                   11005:                
1.126     brouard  11006:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  11007:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   11008:     prlim=matrix(1,nlstate,1,nlstate);
1.209     brouard  11009:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  11010:     fclose(ficrespl);
                   11011: 
                   11012:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  11013:     /*#include "hpijx.h"*/
                   11014:     hPijx(p, bage, fage);
1.145     brouard  11015:     fclose(ficrespij);
1.227     brouard  11016:     
1.220     brouard  11017:     /* ncovcombmax=  pow(2,cptcoveff); */
1.219     brouard  11018:     /*-------------- Variance of one-step probabilities---*/
1.145     brouard  11019:     k=1;
1.126     brouard  11020:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  11021:     
1.219     brouard  11022:     /* Prevalence for each covariates in probs[age][status][cov] */
1.218     brouard  11023:     probs= ma3x(1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.126     brouard  11024:     for(i=1;i<=AGESUP;i++)
1.219     brouard  11025:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  11026:        for(k=1;k<=ncovcombmax;k++)
                   11027:          probs[i][j][k]=0.;
1.219     brouard  11028:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   11029:     if (mobilav!=0 ||mobilavproj !=0 ) {
                   11030:       mobaverages= ma3x(1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.227     brouard  11031:       for(i=1;i<=AGESUP;i++)
                   11032:        for(j=1;j<=nlstate;j++)
                   11033:          for(k=1;k<=ncovcombmax;k++)
                   11034:            mobaverages[i][j][k]=0.;
1.219     brouard  11035:       mobaverage=mobaverages;
                   11036:       if (mobilav!=0) {
1.235     brouard  11037:        printf("Movingaveraging observed prevalence\n");
1.227     brouard  11038:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   11039:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   11040:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   11041:        }
1.219     brouard  11042:       }
                   11043:       /* /\* Prevalence for each covariates in probs[age][status][cov] *\/ */
                   11044:       /* prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   11045:       else if (mobilavproj !=0) {
1.235     brouard  11046:        printf("Movingaveraging projected observed prevalence\n");
1.227     brouard  11047:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   11048:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   11049:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   11050:        }
1.219     brouard  11051:       }
                   11052:     }/* end if moving average */
1.227     brouard  11053:     
1.126     brouard  11054:     /*---------- Forecasting ------------------*/
                   11055:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   11056:     if(prevfcast==1){
                   11057:       /*    if(stepm ==1){*/
1.225     brouard  11058:       prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
1.126     brouard  11059:     }
1.217     brouard  11060:     if(backcast==1){
1.219     brouard  11061:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   11062:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   11063:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   11064: 
                   11065:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   11066: 
                   11067:       bprlim=matrix(1,nlstate,1,nlstate);
                   11068:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   11069:       fclose(ficresplb);
                   11070: 
1.222     brouard  11071:       hBijx(p, bage, fage, mobaverage);
                   11072:       fclose(ficrespijb);
1.219     brouard  11073:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   11074: 
                   11075:       /* prevbackforecast(fileresu, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, mobilavproj,
1.225     brouard  11076:         bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
1.219     brouard  11077:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   11078:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   11079:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   11080:     }
1.217     brouard  11081:     
1.186     brouard  11082:  
                   11083:     /* ------ Other prevalence ratios------------ */
1.126     brouard  11084: 
1.215     brouard  11085:     free_ivector(wav,1,imx);
                   11086:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   11087:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   11088:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  11089:                
                   11090:                
1.127     brouard  11091:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  11092:                
1.201     brouard  11093:     strcpy(filerese,"E_");
                   11094:     strcat(filerese,fileresu);
1.126     brouard  11095:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   11096:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   11097:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   11098:     }
1.208     brouard  11099:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   11100:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  11101: 
                   11102:     pstamp(ficreseij);
1.219     brouard  11103:                
1.235     brouard  11104:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   11105:     if (cptcovn < 1){i1=1;}
                   11106:     
                   11107:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   11108:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
                   11109:       if(TKresult[nres]!= k)
                   11110:        continue;
1.219     brouard  11111:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  11112:       printf("\n#****** ");
1.225     brouard  11113:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  11114:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  11115:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11116:       }
                   11117:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11118:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11119:        fprintf(ficreseij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
1.219     brouard  11120:       }
                   11121:       fprintf(ficreseij,"******\n");
1.235     brouard  11122:       printf("******\n");
1.219     brouard  11123:       
                   11124:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   11125:       oldm=oldms;savm=savms;
1.235     brouard  11126:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  11127:       
1.219     brouard  11128:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  11129:     }
                   11130:     fclose(ficreseij);
1.208     brouard  11131:     printf("done evsij\n");fflush(stdout);
                   11132:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.218     brouard  11133:                
1.227     brouard  11134:     /*---------- State-specific expectancies and variances ------------*/
1.218     brouard  11135:                
                   11136:                
1.201     brouard  11137:     strcpy(filerest,"T_");
                   11138:     strcat(filerest,fileresu);
1.127     brouard  11139:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   11140:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   11141:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   11142:     }
1.208     brouard  11143:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   11144:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.218     brouard  11145:                
1.126     brouard  11146: 
1.201     brouard  11147:     strcpy(fileresstde,"STDE_");
                   11148:     strcat(fileresstde,fileresu);
1.126     brouard  11149:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  11150:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   11151:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  11152:     }
1.227     brouard  11153:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   11154:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  11155: 
1.201     brouard  11156:     strcpy(filerescve,"CVE_");
                   11157:     strcat(filerescve,fileresu);
1.126     brouard  11158:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  11159:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   11160:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  11161:     }
1.227     brouard  11162:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   11163:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  11164: 
1.201     brouard  11165:     strcpy(fileresv,"V_");
                   11166:     strcat(fileresv,fileresu);
1.126     brouard  11167:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   11168:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   11169:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   11170:     }
1.227     brouard  11171:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   11172:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  11173: 
1.145     brouard  11174:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   11175:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   11176:           
1.235     brouard  11177:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   11178:     if (cptcovn < 1){i1=1;}
                   11179:     
                   11180:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   11181:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
                   11182:       if(TKresult[nres]!= k)
                   11183:        continue;
1.242     brouard  11184:       printf("\n#****** Result for:");
                   11185:       fprintf(ficrest,"\n#****** Result for:");
                   11186:       fprintf(ficlog,"\n#****** Result for:");
1.227     brouard  11187:       for(j=1;j<=cptcoveff;j++){ 
                   11188:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11189:        fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11190:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11191:       }
1.235     brouard  11192:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11193:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11194:        fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11195:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11196:       }        
1.208     brouard  11197:       fprintf(ficrest,"******\n");
1.227     brouard  11198:       fprintf(ficlog,"******\n");
                   11199:       printf("******\n");
1.208     brouard  11200:       
                   11201:       fprintf(ficresstdeij,"\n#****** ");
                   11202:       fprintf(ficrescveij,"\n#****** ");
1.225     brouard  11203:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  11204:        fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11205:        fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.208     brouard  11206:       }
1.235     brouard  11207:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11208:        fprintf(ficresstdeij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11209:        fprintf(ficrescveij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11210:       }        
1.208     brouard  11211:       fprintf(ficresstdeij,"******\n");
                   11212:       fprintf(ficrescveij,"******\n");
                   11213:       
                   11214:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  11215:       /* pstamp(ficresvij); */
1.225     brouard  11216:       for(j=1;j<=cptcoveff;j++) 
1.227     brouard  11217:        fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  11218:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11219:        fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11220:       }        
1.208     brouard  11221:       fprintf(ficresvij,"******\n");
                   11222:       
                   11223:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   11224:       oldm=oldms;savm=savms;
1.235     brouard  11225:       printf(" cvevsij ");
                   11226:       fprintf(ficlog, " cvevsij ");
                   11227:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  11228:       printf(" end cvevsij \n ");
                   11229:       fprintf(ficlog, " end cvevsij \n ");
                   11230:       
                   11231:       /*
                   11232:        */
                   11233:       /* goto endfree; */
                   11234:       
                   11235:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   11236:       pstamp(ficrest);
                   11237:       
                   11238:       
                   11239:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  11240:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   11241:        cptcod= 0; /* To be deleted */
                   11242:        printf("varevsij vpopbased=%d \n",vpopbased);
                   11243:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  11244:        varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart, nres); /* cptcod not initialized Intel */
1.227     brouard  11245:        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 ");
                   11246:        if(vpopbased==1)
                   11247:          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);
                   11248:        else
                   11249:          fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
                   11250:        fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
                   11251:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   11252:        fprintf(ficrest,"\n");
                   11253:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
                   11254:        epj=vector(1,nlstate+1);
                   11255:        printf("Computing age specific period (stable) prevalences in each health state \n");
                   11256:        fprintf(ficlog,"Computing age specific period (stable) prevalences in each health state \n");
                   11257:        for(age=bage; age <=fage ;age++){
1.235     brouard  11258:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  11259:          if (vpopbased==1) {
                   11260:            if(mobilav ==0){
                   11261:              for(i=1; i<=nlstate;i++)
                   11262:                prlim[i][i]=probs[(int)age][i][k];
                   11263:            }else{ /* mobilav */ 
                   11264:              for(i=1; i<=nlstate;i++)
                   11265:                prlim[i][i]=mobaverage[(int)age][i][k];
                   11266:            }
                   11267:          }
1.219     brouard  11268:          
1.227     brouard  11269:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   11270:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   11271:          /* printf(" age %4.0f ",age); */
                   11272:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   11273:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   11274:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   11275:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   11276:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   11277:            }
                   11278:            epj[nlstate+1] +=epj[j];
                   11279:          }
                   11280:          /* printf(" age %4.0f \n",age); */
1.219     brouard  11281:          
1.227     brouard  11282:          for(i=1, vepp=0.;i <=nlstate;i++)
                   11283:            for(j=1;j <=nlstate;j++)
                   11284:              vepp += vareij[i][j][(int)age];
                   11285:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   11286:          for(j=1;j <=nlstate;j++){
                   11287:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   11288:          }
                   11289:          fprintf(ficrest,"\n");
                   11290:        }
1.208     brouard  11291:       } /* End vpopbased */
                   11292:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   11293:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   11294:       free_vector(epj,1,nlstate+1);
1.235     brouard  11295:       printf("done selection\n");fflush(stdout);
                   11296:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  11297:       
1.145     brouard  11298:       /*}*/
1.235     brouard  11299:     } /* End k selection */
1.227     brouard  11300: 
                   11301:     printf("done State-specific expectancies\n");fflush(stdout);
                   11302:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   11303: 
1.126     brouard  11304:     /*------- Variance of period (stable) prevalence------*/   
1.227     brouard  11305:     
1.201     brouard  11306:     strcpy(fileresvpl,"VPL_");
                   11307:     strcat(fileresvpl,fileresu);
1.126     brouard  11308:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   11309:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   11310:       exit(0);
                   11311:     }
1.208     brouard  11312:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   11313:     fprintf(ficlog, "Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.227     brouard  11314:     
1.145     brouard  11315:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   11316:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
1.227     brouard  11317:     
1.235     brouard  11318:     i1=pow(2,cptcoveff);
                   11319:     if (cptcovn < 1){i1=1;}
                   11320: 
                   11321:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   11322:     for(k=1; k<=i1;k++){
                   11323:       if(TKresult[nres]!= k)
                   11324:        continue;
1.227     brouard  11325:       fprintf(ficresvpl,"\n#****** ");
                   11326:       printf("\n#****** ");
                   11327:       fprintf(ficlog,"\n#****** ");
                   11328:       for(j=1;j<=cptcoveff;j++) {
                   11329:        fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11330:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11331:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11332:       }
1.235     brouard  11333:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11334:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11335:        fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11336:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11337:       }        
1.227     brouard  11338:       fprintf(ficresvpl,"******\n");
                   11339:       printf("******\n");
                   11340:       fprintf(ficlog,"******\n");
                   11341:       
                   11342:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   11343:       oldm=oldms;savm=savms;
1.235     brouard  11344:       varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, strstart, nres);
1.227     brouard  11345:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145     brouard  11346:       /*}*/
1.126     brouard  11347:     }
1.227     brouard  11348:     
1.126     brouard  11349:     fclose(ficresvpl);
1.208     brouard  11350:     printf("done variance-covariance of period prevalence\n");fflush(stdout);
                   11351:     fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
1.227     brouard  11352:     
                   11353:     free_vector(weight,1,n);
                   11354:     free_imatrix(Tvard,1,NCOVMAX,1,2);
                   11355:     free_imatrix(s,1,maxwav+1,1,n);
                   11356:     free_matrix(anint,1,maxwav,1,n); 
                   11357:     free_matrix(mint,1,maxwav,1,n);
                   11358:     free_ivector(cod,1,n);
                   11359:     free_ivector(tab,1,NCOVMAX);
                   11360:     fclose(ficresstdeij);
                   11361:     fclose(ficrescveij);
                   11362:     fclose(ficresvij);
                   11363:     fclose(ficrest);
                   11364:     fclose(ficpar);
                   11365:     
                   11366:     
1.126     brouard  11367:     /*---------- End : free ----------------*/
1.219     brouard  11368:     if (mobilav!=0 ||mobilavproj !=0)
                   11369:       free_ma3x(mobaverages,1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
1.218     brouard  11370:     free_ma3x(probs,1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  11371:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   11372:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  11373:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  11374:   /* endfree:*/
                   11375:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   11376:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   11377:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   11378:   free_ma3x(cotqvar,1,maxwav,1,nqtv,1,n);
1.233     brouard  11379:   free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,1,n);
1.227     brouard  11380:   free_matrix(coqvar,1,maxwav,1,n);
                   11381:   free_matrix(covar,0,NCOVMAX,1,n);
                   11382:   free_matrix(matcov,1,npar,1,npar);
                   11383:   free_matrix(hess,1,npar,1,npar);
                   11384:   /*free_vector(delti,1,npar);*/
                   11385:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   11386:   free_matrix(agev,1,maxwav,1,imx);
                   11387:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   11388:   
                   11389:   free_ivector(ncodemax,1,NCOVMAX);
                   11390:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   11391:   free_ivector(Dummy,-1,NCOVMAX);
                   11392:   free_ivector(Fixed,-1,NCOVMAX);
1.238     brouard  11393:   free_ivector(DummyV,1,NCOVMAX);
                   11394:   free_ivector(FixedV,1,NCOVMAX);
1.227     brouard  11395:   free_ivector(Typevar,-1,NCOVMAX);
                   11396:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  11397:   free_ivector(TvarsQ,1,NCOVMAX);
                   11398:   free_ivector(TvarsQind,1,NCOVMAX);
                   11399:   free_ivector(TvarsD,1,NCOVMAX);
                   11400:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  11401:   free_ivector(TvarFD,1,NCOVMAX);
                   11402:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  11403:   free_ivector(TvarF,1,NCOVMAX);
                   11404:   free_ivector(TvarFind,1,NCOVMAX);
                   11405:   free_ivector(TvarV,1,NCOVMAX);
                   11406:   free_ivector(TvarVind,1,NCOVMAX);
                   11407:   free_ivector(TvarA,1,NCOVMAX);
                   11408:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  11409:   free_ivector(TvarFQ,1,NCOVMAX);
                   11410:   free_ivector(TvarFQind,1,NCOVMAX);
                   11411:   free_ivector(TvarVD,1,NCOVMAX);
                   11412:   free_ivector(TvarVDind,1,NCOVMAX);
                   11413:   free_ivector(TvarVQ,1,NCOVMAX);
                   11414:   free_ivector(TvarVQind,1,NCOVMAX);
1.230     brouard  11415:   free_ivector(Tvarsel,1,NCOVMAX);
                   11416:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  11417:   free_ivector(Tposprod,1,NCOVMAX);
                   11418:   free_ivector(Tprod,1,NCOVMAX);
                   11419:   free_ivector(Tvaraff,1,NCOVMAX);
                   11420:   free_ivector(invalidvarcomb,1,ncovcombmax);
                   11421:   free_ivector(Tage,1,NCOVMAX);
                   11422:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  11423:   free_ivector(TmodelInvind,1,NCOVMAX);
                   11424:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.227     brouard  11425:   
                   11426:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   11427:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  11428:   fflush(fichtm);
                   11429:   fflush(ficgp);
                   11430:   
1.227     brouard  11431:   
1.126     brouard  11432:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  11433:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   11434:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d. Please look at the log file for details.\n",nberr,nbwarn);
1.126     brouard  11435:   }else{
                   11436:     printf("End of Imach\n");
                   11437:     fprintf(ficlog,"End of Imach\n");
                   11438:   }
                   11439:   printf("See log file on %s\n",filelog);
                   11440:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  11441:   /*(void) gettimeofday(&end_time,&tzp);*/
                   11442:   rend_time = time(NULL);  
                   11443:   end_time = *localtime(&rend_time);
                   11444:   /* tml = *localtime(&end_time.tm_sec); */
                   11445:   strcpy(strtend,asctime(&end_time));
1.126     brouard  11446:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   11447:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  11448:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  11449:   
1.157     brouard  11450:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   11451:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   11452:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  11453:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   11454: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   11455:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   11456:   fclose(fichtm);
                   11457:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   11458:   fclose(fichtmcov);
                   11459:   fclose(ficgp);
                   11460:   fclose(ficlog);
                   11461:   /*------ End -----------*/
1.227     brouard  11462:   
                   11463:   
                   11464:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  11465: #ifdef WIN32
1.227     brouard  11466:   if (_chdir(pathcd) != 0)
                   11467:     printf("Can't move to directory %s!\n",path);
                   11468:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  11469: #else
1.227     brouard  11470:     if(chdir(pathcd) != 0)
                   11471:       printf("Can't move to directory %s!\n", path);
                   11472:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  11473: #endif 
1.126     brouard  11474:     printf("Current directory %s!\n",pathcd);
                   11475:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   11476:   sprintf(plotcmd,"gnuplot");
1.157     brouard  11477: #ifdef _WIN32
1.126     brouard  11478:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   11479: #endif
                   11480:   if(!stat(plotcmd,&info)){
1.158     brouard  11481:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  11482:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  11483:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  11484:     }else
                   11485:       strcpy(pplotcmd,plotcmd);
1.157     brouard  11486: #ifdef __unix
1.126     brouard  11487:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   11488:     if(!stat(plotcmd,&info)){
1.158     brouard  11489:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  11490:     }else
                   11491:       strcpy(pplotcmd,plotcmd);
                   11492: #endif
                   11493:   }else
                   11494:     strcpy(pplotcmd,plotcmd);
                   11495:   
                   11496:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  11497:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.227     brouard  11498:   
1.126     brouard  11499:   if((outcmd=system(plotcmd)) != 0){
1.158     brouard  11500:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  11501:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  11502:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150     brouard  11503:     if((outcmd=system(plotcmd)) != 0)
1.153     brouard  11504:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126     brouard  11505:   }
1.158     brouard  11506:   printf(" Successful, please wait...");
1.126     brouard  11507:   while (z[0] != 'q') {
                   11508:     /* chdir(path); */
1.154     brouard  11509:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  11510:     scanf("%s",z);
                   11511: /*     if (z[0] == 'c') system("./imach"); */
                   11512:     if (z[0] == 'e') {
1.158     brouard  11513: #ifdef __APPLE__
1.152     brouard  11514:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  11515: #elif __linux
                   11516:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  11517: #else
1.152     brouard  11518:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  11519: #endif
                   11520:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   11521:       system(pplotcmd);
1.126     brouard  11522:     }
                   11523:     else if (z[0] == 'g') system(plotcmd);
                   11524:     else if (z[0] == 'q') exit(0);
                   11525:   }
1.227     brouard  11526: end:
1.126     brouard  11527:   while (z[0] != 'q') {
1.195     brouard  11528:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  11529:     scanf("%s",z);
                   11530:   }
                   11531: }

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>