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

1.232   ! brouard     1: /* $Id: imach.c,v 1.231 2016/08/22 07:17:15 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.232   ! brouard     4:   Revision 1.231  2016/08/22 07:17:15  brouard
        !             5:   Summary: not working
        !             6: 
1.231     brouard     7:   Revision 1.230  2016/08/22 06:55:53  brouard
                      8:   Summary: Not working
                      9: 
1.230     brouard    10:   Revision 1.229  2016/07/23 09:45:53  brouard
                     11:   Summary: Completing for func too
                     12: 
1.229     brouard    13:   Revision 1.228  2016/07/22 17:45:30  brouard
                     14:   Summary: Fixing some arrays, still debugging
                     15: 
1.227     brouard    16:   Revision 1.226  2016/07/12 18:42:34  brouard
                     17:   Summary: temp
                     18: 
1.226     brouard    19:   Revision 1.225  2016/07/12 08:40:03  brouard
                     20:   Summary: saving but not running
                     21: 
1.225     brouard    22:   Revision 1.224  2016/07/01 13:16:01  brouard
                     23:   Summary: Fixes
                     24: 
1.224     brouard    25:   Revision 1.223  2016/02/19 09:23:35  brouard
                     26:   Summary: temporary
                     27: 
1.223     brouard    28:   Revision 1.222  2016/02/17 08:14:50  brouard
                     29:   Summary: Probably last 0.98 stable version 0.98r6
                     30: 
1.222     brouard    31:   Revision 1.221  2016/02/15 23:35:36  brouard
                     32:   Summary: minor bug
                     33: 
1.220     brouard    34:   Revision 1.219  2016/02/15 00:48:12  brouard
                     35:   *** empty log message ***
                     36: 
1.219     brouard    37:   Revision 1.218  2016/02/12 11:29:23  brouard
                     38:   Summary: 0.99 Back projections
                     39: 
1.218     brouard    40:   Revision 1.217  2015/12/23 17:18:31  brouard
                     41:   Summary: Experimental backcast
                     42: 
1.217     brouard    43:   Revision 1.216  2015/12/18 17:32:11  brouard
                     44:   Summary: 0.98r4 Warning and status=-2
                     45: 
                     46:   Version 0.98r4 is now:
                     47:    - displaying an error when status is -1, date of interview unknown and date of death known;
                     48:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                     49:   Older changes concerning s=-2, dating from 2005 have been supersed.
                     50: 
1.216     brouard    51:   Revision 1.215  2015/12/16 08:52:24  brouard
                     52:   Summary: 0.98r4 working
                     53: 
1.215     brouard    54:   Revision 1.214  2015/12/16 06:57:54  brouard
                     55:   Summary: temporary not working
                     56: 
1.214     brouard    57:   Revision 1.213  2015/12/11 18:22:17  brouard
                     58:   Summary: 0.98r4
                     59: 
1.213     brouard    60:   Revision 1.212  2015/11/21 12:47:24  brouard
                     61:   Summary: minor typo
                     62: 
1.212     brouard    63:   Revision 1.211  2015/11/21 12:41:11  brouard
                     64:   Summary: 0.98r3 with some graph of projected cross-sectional
                     65: 
                     66:   Author: Nicolas Brouard
                     67: 
1.211     brouard    68:   Revision 1.210  2015/11/18 17:41:20  brouard
                     69:   Summary: Start working on projected prevalences
                     70: 
1.210     brouard    71:   Revision 1.209  2015/11/17 22:12:03  brouard
                     72:   Summary: Adding ftolpl parameter
                     73:   Author: N Brouard
                     74: 
                     75:   We had difficulties to get smoothed confidence intervals. It was due
                     76:   to the period prevalence which wasn't computed accurately. The inner
                     77:   parameter ftolpl is now an outer parameter of the .imach parameter
                     78:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                     79:   computation are long.
                     80: 
1.209     brouard    81:   Revision 1.208  2015/11/17 14:31:57  brouard
                     82:   Summary: temporary
                     83: 
1.208     brouard    84:   Revision 1.207  2015/10/27 17:36:57  brouard
                     85:   *** empty log message ***
                     86: 
1.207     brouard    87:   Revision 1.206  2015/10/24 07:14:11  brouard
                     88:   *** empty log message ***
                     89: 
1.206     brouard    90:   Revision 1.205  2015/10/23 15:50:53  brouard
                     91:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                     92: 
1.205     brouard    93:   Revision 1.204  2015/10/01 16:20:26  brouard
                     94:   Summary: Some new graphs of contribution to likelihood
                     95: 
1.204     brouard    96:   Revision 1.203  2015/09/30 17:45:14  brouard
                     97:   Summary: looking at better estimation of the hessian
                     98: 
                     99:   Also a better criteria for convergence to the period prevalence And
                    100:   therefore adding the number of years needed to converge. (The
                    101:   prevalence in any alive state shold sum to one
                    102: 
1.203     brouard   103:   Revision 1.202  2015/09/22 19:45:16  brouard
                    104:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    105: 
1.202     brouard   106:   Revision 1.201  2015/09/15 17:34:58  brouard
                    107:   Summary: 0.98r0
                    108: 
                    109:   - Some new graphs like suvival functions
                    110:   - Some bugs fixed like model=1+age+V2.
                    111: 
1.201     brouard   112:   Revision 1.200  2015/09/09 16:53:55  brouard
                    113:   Summary: Big bug thanks to Flavia
                    114: 
                    115:   Even model=1+age+V2. did not work anymore
                    116: 
1.200     brouard   117:   Revision 1.199  2015/09/07 14:09:23  brouard
                    118:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    119: 
1.199     brouard   120:   Revision 1.198  2015/09/03 07:14:39  brouard
                    121:   Summary: 0.98q5 Flavia
                    122: 
1.198     brouard   123:   Revision 1.197  2015/09/01 18:24:39  brouard
                    124:   *** empty log message ***
                    125: 
1.197     brouard   126:   Revision 1.196  2015/08/18 23:17:52  brouard
                    127:   Summary: 0.98q5
                    128: 
1.196     brouard   129:   Revision 1.195  2015/08/18 16:28:39  brouard
                    130:   Summary: Adding a hack for testing purpose
                    131: 
                    132:   After reading the title, ftol and model lines, if the comment line has
                    133:   a q, starting with #q, the answer at the end of the run is quit. It
                    134:   permits to run test files in batch with ctest. The former workaround was
                    135:   $ echo q | imach foo.imach
                    136: 
1.195     brouard   137:   Revision 1.194  2015/08/18 13:32:00  brouard
                    138:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    139: 
1.194     brouard   140:   Revision 1.193  2015/08/04 07:17:42  brouard
                    141:   Summary: 0.98q4
                    142: 
1.193     brouard   143:   Revision 1.192  2015/07/16 16:49:02  brouard
                    144:   Summary: Fixing some outputs
                    145: 
1.192     brouard   146:   Revision 1.191  2015/07/14 10:00:33  brouard
                    147:   Summary: Some fixes
                    148: 
1.191     brouard   149:   Revision 1.190  2015/05/05 08:51:13  brouard
                    150:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    151: 
                    152:   Fix 1+age+.
                    153: 
1.190     brouard   154:   Revision 1.189  2015/04/30 14:45:16  brouard
                    155:   Summary: 0.98q2
                    156: 
1.189     brouard   157:   Revision 1.188  2015/04/30 08:27:53  brouard
                    158:   *** empty log message ***
                    159: 
1.188     brouard   160:   Revision 1.187  2015/04/29 09:11:15  brouard
                    161:   *** empty log message ***
                    162: 
1.187     brouard   163:   Revision 1.186  2015/04/23 12:01:52  brouard
                    164:   Summary: V1*age is working now, version 0.98q1
                    165: 
                    166:   Some codes had been disabled in order to simplify and Vn*age was
                    167:   working in the optimization phase, ie, giving correct MLE parameters,
                    168:   but, as usual, outputs were not correct and program core dumped.
                    169: 
1.186     brouard   170:   Revision 1.185  2015/03/11 13:26:42  brouard
                    171:   Summary: Inclusion of compile and links command line for Intel Compiler
                    172: 
1.185     brouard   173:   Revision 1.184  2015/03/11 11:52:39  brouard
                    174:   Summary: Back from Windows 8. Intel Compiler
                    175: 
1.184     brouard   176:   Revision 1.183  2015/03/10 20:34:32  brouard
                    177:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    178: 
                    179:   We use directest instead of original Powell test; probably no
                    180:   incidence on the results, but better justifications;
                    181:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    182:   wrong results.
                    183: 
1.183     brouard   184:   Revision 1.182  2015/02/12 08:19:57  brouard
                    185:   Summary: Trying to keep directest which seems simpler and more general
                    186:   Author: Nicolas Brouard
                    187: 
1.182     brouard   188:   Revision 1.181  2015/02/11 23:22:24  brouard
                    189:   Summary: Comments on Powell added
                    190: 
                    191:   Author:
                    192: 
1.181     brouard   193:   Revision 1.180  2015/02/11 17:33:45  brouard
                    194:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    195: 
1.180     brouard   196:   Revision 1.179  2015/01/04 09:57:06  brouard
                    197:   Summary: back to OS/X
                    198: 
1.179     brouard   199:   Revision 1.178  2015/01/04 09:35:48  brouard
                    200:   *** empty log message ***
                    201: 
1.178     brouard   202:   Revision 1.177  2015/01/03 18:40:56  brouard
                    203:   Summary: Still testing ilc32 on OSX
                    204: 
1.177     brouard   205:   Revision 1.176  2015/01/03 16:45:04  brouard
                    206:   *** empty log message ***
                    207: 
1.176     brouard   208:   Revision 1.175  2015/01/03 16:33:42  brouard
                    209:   *** empty log message ***
                    210: 
1.175     brouard   211:   Revision 1.174  2015/01/03 16:15:49  brouard
                    212:   Summary: Still in cross-compilation
                    213: 
1.174     brouard   214:   Revision 1.173  2015/01/03 12:06:26  brouard
                    215:   Summary: trying to detect cross-compilation
                    216: 
1.173     brouard   217:   Revision 1.172  2014/12/27 12:07:47  brouard
                    218:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    219: 
1.172     brouard   220:   Revision 1.171  2014/12/23 13:26:59  brouard
                    221:   Summary: Back from Visual C
                    222: 
                    223:   Still problem with utsname.h on Windows
                    224: 
1.171     brouard   225:   Revision 1.170  2014/12/23 11:17:12  brouard
                    226:   Summary: Cleaning some \%% back to %%
                    227: 
                    228:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    229: 
1.170     brouard   230:   Revision 1.169  2014/12/22 23:08:31  brouard
                    231:   Summary: 0.98p
                    232: 
                    233:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    234: 
1.169     brouard   235:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   236:   Summary: update
1.169     brouard   237: 
1.168     brouard   238:   Revision 1.167  2014/12/22 13:50:56  brouard
                    239:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    240: 
                    241:   Testing on Linux 64
                    242: 
1.167     brouard   243:   Revision 1.166  2014/12/22 11:40:47  brouard
                    244:   *** empty log message ***
                    245: 
1.166     brouard   246:   Revision 1.165  2014/12/16 11:20:36  brouard
                    247:   Summary: After compiling on Visual C
                    248: 
                    249:   * imach.c (Module): Merging 1.61 to 1.162
                    250: 
1.165     brouard   251:   Revision 1.164  2014/12/16 10:52:11  brouard
                    252:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    253: 
                    254:   * imach.c (Module): Merging 1.61 to 1.162
                    255: 
1.164     brouard   256:   Revision 1.163  2014/12/16 10:30:11  brouard
                    257:   * imach.c (Module): Merging 1.61 to 1.162
                    258: 
1.163     brouard   259:   Revision 1.162  2014/09/25 11:43:39  brouard
                    260:   Summary: temporary backup 0.99!
                    261: 
1.162     brouard   262:   Revision 1.1  2014/09/16 11:06:58  brouard
                    263:   Summary: With some code (wrong) for nlopt
                    264: 
                    265:   Author:
                    266: 
                    267:   Revision 1.161  2014/09/15 20:41:41  brouard
                    268:   Summary: Problem with macro SQR on Intel compiler
                    269: 
1.161     brouard   270:   Revision 1.160  2014/09/02 09:24:05  brouard
                    271:   *** empty log message ***
                    272: 
1.160     brouard   273:   Revision 1.159  2014/09/01 10:34:10  brouard
                    274:   Summary: WIN32
                    275:   Author: Brouard
                    276: 
1.159     brouard   277:   Revision 1.158  2014/08/27 17:11:51  brouard
                    278:   *** empty log message ***
                    279: 
1.158     brouard   280:   Revision 1.157  2014/08/27 16:26:55  brouard
                    281:   Summary: Preparing windows Visual studio version
                    282:   Author: Brouard
                    283: 
                    284:   In order to compile on Visual studio, time.h is now correct and time_t
                    285:   and tm struct should be used. difftime should be used but sometimes I
                    286:   just make the differences in raw time format (time(&now).
                    287:   Trying to suppress #ifdef LINUX
                    288:   Add xdg-open for __linux in order to open default browser.
                    289: 
1.157     brouard   290:   Revision 1.156  2014/08/25 20:10:10  brouard
                    291:   *** empty log message ***
                    292: 
1.156     brouard   293:   Revision 1.155  2014/08/25 18:32:34  brouard
                    294:   Summary: New compile, minor changes
                    295:   Author: Brouard
                    296: 
1.155     brouard   297:   Revision 1.154  2014/06/20 17:32:08  brouard
                    298:   Summary: Outputs now all graphs of convergence to period prevalence
                    299: 
1.154     brouard   300:   Revision 1.153  2014/06/20 16:45:46  brouard
                    301:   Summary: If 3 live state, convergence to period prevalence on same graph
                    302:   Author: Brouard
                    303: 
1.153     brouard   304:   Revision 1.152  2014/06/18 17:54:09  brouard
                    305:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    306: 
1.152     brouard   307:   Revision 1.151  2014/06/18 16:43:30  brouard
                    308:   *** empty log message ***
                    309: 
1.151     brouard   310:   Revision 1.150  2014/06/18 16:42:35  brouard
                    311:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    312:   Author: brouard
                    313: 
1.150     brouard   314:   Revision 1.149  2014/06/18 15:51:14  brouard
                    315:   Summary: Some fixes in parameter files errors
                    316:   Author: Nicolas Brouard
                    317: 
1.149     brouard   318:   Revision 1.148  2014/06/17 17:38:48  brouard
                    319:   Summary: Nothing new
                    320:   Author: Brouard
                    321: 
                    322:   Just a new packaging for OS/X version 0.98nS
                    323: 
1.148     brouard   324:   Revision 1.147  2014/06/16 10:33:11  brouard
                    325:   *** empty log message ***
                    326: 
1.147     brouard   327:   Revision 1.146  2014/06/16 10:20:28  brouard
                    328:   Summary: Merge
                    329:   Author: Brouard
                    330: 
                    331:   Merge, before building revised version.
                    332: 
1.146     brouard   333:   Revision 1.145  2014/06/10 21:23:15  brouard
                    334:   Summary: Debugging with valgrind
                    335:   Author: Nicolas Brouard
                    336: 
                    337:   Lot of changes in order to output the results with some covariates
                    338:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    339:   improve the code.
                    340:   No more memory valgrind error but a lot has to be done in order to
                    341:   continue the work of splitting the code into subroutines.
                    342:   Also, decodemodel has been improved. Tricode is still not
                    343:   optimal. nbcode should be improved. Documentation has been added in
                    344:   the source code.
                    345: 
1.144     brouard   346:   Revision 1.143  2014/01/26 09:45:38  brouard
                    347:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    348: 
                    349:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    350:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    351: 
1.143     brouard   352:   Revision 1.142  2014/01/26 03:57:36  brouard
                    353:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    354: 
                    355:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    356: 
1.142     brouard   357:   Revision 1.141  2014/01/26 02:42:01  brouard
                    358:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    359: 
1.141     brouard   360:   Revision 1.140  2011/09/02 10:37:54  brouard
                    361:   Summary: times.h is ok with mingw32 now.
                    362: 
1.140     brouard   363:   Revision 1.139  2010/06/14 07:50:17  brouard
                    364:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    365:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    366: 
1.139     brouard   367:   Revision 1.138  2010/04/30 18:19:40  brouard
                    368:   *** empty log message ***
                    369: 
1.138     brouard   370:   Revision 1.137  2010/04/29 18:11:38  brouard
                    371:   (Module): Checking covariates for more complex models
                    372:   than V1+V2. A lot of change to be done. Unstable.
                    373: 
1.137     brouard   374:   Revision 1.136  2010/04/26 20:30:53  brouard
                    375:   (Module): merging some libgsl code. Fixing computation
                    376:   of likelione (using inter/intrapolation if mle = 0) in order to
                    377:   get same likelihood as if mle=1.
                    378:   Some cleaning of code and comments added.
                    379: 
1.136     brouard   380:   Revision 1.135  2009/10/29 15:33:14  brouard
                    381:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    382: 
1.135     brouard   383:   Revision 1.134  2009/10/29 13:18:53  brouard
                    384:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    385: 
1.134     brouard   386:   Revision 1.133  2009/07/06 10:21:25  brouard
                    387:   just nforces
                    388: 
1.133     brouard   389:   Revision 1.132  2009/07/06 08:22:05  brouard
                    390:   Many tings
                    391: 
1.132     brouard   392:   Revision 1.131  2009/06/20 16:22:47  brouard
                    393:   Some dimensions resccaled
                    394: 
1.131     brouard   395:   Revision 1.130  2009/05/26 06:44:34  brouard
                    396:   (Module): Max Covariate is now set to 20 instead of 8. A
                    397:   lot of cleaning with variables initialized to 0. Trying to make
                    398:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    399: 
1.130     brouard   400:   Revision 1.129  2007/08/31 13:49:27  lievre
                    401:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    402: 
1.129     lievre    403:   Revision 1.128  2006/06/30 13:02:05  brouard
                    404:   (Module): Clarifications on computing e.j
                    405: 
1.128     brouard   406:   Revision 1.127  2006/04/28 18:11:50  brouard
                    407:   (Module): Yes the sum of survivors was wrong since
                    408:   imach-114 because nhstepm was no more computed in the age
                    409:   loop. Now we define nhstepma in the age loop.
                    410:   (Module): In order to speed up (in case of numerous covariates) we
                    411:   compute health expectancies (without variances) in a first step
                    412:   and then all the health expectancies with variances or standard
                    413:   deviation (needs data from the Hessian matrices) which slows the
                    414:   computation.
                    415:   In the future we should be able to stop the program is only health
                    416:   expectancies and graph are needed without standard deviations.
                    417: 
1.127     brouard   418:   Revision 1.126  2006/04/28 17:23:28  brouard
                    419:   (Module): Yes the sum of survivors was wrong since
                    420:   imach-114 because nhstepm was no more computed in the age
                    421:   loop. Now we define nhstepma in the age loop.
                    422:   Version 0.98h
                    423: 
1.126     brouard   424:   Revision 1.125  2006/04/04 15:20:31  lievre
                    425:   Errors in calculation of health expectancies. Age was not initialized.
                    426:   Forecasting file added.
                    427: 
                    428:   Revision 1.124  2006/03/22 17:13:53  lievre
                    429:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    430:   The log-likelihood is printed in the log file
                    431: 
                    432:   Revision 1.123  2006/03/20 10:52:43  brouard
                    433:   * imach.c (Module): <title> changed, corresponds to .htm file
                    434:   name. <head> headers where missing.
                    435: 
                    436:   * imach.c (Module): Weights can have a decimal point as for
                    437:   English (a comma might work with a correct LC_NUMERIC environment,
                    438:   otherwise the weight is truncated).
                    439:   Modification of warning when the covariates values are not 0 or
                    440:   1.
                    441:   Version 0.98g
                    442: 
                    443:   Revision 1.122  2006/03/20 09:45:41  brouard
                    444:   (Module): Weights can have a decimal point as for
                    445:   English (a comma might work with a correct LC_NUMERIC environment,
                    446:   otherwise the weight is truncated).
                    447:   Modification of warning when the covariates values are not 0 or
                    448:   1.
                    449:   Version 0.98g
                    450: 
                    451:   Revision 1.121  2006/03/16 17:45:01  lievre
                    452:   * imach.c (Module): Comments concerning covariates added
                    453: 
                    454:   * imach.c (Module): refinements in the computation of lli if
                    455:   status=-2 in order to have more reliable computation if stepm is
                    456:   not 1 month. Version 0.98f
                    457: 
                    458:   Revision 1.120  2006/03/16 15:10:38  lievre
                    459:   (Module): refinements in the computation of lli if
                    460:   status=-2 in order to have more reliable computation if stepm is
                    461:   not 1 month. Version 0.98f
                    462: 
                    463:   Revision 1.119  2006/03/15 17:42:26  brouard
                    464:   (Module): Bug if status = -2, the loglikelihood was
                    465:   computed as likelihood omitting the logarithm. Version O.98e
                    466: 
                    467:   Revision 1.118  2006/03/14 18:20:07  brouard
                    468:   (Module): varevsij Comments added explaining the second
                    469:   table of variances if popbased=1 .
                    470:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    471:   (Module): Function pstamp added
                    472:   (Module): Version 0.98d
                    473: 
                    474:   Revision 1.117  2006/03/14 17:16:22  brouard
                    475:   (Module): varevsij Comments added explaining the second
                    476:   table of variances if popbased=1 .
                    477:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    478:   (Module): Function pstamp added
                    479:   (Module): Version 0.98d
                    480: 
                    481:   Revision 1.116  2006/03/06 10:29:27  brouard
                    482:   (Module): Variance-covariance wrong links and
                    483:   varian-covariance of ej. is needed (Saito).
                    484: 
                    485:   Revision 1.115  2006/02/27 12:17:45  brouard
                    486:   (Module): One freematrix added in mlikeli! 0.98c
                    487: 
                    488:   Revision 1.114  2006/02/26 12:57:58  brouard
                    489:   (Module): Some improvements in processing parameter
                    490:   filename with strsep.
                    491: 
                    492:   Revision 1.113  2006/02/24 14:20:24  brouard
                    493:   (Module): Memory leaks checks with valgrind and:
                    494:   datafile was not closed, some imatrix were not freed and on matrix
                    495:   allocation too.
                    496: 
                    497:   Revision 1.112  2006/01/30 09:55:26  brouard
                    498:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    499: 
                    500:   Revision 1.111  2006/01/25 20:38:18  brouard
                    501:   (Module): Lots of cleaning and bugs added (Gompertz)
                    502:   (Module): Comments can be added in data file. Missing date values
                    503:   can be a simple dot '.'.
                    504: 
                    505:   Revision 1.110  2006/01/25 00:51:50  brouard
                    506:   (Module): Lots of cleaning and bugs added (Gompertz)
                    507: 
                    508:   Revision 1.109  2006/01/24 19:37:15  brouard
                    509:   (Module): Comments (lines starting with a #) are allowed in data.
                    510: 
                    511:   Revision 1.108  2006/01/19 18:05:42  lievre
                    512:   Gnuplot problem appeared...
                    513:   To be fixed
                    514: 
                    515:   Revision 1.107  2006/01/19 16:20:37  brouard
                    516:   Test existence of gnuplot in imach path
                    517: 
                    518:   Revision 1.106  2006/01/19 13:24:36  brouard
                    519:   Some cleaning and links added in html output
                    520: 
                    521:   Revision 1.105  2006/01/05 20:23:19  lievre
                    522:   *** empty log message ***
                    523: 
                    524:   Revision 1.104  2005/09/30 16:11:43  lievre
                    525:   (Module): sump fixed, loop imx fixed, and simplifications.
                    526:   (Module): If the status is missing at the last wave but we know
                    527:   that the person is alive, then we can code his/her status as -2
                    528:   (instead of missing=-1 in earlier versions) and his/her
                    529:   contributions to the likelihood is 1 - Prob of dying from last
                    530:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    531:   the healthy state at last known wave). Version is 0.98
                    532: 
                    533:   Revision 1.103  2005/09/30 15:54:49  lievre
                    534:   (Module): sump fixed, loop imx fixed, and simplifications.
                    535: 
                    536:   Revision 1.102  2004/09/15 17:31:30  brouard
                    537:   Add the possibility to read data file including tab characters.
                    538: 
                    539:   Revision 1.101  2004/09/15 10:38:38  brouard
                    540:   Fix on curr_time
                    541: 
                    542:   Revision 1.100  2004/07/12 18:29:06  brouard
                    543:   Add version for Mac OS X. Just define UNIX in Makefile
                    544: 
                    545:   Revision 1.99  2004/06/05 08:57:40  brouard
                    546:   *** empty log message ***
                    547: 
                    548:   Revision 1.98  2004/05/16 15:05:56  brouard
                    549:   New version 0.97 . First attempt to estimate force of mortality
                    550:   directly from the data i.e. without the need of knowing the health
                    551:   state at each age, but using a Gompertz model: log u =a + b*age .
                    552:   This is the basic analysis of mortality and should be done before any
                    553:   other analysis, in order to test if the mortality estimated from the
                    554:   cross-longitudinal survey is different from the mortality estimated
                    555:   from other sources like vital statistic data.
                    556: 
                    557:   The same imach parameter file can be used but the option for mle should be -3.
                    558: 
1.133     brouard   559:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   560:   former routines in order to include the new code within the former code.
                    561: 
                    562:   The output is very simple: only an estimate of the intercept and of
                    563:   the slope with 95% confident intervals.
                    564: 
                    565:   Current limitations:
                    566:   A) Even if you enter covariates, i.e. with the
                    567:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    568:   B) There is no computation of Life Expectancy nor Life Table.
                    569: 
                    570:   Revision 1.97  2004/02/20 13:25:42  lievre
                    571:   Version 0.96d. Population forecasting command line is (temporarily)
                    572:   suppressed.
                    573: 
                    574:   Revision 1.96  2003/07/15 15:38:55  brouard
                    575:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    576:   rewritten within the same printf. Workaround: many printfs.
                    577: 
                    578:   Revision 1.95  2003/07/08 07:54:34  brouard
                    579:   * imach.c (Repository):
                    580:   (Repository): Using imachwizard code to output a more meaningful covariance
                    581:   matrix (cov(a12,c31) instead of numbers.
                    582: 
                    583:   Revision 1.94  2003/06/27 13:00:02  brouard
                    584:   Just cleaning
                    585: 
                    586:   Revision 1.93  2003/06/25 16:33:55  brouard
                    587:   (Module): On windows (cygwin) function asctime_r doesn't
                    588:   exist so I changed back to asctime which exists.
                    589:   (Module): Version 0.96b
                    590: 
                    591:   Revision 1.92  2003/06/25 16:30:45  brouard
                    592:   (Module): On windows (cygwin) function asctime_r doesn't
                    593:   exist so I changed back to asctime which exists.
                    594: 
                    595:   Revision 1.91  2003/06/25 15:30:29  brouard
                    596:   * imach.c (Repository): Duplicated warning errors corrected.
                    597:   (Repository): Elapsed time after each iteration is now output. It
                    598:   helps to forecast when convergence will be reached. Elapsed time
                    599:   is stamped in powell.  We created a new html file for the graphs
                    600:   concerning matrix of covariance. It has extension -cov.htm.
                    601: 
                    602:   Revision 1.90  2003/06/24 12:34:15  brouard
                    603:   (Module): Some bugs corrected for windows. Also, when
                    604:   mle=-1 a template is output in file "or"mypar.txt with the design
                    605:   of the covariance matrix to be input.
                    606: 
                    607:   Revision 1.89  2003/06/24 12:30:52  brouard
                    608:   (Module): Some bugs corrected for windows. Also, when
                    609:   mle=-1 a template is output in file "or"mypar.txt with the design
                    610:   of the covariance matrix to be input.
                    611: 
                    612:   Revision 1.88  2003/06/23 17:54:56  brouard
                    613:   * 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.
                    614: 
                    615:   Revision 1.87  2003/06/18 12:26:01  brouard
                    616:   Version 0.96
                    617: 
                    618:   Revision 1.86  2003/06/17 20:04:08  brouard
                    619:   (Module): Change position of html and gnuplot routines and added
                    620:   routine fileappend.
                    621: 
                    622:   Revision 1.85  2003/06/17 13:12:43  brouard
                    623:   * imach.c (Repository): Check when date of death was earlier that
                    624:   current date of interview. It may happen when the death was just
                    625:   prior to the death. In this case, dh was negative and likelihood
                    626:   was wrong (infinity). We still send an "Error" but patch by
                    627:   assuming that the date of death was just one stepm after the
                    628:   interview.
                    629:   (Repository): Because some people have very long ID (first column)
                    630:   we changed int to long in num[] and we added a new lvector for
                    631:   memory allocation. But we also truncated to 8 characters (left
                    632:   truncation)
                    633:   (Repository): No more line truncation errors.
                    634: 
                    635:   Revision 1.84  2003/06/13 21:44:43  brouard
                    636:   * imach.c (Repository): Replace "freqsummary" at a correct
                    637:   place. It differs from routine "prevalence" which may be called
                    638:   many times. Probs is memory consuming and must be used with
                    639:   parcimony.
                    640:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    641: 
                    642:   Revision 1.83  2003/06/10 13:39:11  lievre
                    643:   *** empty log message ***
                    644: 
                    645:   Revision 1.82  2003/06/05 15:57:20  brouard
                    646:   Add log in  imach.c and  fullversion number is now printed.
                    647: 
                    648: */
                    649: /*
                    650:    Interpolated Markov Chain
                    651: 
                    652:   Short summary of the programme:
                    653:   
1.227     brouard   654:   This program computes Healthy Life Expectancies or State-specific
                    655:   (if states aren't health statuses) Expectancies from
                    656:   cross-longitudinal data. Cross-longitudinal data consist in: 
                    657: 
                    658:   -1- a first survey ("cross") where individuals from different ages
                    659:   are interviewed on their health status or degree of disability (in
                    660:   the case of a health survey which is our main interest)
                    661: 
                    662:   -2- at least a second wave of interviews ("longitudinal") which
                    663:   measure each change (if any) in individual health status.  Health
                    664:   expectancies are computed from the time spent in each health state
                    665:   according to a model. More health states you consider, more time is
                    666:   necessary to reach the Maximum Likelihood of the parameters involved
                    667:   in the model.  The simplest model is the multinomial logistic model
                    668:   where pij is the probability to be observed in state j at the second
                    669:   wave conditional to be observed in state i at the first
                    670:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                    671:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                    672:   have a more complex model than "constant and age", you should modify
                    673:   the program where the markup *Covariates have to be included here
                    674:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard   675:   convergence.
                    676: 
                    677:   The advantage of this computer programme, compared to a simple
                    678:   multinomial logistic model, is clear when the delay between waves is not
                    679:   identical for each individual. Also, if a individual missed an
                    680:   intermediate interview, the information is lost, but taken into
                    681:   account using an interpolation or extrapolation.  
                    682: 
                    683:   hPijx is the probability to be observed in state i at age x+h
                    684:   conditional to the observed state i at age x. The delay 'h' can be
                    685:   split into an exact number (nh*stepm) of unobserved intermediate
                    686:   states. This elementary transition (by month, quarter,
                    687:   semester or year) is modelled as a multinomial logistic.  The hPx
                    688:   matrix is simply the matrix product of nh*stepm elementary matrices
                    689:   and the contribution of each individual to the likelihood is simply
                    690:   hPijx.
                    691: 
                    692:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard   693:   of the life expectancies. It also computes the period (stable) prevalence.
                    694: 
                    695: Back prevalence and projections:
1.227     brouard   696: 
                    697:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                    698:    double agemaxpar, double ftolpl, int *ncvyearp, double
                    699:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                    700:    mobilavproj)
                    701: 
                    702:     Computes the back prevalence limit for any combination of
                    703:     covariate values k at any age between ageminpar and agemaxpar and
                    704:     returns it in **bprlim. In the loops,
                    705: 
                    706:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                    707:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                    708: 
                    709:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard   710:    Computes for any combination of covariates k and any age between bage and fage 
                    711:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                    712:                        oldm=oldms;savm=savms;
1.227     brouard   713: 
                    714:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
1.218     brouard   715:      Computes the transition matrix starting at age 'age' over
                    716:      'nhstepm*hstepm*stepm' months (i.e. until
                    717:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard   718:      nhstepm*hstepm matrices. 
                    719: 
                    720:      Returns p3mat[i][j][h] after calling
                    721:      p3mat[i][j][h]=matprod2(newm,
                    722:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                    723:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                    724:      oldm);
1.226     brouard   725: 
                    726: Important routines
                    727: 
                    728: - func (or funcone), computes logit (pij) distinguishing
                    729:   o fixed variables (single or product dummies or quantitative);
                    730:   o varying variables by:
                    731:    (1) wave (single, product dummies, quantitative), 
                    732:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                    733:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                    734:        % varying dummy (not done) or quantitative (not done);
                    735: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                    736:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                    737: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
                    738:   o There are 2*cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
                    739:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard   740: 
1.226     brouard   741: 
                    742:   
1.133     brouard   743:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    744:            Institut national d'études démographiques, Paris.
1.126     brouard   745:   This software have been partly granted by Euro-REVES, a concerted action
                    746:   from the European Union.
                    747:   It is copyrighted identically to a GNU software product, ie programme and
                    748:   software can be distributed freely for non commercial use. Latest version
                    749:   can be accessed at http://euroreves.ined.fr/imach .
                    750: 
                    751:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    752:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    753:   
                    754:   **********************************************************************/
                    755: /*
                    756:   main
                    757:   read parameterfile
                    758:   read datafile
                    759:   concatwav
                    760:   freqsummary
                    761:   if (mle >= 1)
                    762:     mlikeli
                    763:   print results files
                    764:   if mle==1 
                    765:      computes hessian
                    766:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    767:       begin-prev-date,...
                    768:   open gnuplot file
                    769:   open html file
1.145     brouard   770:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    771:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    772:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    773:     freexexit2 possible for memory heap.
                    774: 
                    775:   h Pij x                         | pij_nom  ficrestpij
                    776:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    777:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    778:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    779: 
                    780:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    781:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    782:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    783:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    784:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    785: 
1.126     brouard   786:   forecasting if prevfcast==1 prevforecast call prevalence()
                    787:   health expectancies
                    788:   Variance-covariance of DFLE
                    789:   prevalence()
                    790:    movingaverage()
                    791:   varevsij() 
                    792:   if popbased==1 varevsij(,popbased)
                    793:   total life expectancies
                    794:   Variance of period (stable) prevalence
                    795:  end
                    796: */
                    797: 
1.187     brouard   798: /* #define DEBUG */
                    799: /* #define DEBUGBRENT */
1.203     brouard   800: /* #define DEBUGLINMIN */
                    801: /* #define DEBUGHESS */
                    802: #define DEBUGHESSIJ
1.224     brouard   803: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard   804: #define POWELL /* Instead of NLOPT */
1.224     brouard   805: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard   806: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                    807: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard   808: 
                    809: #include <math.h>
                    810: #include <stdio.h>
                    811: #include <stdlib.h>
                    812: #include <string.h>
1.226     brouard   813: #include <ctype.h>
1.159     brouard   814: 
                    815: #ifdef _WIN32
                    816: #include <io.h>
1.172     brouard   817: #include <windows.h>
                    818: #include <tchar.h>
1.159     brouard   819: #else
1.126     brouard   820: #include <unistd.h>
1.159     brouard   821: #endif
1.126     brouard   822: 
                    823: #include <limits.h>
                    824: #include <sys/types.h>
1.171     brouard   825: 
                    826: #if defined(__GNUC__)
                    827: #include <sys/utsname.h> /* Doesn't work on Windows */
                    828: #endif
                    829: 
1.126     brouard   830: #include <sys/stat.h>
                    831: #include <errno.h>
1.159     brouard   832: /* extern int errno; */
1.126     brouard   833: 
1.157     brouard   834: /* #ifdef LINUX */
                    835: /* #include <time.h> */
                    836: /* #include "timeval.h" */
                    837: /* #else */
                    838: /* #include <sys/time.h> */
                    839: /* #endif */
                    840: 
1.126     brouard   841: #include <time.h>
                    842: 
1.136     brouard   843: #ifdef GSL
                    844: #include <gsl/gsl_errno.h>
                    845: #include <gsl/gsl_multimin.h>
                    846: #endif
                    847: 
1.167     brouard   848: 
1.162     brouard   849: #ifdef NLOPT
                    850: #include <nlopt.h>
                    851: typedef struct {
                    852:   double (* function)(double [] );
                    853: } myfunc_data ;
                    854: #endif
                    855: 
1.126     brouard   856: /* #include <libintl.h> */
                    857: /* #define _(String) gettext (String) */
                    858: 
1.141     brouard   859: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   860: 
                    861: #define GNUPLOTPROGRAM "gnuplot"
                    862: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    863: #define FILENAMELENGTH 132
                    864: 
                    865: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    866: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    867: 
1.144     brouard   868: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    869: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   870: 
                    871: #define NINTERVMAX 8
1.144     brouard   872: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    873: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    874: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197     brouard   875: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard   876: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                    877: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.126     brouard   878: #define MAXN 20000
1.144     brouard   879: #define YEARM 12. /**< Number of months per year */
1.218     brouard   880: /* #define AGESUP 130 */
                    881: #define AGESUP 150
                    882: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard   883: #define AGEBASE 40
1.194     brouard   884: #define AGEOVERFLOW 1.e20
1.164     brouard   885: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard   886: #ifdef _WIN32
                    887: #define DIRSEPARATOR '\\'
                    888: #define CHARSEPARATOR "\\"
                    889: #define ODIRSEPARATOR '/'
                    890: #else
1.126     brouard   891: #define DIRSEPARATOR '/'
                    892: #define CHARSEPARATOR "/"
                    893: #define ODIRSEPARATOR '\\'
                    894: #endif
                    895: 
1.232   ! brouard   896: /* $Id: imach.c,v 1.231 2016/08/22 07:17:15 brouard Exp $ */
1.126     brouard   897: /* $State: Exp $ */
1.196     brouard   898: #include "version.h"
                    899: char version[]=__IMACH_VERSION__;
1.224     brouard   900: 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.232   ! brouard   901: char fullversion[]="$Revision: 1.231 $ $Date: 2016/08/22 07:17:15 $"; 
1.126     brouard   902: char strstart[80];
                    903: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   904: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard   905: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard   906: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    907: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    908: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
1.225     brouard   909: int cptcovs=0; /**< cptcovs number of simple covariates in the model V2+V1 =2 */
                    910: int cptcovsnq=0; /**< cptcovsnq number of simple covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard   911: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    912: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    913: int cptcoveff=0; /* Total number of covariates to vary for printing results */
1.232   ! brouard   914: int ncovf=0; /* Total number of effective fixed covariates (dummy of quantitative) in the model */
        !           915: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy of quantitative) in the model */
        !           916: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
        !           917: 
        !           918: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard   919: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard   920: int ntveff=0; /**< ntveff number of effective time varying variables */
                    921: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard   922: int cptcov=0; /* Working variable */
1.218     brouard   923: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.126     brouard   924: int npar=NPARMAX;
                    925: int nlstate=2; /* Number of live states */
                    926: int ndeath=1; /* Number of dead states */
1.130     brouard   927: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.223     brouard   928: int  nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable */ 
1.126     brouard   929: int popbased=0;
                    930: 
                    931: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard   932: int maxwav=0; /* Maxim number of waves */
                    933: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    934: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    935: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard   936:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard   937: int mle=1, weightopt=0;
1.126     brouard   938: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    939: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    940: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    941:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard   942: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard   943: int selected(int kvar); /* Is covariate kvar selected for printing results */
                    944: 
1.130     brouard   945: double jmean=1; /* Mean space between 2 waves */
1.145     brouard   946: double **matprod2(); /* test */
1.126     brouard   947: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    948: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard   949: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                    950: 
1.136     brouard   951: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard   952: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard   953: FILE *ficlog, *ficrespow;
1.130     brouard   954: int globpr=0; /* Global variable for printing or not */
1.126     brouard   955: double fretone; /* Only one call to likelihood */
1.130     brouard   956: long ipmx=0; /* Number of contributions */
1.126     brouard   957: double sw; /* Sum of weights */
                    958: char filerespow[FILENAMELENGTH];
                    959: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                    960: FILE *ficresilk;
                    961: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                    962: FILE *ficresprobmorprev;
                    963: FILE *fichtm, *fichtmcov; /* Html File */
                    964: FILE *ficreseij;
                    965: char filerese[FILENAMELENGTH];
                    966: FILE *ficresstdeij;
                    967: char fileresstde[FILENAMELENGTH];
                    968: FILE *ficrescveij;
                    969: char filerescve[FILENAMELENGTH];
                    970: FILE  *ficresvij;
                    971: char fileresv[FILENAMELENGTH];
                    972: FILE  *ficresvpl;
                    973: char fileresvpl[FILENAMELENGTH];
                    974: char title[MAXLINE];
1.217     brouard   975: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard   976: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                    977: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                    978: char command[FILENAMELENGTH];
                    979: int  outcmd=0;
                    980: 
1.217     brouard   981: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard   982: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard   983: char filelog[FILENAMELENGTH]; /* Log file */
                    984: char filerest[FILENAMELENGTH];
                    985: char fileregp[FILENAMELENGTH];
                    986: char popfile[FILENAMELENGTH];
                    987: 
                    988: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                    989: 
1.157     brouard   990: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                    991: /* struct timezone tzp; */
                    992: /* extern int gettimeofday(); */
                    993: struct tm tml, *gmtime(), *localtime();
                    994: 
                    995: extern time_t time();
                    996: 
                    997: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                    998: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                    999: struct tm tm;
                   1000: 
1.126     brouard  1001: char strcurr[80], strfor[80];
                   1002: 
                   1003: char *endptr;
                   1004: long lval;
                   1005: double dval;
                   1006: 
                   1007: #define NR_END 1
                   1008: #define FREE_ARG char*
                   1009: #define FTOL 1.0e-10
                   1010: 
                   1011: #define NRANSI 
                   1012: #define ITMAX 200 
                   1013: 
                   1014: #define TOL 2.0e-4 
                   1015: 
                   1016: #define CGOLD 0.3819660 
                   1017: #define ZEPS 1.0e-10 
                   1018: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1019: 
                   1020: #define GOLD 1.618034 
                   1021: #define GLIMIT 100.0 
                   1022: #define TINY 1.0e-20 
                   1023: 
                   1024: static double maxarg1,maxarg2;
                   1025: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1026: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1027:   
                   1028: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1029: #define rint(a) floor(a+0.5)
1.166     brouard  1030: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1031: #define mytinydouble 1.0e-16
1.166     brouard  1032: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1033: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1034: /* static double dsqrarg; */
                   1035: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1036: static double sqrarg;
                   1037: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1038: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1039: int agegomp= AGEGOMP;
                   1040: 
                   1041: int imx; 
                   1042: int stepm=1;
                   1043: /* Stepm, step in month: minimum step interpolation*/
                   1044: 
                   1045: int estepm;
                   1046: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1047: 
                   1048: int m,nb;
                   1049: long *num;
1.197     brouard  1050: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1051: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1052:                   covariate for which somebody answered excluding 
                   1053:                   undefined. Usually 2: 0 and 1. */
                   1054: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1055:                             covariate for which somebody answered including 
                   1056:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1057: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1058: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1059: double ***mobaverage, ***mobaverages; /* New global variable */
1.126     brouard  1060: double *ageexmed,*agecens;
                   1061: double dateintmean=0;
                   1062: 
                   1063: double *weight;
                   1064: int **s; /* Status */
1.141     brouard  1065: double *agedc;
1.145     brouard  1066: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1067:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1068:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.225     brouard  1069: double **coqvar; /* Fixed quantitative covariate iqv */
                   1070: double ***cotvar; /* Time varying covariate itv */
                   1071: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1072: double  idx; 
                   1073: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.232   ! brouard  1074: 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 */
        !          1075: 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 */
        !          1076: 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 */
        !          1077: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
        !          1078: 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 */
        !          1079: 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  1080: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1081: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1082: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1083: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1084: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1085: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1086: 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 */
                   1087: 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 */
                   1088: 
1.230     brouard  1089: int *Tvarsel; /**< Selected covariates for output */
                   1090: double *Tvalsel; /**< Selected modality value of covariate for output */
1.226     brouard  1091: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.227     brouard  1092: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1093: 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.197     brouard  1094: int *Tage;
1.227     brouard  1095: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1096: 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  1097: 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*/ 
                   1098: 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  1099: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1100: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1101: int **Tvard;
                   1102: int *Tprod;/**< Gives the k position of the k1 product */
                   1103: int *Tposprod; /**< Gives the k1 product from the k position */
                   1104: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   1105:    if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
                   1106:    Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
                   1107: */
                   1108: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1109: double *lsurv, *lpop, *tpop;
                   1110: 
1.231     brouard  1111: #define FD 1; /* Fixed dummy covariate */
                   1112: #define FQ 2; /* Fixed quantitative covariate */
                   1113: #define FP 3; /* Fixed product covariate */
                   1114: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1115: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1116: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1117: #define VD 10; /* Varying dummy covariate */
                   1118: #define VQ 11; /* Varying quantitative covariate */
                   1119: #define VP 12; /* Varying product covariate */
                   1120: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1121: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1122: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1123: #define APFD 16; /* Age product * fixed dummy covariate */
                   1124: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1125: #define APVD 18; /* Age product * varying dummy covariate */
                   1126: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1127: 
                   1128: #define FTYPE 1; /* Fixed covariate */
                   1129: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1130: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1131: 
                   1132: struct kmodel{
                   1133:        int maintype; /* main type */
                   1134:        int subtype; /* subtype */
                   1135: };
                   1136: struct kmodel modell[NCOVMAX];
                   1137: 
1.143     brouard  1138: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1139: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1140: 
                   1141: /**************** split *************************/
                   1142: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1143: {
                   1144:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1145:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1146:   */ 
                   1147:   char *ss;                            /* pointer */
1.186     brouard  1148:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1149: 
                   1150:   l1 = strlen(path );                  /* length of path */
                   1151:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1152:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1153:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1154:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1155:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1156:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1157:     /* get current working directory */
                   1158:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1159: #ifdef WIN32
                   1160:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1161: #else
                   1162:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1163: #endif
1.126     brouard  1164:       return( GLOCK_ERROR_GETCWD );
                   1165:     }
                   1166:     /* got dirc from getcwd*/
                   1167:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1168:   } else {                             /* strip directory from path */
1.126     brouard  1169:     ss++;                              /* after this, the filename */
                   1170:     l2 = strlen( ss );                 /* length of filename */
                   1171:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1172:     strcpy( name, ss );                /* save file name */
                   1173:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1174:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1175:     printf(" DIRC2 = %s \n",dirc);
                   1176:   }
                   1177:   /* We add a separator at the end of dirc if not exists */
                   1178:   l1 = strlen( dirc );                 /* length of directory */
                   1179:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1180:     dirc[l1] =  DIRSEPARATOR;
                   1181:     dirc[l1+1] = 0; 
                   1182:     printf(" DIRC3 = %s \n",dirc);
                   1183:   }
                   1184:   ss = strrchr( name, '.' );           /* find last / */
                   1185:   if (ss >0){
                   1186:     ss++;
                   1187:     strcpy(ext,ss);                    /* save extension */
                   1188:     l1= strlen( name);
                   1189:     l2= strlen(ss)+1;
                   1190:     strncpy( finame, name, l1-l2);
                   1191:     finame[l1-l2]= 0;
                   1192:   }
                   1193: 
                   1194:   return( 0 );                         /* we're done */
                   1195: }
                   1196: 
                   1197: 
                   1198: /******************************************/
                   1199: 
                   1200: void replace_back_to_slash(char *s, char*t)
                   1201: {
                   1202:   int i;
                   1203:   int lg=0;
                   1204:   i=0;
                   1205:   lg=strlen(t);
                   1206:   for(i=0; i<= lg; i++) {
                   1207:     (s[i] = t[i]);
                   1208:     if (t[i]== '\\') s[i]='/';
                   1209:   }
                   1210: }
                   1211: 
1.132     brouard  1212: char *trimbb(char *out, char *in)
1.137     brouard  1213: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1214:   char *s;
                   1215:   s=out;
                   1216:   while (*in != '\0'){
1.137     brouard  1217:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1218:       in++;
                   1219:     }
                   1220:     *out++ = *in++;
                   1221:   }
                   1222:   *out='\0';
                   1223:   return s;
                   1224: }
                   1225: 
1.187     brouard  1226: /* char *substrchaine(char *out, char *in, char *chain) */
                   1227: /* { */
                   1228: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1229: /*   char *s, *t; */
                   1230: /*   t=in;s=out; */
                   1231: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1232: /*     *out++ = *in++; */
                   1233: /*   } */
                   1234: 
                   1235: /*   /\* *in matches *chain *\/ */
                   1236: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1237: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1238: /*   } */
                   1239: /*   in--; chain--; */
                   1240: /*   while ( (*in != '\0')){ */
                   1241: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1242: /*     *out++ = *in++; */
                   1243: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1244: /*   } */
                   1245: /*   *out='\0'; */
                   1246: /*   out=s; */
                   1247: /*   return out; */
                   1248: /* } */
                   1249: char *substrchaine(char *out, char *in, char *chain)
                   1250: {
                   1251:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1252:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1253: 
                   1254:   char *strloc;
                   1255: 
                   1256:   strcpy (out, in); 
                   1257:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1258:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1259:   if(strloc != NULL){ 
                   1260:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1261:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1262:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1263:   }
                   1264:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1265:   return out;
                   1266: }
                   1267: 
                   1268: 
1.145     brouard  1269: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1270: {
1.187     brouard  1271:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1272:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187     brouard  1273:      gives blocc="abcdef" and alocc="ghi2j".
1.145     brouard  1274:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1275:   */
1.160     brouard  1276:   char *s, *t;
1.145     brouard  1277:   t=in;s=in;
                   1278:   while ((*in != occ) && (*in != '\0')){
                   1279:     *alocc++ = *in++;
                   1280:   }
                   1281:   if( *in == occ){
                   1282:     *(alocc)='\0';
                   1283:     s=++in;
                   1284:   }
                   1285:  
                   1286:   if (s == t) {/* occ not found */
                   1287:     *(alocc-(in-s))='\0';
                   1288:     in=s;
                   1289:   }
                   1290:   while ( *in != '\0'){
                   1291:     *blocc++ = *in++;
                   1292:   }
                   1293: 
                   1294:   *blocc='\0';
                   1295:   return t;
                   1296: }
1.137     brouard  1297: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1298: {
1.187     brouard  1299:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1300:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1301:      gives blocc="abcdef2ghi" and alocc="j".
                   1302:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1303:   */
                   1304:   char *s, *t;
                   1305:   t=in;s=in;
                   1306:   while (*in != '\0'){
                   1307:     while( *in == occ){
                   1308:       *blocc++ = *in++;
                   1309:       s=in;
                   1310:     }
                   1311:     *blocc++ = *in++;
                   1312:   }
                   1313:   if (s == t) /* occ not found */
                   1314:     *(blocc-(in-s))='\0';
                   1315:   else
                   1316:     *(blocc-(in-s)-1)='\0';
                   1317:   in=s;
                   1318:   while ( *in != '\0'){
                   1319:     *alocc++ = *in++;
                   1320:   }
                   1321: 
                   1322:   *alocc='\0';
                   1323:   return s;
                   1324: }
                   1325: 
1.126     brouard  1326: int nbocc(char *s, char occ)
                   1327: {
                   1328:   int i,j=0;
                   1329:   int lg=20;
                   1330:   i=0;
                   1331:   lg=strlen(s);
                   1332:   for(i=0; i<= lg; i++) {
                   1333:   if  (s[i] == occ ) j++;
                   1334:   }
                   1335:   return j;
                   1336: }
                   1337: 
1.137     brouard  1338: /* void cutv(char *u,char *v, char*t, char occ) */
                   1339: /* { */
                   1340: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1341: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1342: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1343: /*   int i,lg,j,p=0; */
                   1344: /*   i=0; */
                   1345: /*   lg=strlen(t); */
                   1346: /*   for(j=0; j<=lg-1; j++) { */
                   1347: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1348: /*   } */
1.126     brouard  1349: 
1.137     brouard  1350: /*   for(j=0; j<p; j++) { */
                   1351: /*     (u[j] = t[j]); */
                   1352: /*   } */
                   1353: /*      u[p]='\0'; */
1.126     brouard  1354: 
1.137     brouard  1355: /*    for(j=0; j<= lg; j++) { */
                   1356: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1357: /*   } */
                   1358: /* } */
1.126     brouard  1359: 
1.160     brouard  1360: #ifdef _WIN32
                   1361: char * strsep(char **pp, const char *delim)
                   1362: {
                   1363:   char *p, *q;
                   1364:          
                   1365:   if ((p = *pp) == NULL)
                   1366:     return 0;
                   1367:   if ((q = strpbrk (p, delim)) != NULL)
                   1368:   {
                   1369:     *pp = q + 1;
                   1370:     *q = '\0';
                   1371:   }
                   1372:   else
                   1373:     *pp = 0;
                   1374:   return p;
                   1375: }
                   1376: #endif
                   1377: 
1.126     brouard  1378: /********************** nrerror ********************/
                   1379: 
                   1380: void nrerror(char error_text[])
                   1381: {
                   1382:   fprintf(stderr,"ERREUR ...\n");
                   1383:   fprintf(stderr,"%s\n",error_text);
                   1384:   exit(EXIT_FAILURE);
                   1385: }
                   1386: /*********************** vector *******************/
                   1387: double *vector(int nl, int nh)
                   1388: {
                   1389:   double *v;
                   1390:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1391:   if (!v) nrerror("allocation failure in vector");
                   1392:   return v-nl+NR_END;
                   1393: }
                   1394: 
                   1395: /************************ free vector ******************/
                   1396: void free_vector(double*v, int nl, int nh)
                   1397: {
                   1398:   free((FREE_ARG)(v+nl-NR_END));
                   1399: }
                   1400: 
                   1401: /************************ivector *******************************/
                   1402: int *ivector(long nl,long nh)
                   1403: {
                   1404:   int *v;
                   1405:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1406:   if (!v) nrerror("allocation failure in ivector");
                   1407:   return v-nl+NR_END;
                   1408: }
                   1409: 
                   1410: /******************free ivector **************************/
                   1411: void free_ivector(int *v, long nl, long nh)
                   1412: {
                   1413:   free((FREE_ARG)(v+nl-NR_END));
                   1414: }
                   1415: 
                   1416: /************************lvector *******************************/
                   1417: long *lvector(long nl,long nh)
                   1418: {
                   1419:   long *v;
                   1420:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1421:   if (!v) nrerror("allocation failure in ivector");
                   1422:   return v-nl+NR_END;
                   1423: }
                   1424: 
                   1425: /******************free lvector **************************/
                   1426: void free_lvector(long *v, long nl, long nh)
                   1427: {
                   1428:   free((FREE_ARG)(v+nl-NR_END));
                   1429: }
                   1430: 
                   1431: /******************* imatrix *******************************/
                   1432: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1433:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1434: { 
                   1435:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1436:   int **m; 
                   1437:   
                   1438:   /* allocate pointers to rows */ 
                   1439:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1440:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1441:   m += NR_END; 
                   1442:   m -= nrl; 
                   1443:   
                   1444:   
                   1445:   /* allocate rows and set pointers to them */ 
                   1446:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1447:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1448:   m[nrl] += NR_END; 
                   1449:   m[nrl] -= ncl; 
                   1450:   
                   1451:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1452:   
                   1453:   /* return pointer to array of pointers to rows */ 
                   1454:   return m; 
                   1455: } 
                   1456: 
                   1457: /****************** free_imatrix *************************/
                   1458: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1459:       int **m;
                   1460:       long nch,ncl,nrh,nrl; 
                   1461:      /* free an int matrix allocated by imatrix() */ 
                   1462: { 
                   1463:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1464:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1465: } 
                   1466: 
                   1467: /******************* matrix *******************************/
                   1468: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1469: {
                   1470:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1471:   double **m;
                   1472: 
                   1473:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1474:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1475:   m += NR_END;
                   1476:   m -= nrl;
                   1477: 
                   1478:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1479:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1480:   m[nrl] += NR_END;
                   1481:   m[nrl] -= ncl;
                   1482: 
                   1483:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1484:   return m;
1.145     brouard  1485:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1486: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1487: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1488:    */
                   1489: }
                   1490: 
                   1491: /*************************free matrix ************************/
                   1492: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1493: {
                   1494:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1495:   free((FREE_ARG)(m+nrl-NR_END));
                   1496: }
                   1497: 
                   1498: /******************* ma3x *******************************/
                   1499: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1500: {
                   1501:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1502:   double ***m;
                   1503: 
                   1504:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1505:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1506:   m += NR_END;
                   1507:   m -= nrl;
                   1508: 
                   1509:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1510:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1511:   m[nrl] += NR_END;
                   1512:   m[nrl] -= ncl;
                   1513: 
                   1514:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1515: 
                   1516:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1517:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1518:   m[nrl][ncl] += NR_END;
                   1519:   m[nrl][ncl] -= nll;
                   1520:   for (j=ncl+1; j<=nch; j++) 
                   1521:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1522:   
                   1523:   for (i=nrl+1; i<=nrh; i++) {
                   1524:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1525:     for (j=ncl+1; j<=nch; j++) 
                   1526:       m[i][j]=m[i][j-1]+nlay;
                   1527:   }
                   1528:   return m; 
                   1529:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1530:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1531:   */
                   1532: }
                   1533: 
                   1534: /*************************free ma3x ************************/
                   1535: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1536: {
                   1537:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1538:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1539:   free((FREE_ARG)(m+nrl-NR_END));
                   1540: }
                   1541: 
                   1542: /*************** function subdirf ***********/
                   1543: char *subdirf(char fileres[])
                   1544: {
                   1545:   /* Caution optionfilefiname is hidden */
                   1546:   strcpy(tmpout,optionfilefiname);
                   1547:   strcat(tmpout,"/"); /* Add to the right */
                   1548:   strcat(tmpout,fileres);
                   1549:   return tmpout;
                   1550: }
                   1551: 
                   1552: /*************** function subdirf2 ***********/
                   1553: char *subdirf2(char fileres[], char *preop)
                   1554: {
                   1555:   
                   1556:   /* Caution optionfilefiname is hidden */
                   1557:   strcpy(tmpout,optionfilefiname);
                   1558:   strcat(tmpout,"/");
                   1559:   strcat(tmpout,preop);
                   1560:   strcat(tmpout,fileres);
                   1561:   return tmpout;
                   1562: }
                   1563: 
                   1564: /*************** function subdirf3 ***********/
                   1565: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1566: {
                   1567:   
                   1568:   /* Caution optionfilefiname is hidden */
                   1569:   strcpy(tmpout,optionfilefiname);
                   1570:   strcat(tmpout,"/");
                   1571:   strcat(tmpout,preop);
                   1572:   strcat(tmpout,preop2);
                   1573:   strcat(tmpout,fileres);
                   1574:   return tmpout;
                   1575: }
1.213     brouard  1576:  
                   1577: /*************** function subdirfext ***********/
                   1578: char *subdirfext(char fileres[], char *preop, char *postop)
                   1579: {
                   1580:   
                   1581:   strcpy(tmpout,preop);
                   1582:   strcat(tmpout,fileres);
                   1583:   strcat(tmpout,postop);
                   1584:   return tmpout;
                   1585: }
1.126     brouard  1586: 
1.213     brouard  1587: /*************** function subdirfext3 ***********/
                   1588: char *subdirfext3(char fileres[], char *preop, char *postop)
                   1589: {
                   1590:   
                   1591:   /* Caution optionfilefiname is hidden */
                   1592:   strcpy(tmpout,optionfilefiname);
                   1593:   strcat(tmpout,"/");
                   1594:   strcat(tmpout,preop);
                   1595:   strcat(tmpout,fileres);
                   1596:   strcat(tmpout,postop);
                   1597:   return tmpout;
                   1598: }
                   1599:  
1.162     brouard  1600: char *asc_diff_time(long time_sec, char ascdiff[])
                   1601: {
                   1602:   long sec_left, days, hours, minutes;
                   1603:   days = (time_sec) / (60*60*24);
                   1604:   sec_left = (time_sec) % (60*60*24);
                   1605:   hours = (sec_left) / (60*60) ;
                   1606:   sec_left = (sec_left) %(60*60);
                   1607:   minutes = (sec_left) /60;
                   1608:   sec_left = (sec_left) % (60);
                   1609:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1610:   return ascdiff;
                   1611: }
                   1612: 
1.126     brouard  1613: /***************** f1dim *************************/
                   1614: extern int ncom; 
                   1615: extern double *pcom,*xicom;
                   1616: extern double (*nrfunc)(double []); 
                   1617:  
                   1618: double f1dim(double x) 
                   1619: { 
                   1620:   int j; 
                   1621:   double f;
                   1622:   double *xt; 
                   1623:  
                   1624:   xt=vector(1,ncom); 
                   1625:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1626:   f=(*nrfunc)(xt); 
                   1627:   free_vector(xt,1,ncom); 
                   1628:   return f; 
                   1629: } 
                   1630: 
                   1631: /*****************brent *************************/
                   1632: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1633: {
                   1634:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1635:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1636:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1637:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1638:    * returned function value. 
                   1639:   */
1.126     brouard  1640:   int iter; 
                   1641:   double a,b,d,etemp;
1.159     brouard  1642:   double fu=0,fv,fw,fx;
1.164     brouard  1643:   double ftemp=0.;
1.126     brouard  1644:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1645:   double e=0.0; 
                   1646:  
                   1647:   a=(ax < cx ? ax : cx); 
                   1648:   b=(ax > cx ? ax : cx); 
                   1649:   x=w=v=bx; 
                   1650:   fw=fv=fx=(*f)(x); 
                   1651:   for (iter=1;iter<=ITMAX;iter++) { 
                   1652:     xm=0.5*(a+b); 
                   1653:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1654:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1655:     printf(".");fflush(stdout);
                   1656:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1657: #ifdef DEBUGBRENT
1.126     brouard  1658:     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);
                   1659:     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);
                   1660:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1661: #endif
                   1662:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1663:       *xmin=x; 
                   1664:       return fx; 
                   1665:     } 
                   1666:     ftemp=fu;
                   1667:     if (fabs(e) > tol1) { 
                   1668:       r=(x-w)*(fx-fv); 
                   1669:       q=(x-v)*(fx-fw); 
                   1670:       p=(x-v)*q-(x-w)*r; 
                   1671:       q=2.0*(q-r); 
                   1672:       if (q > 0.0) p = -p; 
                   1673:       q=fabs(q); 
                   1674:       etemp=e; 
                   1675:       e=d; 
                   1676:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  1677:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  1678:       else { 
1.224     brouard  1679:                                d=p/q; 
                   1680:                                u=x+d; 
                   1681:                                if (u-a < tol2 || b-u < tol2) 
                   1682:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  1683:       } 
                   1684:     } else { 
                   1685:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1686:     } 
                   1687:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1688:     fu=(*f)(u); 
                   1689:     if (fu <= fx) { 
                   1690:       if (u >= x) a=x; else b=x; 
                   1691:       SHFT(v,w,x,u) 
1.183     brouard  1692:       SHFT(fv,fw,fx,fu) 
                   1693:     } else { 
                   1694:       if (u < x) a=u; else b=u; 
                   1695:       if (fu <= fw || w == x) { 
1.224     brouard  1696:                                v=w; 
                   1697:                                w=u; 
                   1698:                                fv=fw; 
                   1699:                                fw=fu; 
1.183     brouard  1700:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  1701:                                v=u; 
                   1702:                                fv=fu; 
1.183     brouard  1703:       } 
                   1704:     } 
1.126     brouard  1705:   } 
                   1706:   nrerror("Too many iterations in brent"); 
                   1707:   *xmin=x; 
                   1708:   return fx; 
                   1709: } 
                   1710: 
                   1711: /****************** mnbrak ***********************/
                   1712: 
                   1713: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1714:            double (*func)(double)) 
1.183     brouard  1715: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1716: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1717: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1718: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1719:    */
1.126     brouard  1720:   double ulim,u,r,q, dum;
                   1721:   double fu; 
1.187     brouard  1722: 
                   1723:   double scale=10.;
                   1724:   int iterscale=0;
                   1725: 
                   1726:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   1727:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   1728: 
                   1729: 
                   1730:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   1731:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   1732:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   1733:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   1734:   /* } */
                   1735: 
1.126     brouard  1736:   if (*fb > *fa) { 
                   1737:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  1738:     SHFT(dum,*fb,*fa,dum) 
                   1739:   } 
1.126     brouard  1740:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1741:   *fc=(*func)(*cx); 
1.183     brouard  1742: #ifdef DEBUG
1.224     brouard  1743:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   1744:   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  1745: #endif
1.224     brouard  1746:   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  1747:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  1748:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  1749:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  1750:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1751:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   1752:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  1753:       fu=(*func)(u); 
1.163     brouard  1754: #ifdef DEBUG
                   1755:       /* f(x)=A(x-u)**2+f(u) */
                   1756:       double A, fparabu; 
                   1757:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1758:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  1759:       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);
                   1760:       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  1761:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   1762:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   1763:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   1764:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  1765: #endif 
1.184     brouard  1766: #ifdef MNBRAKORIGINAL
1.183     brouard  1767: #else
1.191     brouard  1768: /*       if (fu > *fc) { */
                   1769: /* #ifdef DEBUG */
                   1770: /*       printf("mnbrak4  fu > fc \n"); */
                   1771: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   1772: /* #endif */
                   1773: /*     /\* 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 *\\/  *\/ */
                   1774: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   1775: /*     dum=u; /\* Shifting c and u *\/ */
                   1776: /*     u = *cx; */
                   1777: /*     *cx = dum; */
                   1778: /*     dum = fu; */
                   1779: /*     fu = *fc; */
                   1780: /*     *fc =dum; */
                   1781: /*       } else { /\* end *\/ */
                   1782: /* #ifdef DEBUG */
                   1783: /*       printf("mnbrak3  fu < fc \n"); */
                   1784: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   1785: /* #endif */
                   1786: /*     dum=u; /\* Shifting c and u *\/ */
                   1787: /*     u = *cx; */
                   1788: /*     *cx = dum; */
                   1789: /*     dum = fu; */
                   1790: /*     fu = *fc; */
                   1791: /*     *fc =dum; */
                   1792: /*       } */
1.224     brouard  1793: #ifdef DEBUGMNBRAK
                   1794:                 double A, fparabu; 
                   1795:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1796:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   1797:      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);
                   1798:      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  1799: #endif
1.191     brouard  1800:       dum=u; /* Shifting c and u */
                   1801:       u = *cx;
                   1802:       *cx = dum;
                   1803:       dum = fu;
                   1804:       fu = *fc;
                   1805:       *fc =dum;
1.183     brouard  1806: #endif
1.162     brouard  1807:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  1808: #ifdef DEBUG
1.224     brouard  1809:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   1810:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  1811: #endif
1.126     brouard  1812:       fu=(*func)(u); 
                   1813:       if (fu < *fc) { 
1.183     brouard  1814: #ifdef DEBUG
1.224     brouard  1815:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   1816:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   1817: #endif
                   1818:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   1819:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   1820: #ifdef DEBUG
                   1821:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  1822: #endif
                   1823:       } 
1.162     brouard  1824:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  1825: #ifdef DEBUG
1.224     brouard  1826:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   1827:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  1828: #endif
1.126     brouard  1829:       u=ulim; 
                   1830:       fu=(*func)(u); 
1.183     brouard  1831:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   1832: #ifdef DEBUG
1.224     brouard  1833:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   1834:       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  1835: #endif
1.126     brouard  1836:       u=(*cx)+GOLD*(*cx-*bx); 
                   1837:       fu=(*func)(u); 
1.224     brouard  1838: #ifdef DEBUG
                   1839:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   1840:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   1841: #endif
1.183     brouard  1842:     } /* end tests */
1.126     brouard  1843:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  1844:     SHFT(*fa,*fb,*fc,fu) 
                   1845: #ifdef DEBUG
1.224     brouard  1846:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   1847:       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  1848: #endif
                   1849:   } /* 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  1850: } 
                   1851: 
                   1852: /*************** linmin ************************/
1.162     brouard  1853: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   1854: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   1855: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   1856: the value of func at the returned location p . This is actually all accomplished by calling the
                   1857: routines mnbrak and brent .*/
1.126     brouard  1858: int ncom; 
                   1859: double *pcom,*xicom;
                   1860: double (*nrfunc)(double []); 
                   1861:  
1.224     brouard  1862: #ifdef LINMINORIGINAL
1.126     brouard  1863: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  1864: #else
                   1865: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   1866: #endif
1.126     brouard  1867: { 
                   1868:   double brent(double ax, double bx, double cx, 
                   1869:               double (*f)(double), double tol, double *xmin); 
                   1870:   double f1dim(double x); 
                   1871:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1872:              double *fc, double (*func)(double)); 
                   1873:   int j; 
                   1874:   double xx,xmin,bx,ax; 
                   1875:   double fx,fb,fa;
1.187     brouard  1876: 
1.203     brouard  1877: #ifdef LINMINORIGINAL
                   1878: #else
                   1879:   double scale=10., axs, xxs; /* Scale added for infinity */
                   1880: #endif
                   1881:   
1.126     brouard  1882:   ncom=n; 
                   1883:   pcom=vector(1,n); 
                   1884:   xicom=vector(1,n); 
                   1885:   nrfunc=func; 
                   1886:   for (j=1;j<=n;j++) { 
                   1887:     pcom[j]=p[j]; 
1.202     brouard  1888:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  1889:   } 
1.187     brouard  1890: 
1.203     brouard  1891: #ifdef LINMINORIGINAL
                   1892:   xx=1.;
                   1893: #else
                   1894:   axs=0.0;
                   1895:   xxs=1.;
                   1896:   do{
                   1897:     xx= xxs;
                   1898: #endif
1.187     brouard  1899:     ax=0.;
                   1900:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   1901:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   1902:     /* 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))   */
                   1903:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   1904:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   1905:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   1906:     /* 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  1907: #ifdef LINMINORIGINAL
                   1908: #else
                   1909:     if (fx != fx){
1.224     brouard  1910:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   1911:                        printf("|");
                   1912:                        fprintf(ficlog,"|");
1.203     brouard  1913: #ifdef DEBUGLINMIN
1.224     brouard  1914:                        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  1915: #endif
                   1916:     }
1.224     brouard  1917:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  1918: #endif
                   1919:   
1.191     brouard  1920: #ifdef DEBUGLINMIN
                   1921:   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  1922:   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  1923: #endif
1.224     brouard  1924: #ifdef LINMINORIGINAL
                   1925: #else
                   1926:        if(fb == fx){ /* Flat function in the direction */
                   1927:                xmin=xx;
                   1928:     *flat=1;
                   1929:        }else{
                   1930:     *flat=0;
                   1931: #endif
                   1932:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  1933:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   1934:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   1935:   /* fmin = f(p[j] + xmin * xi[j]) */
                   1936:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   1937:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  1938: #ifdef DEBUG
1.224     brouard  1939:   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);
                   1940:   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);
                   1941: #endif
                   1942: #ifdef LINMINORIGINAL
                   1943: #else
                   1944:                        }
1.126     brouard  1945: #endif
1.191     brouard  1946: #ifdef DEBUGLINMIN
                   1947:   printf("linmin end ");
1.202     brouard  1948:   fprintf(ficlog,"linmin end ");
1.191     brouard  1949: #endif
1.126     brouard  1950:   for (j=1;j<=n;j++) { 
1.203     brouard  1951: #ifdef LINMINORIGINAL
                   1952:     xi[j] *= xmin; 
                   1953: #else
                   1954: #ifdef DEBUGLINMIN
                   1955:     if(xxs <1.0)
                   1956:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   1957: #endif
                   1958:     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) */
                   1959: #ifdef DEBUGLINMIN
                   1960:     if(xxs <1.0)
                   1961:       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 );
                   1962: #endif
                   1963: #endif
1.187     brouard  1964:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  1965:   } 
1.191     brouard  1966: #ifdef DEBUGLINMIN
1.203     brouard  1967:   printf("\n");
1.191     brouard  1968:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  1969:   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  1970:   for (j=1;j<=n;j++) { 
1.202     brouard  1971:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   1972:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   1973:     if(j % ncovmodel == 0){
1.191     brouard  1974:       printf("\n");
1.202     brouard  1975:       fprintf(ficlog,"\n");
                   1976:     }
1.191     brouard  1977:   }
1.203     brouard  1978: #else
1.191     brouard  1979: #endif
1.126     brouard  1980:   free_vector(xicom,1,n); 
                   1981:   free_vector(pcom,1,n); 
                   1982: } 
                   1983: 
                   1984: 
                   1985: /*************** powell ************************/
1.162     brouard  1986: /*
                   1987: Minimization of a function func of n variables. Input consists of an initial starting point
                   1988: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   1989: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   1990: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   1991: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   1992: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   1993:  */
1.224     brouard  1994: #ifdef LINMINORIGINAL
                   1995: #else
                   1996:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  1997:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  1998: #endif
1.126     brouard  1999: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2000:            double (*func)(double [])) 
                   2001: { 
1.224     brouard  2002: #ifdef LINMINORIGINAL
                   2003:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2004:              double (*func)(double [])); 
1.224     brouard  2005: #else 
                   2006:  void linmin(double p[], double xi[], int n, double *fret, 
                   2007:                                                 double (*func)(double []),int *flat); 
                   2008: #endif
1.126     brouard  2009:   int i,ibig,j; 
                   2010:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2011:   double directest;
1.126     brouard  2012:   double fp,fptt;
                   2013:   double *xits;
                   2014:   int niterf, itmp;
1.224     brouard  2015: #ifdef LINMINORIGINAL
                   2016: #else
                   2017: 
                   2018:   flatdir=ivector(1,n); 
                   2019:   for (j=1;j<=n;j++) flatdir[j]=0; 
                   2020: #endif
1.126     brouard  2021: 
                   2022:   pt=vector(1,n); 
                   2023:   ptt=vector(1,n); 
                   2024:   xit=vector(1,n); 
                   2025:   xits=vector(1,n); 
                   2026:   *fret=(*func)(p); 
                   2027:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  2028:   rcurr_time = time(NULL);  
1.126     brouard  2029:   for (*iter=1;;++(*iter)) { 
1.187     brouard  2030:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  2031:     ibig=0; 
                   2032:     del=0.0; 
1.157     brouard  2033:     rlast_time=rcurr_time;
                   2034:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2035:     rcurr_time = time(NULL);  
                   2036:     curr_time = *localtime(&rcurr_time);
                   2037:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   2038:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   2039: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  2040:     for (i=1;i<=n;i++) {
1.126     brouard  2041:       printf(" %d %.12f",i, p[i]);
                   2042:       fprintf(ficlog," %d %.12lf",i, p[i]);
                   2043:       fprintf(ficrespow," %.12lf", p[i]);
                   2044:     }
                   2045:     printf("\n");
                   2046:     fprintf(ficlog,"\n");
                   2047:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2048:     if(*iter <=3){
1.157     brouard  2049:       tml = *localtime(&rcurr_time);
                   2050:       strcpy(strcurr,asctime(&tml));
                   2051:       rforecast_time=rcurr_time; 
1.126     brouard  2052:       itmp = strlen(strcurr);
                   2053:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.224     brouard  2054:                                strcurr[itmp-1]='\0';
1.162     brouard  2055:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2056:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  2057:       for(niterf=10;niterf<=30;niterf+=10){
1.224     brouard  2058:                                rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2059:                                forecast_time = *localtime(&rforecast_time);
                   2060:                                strcpy(strfor,asctime(&forecast_time));
                   2061:                                itmp = strlen(strfor);
                   2062:                                if(strfor[itmp-1]=='\n')
                   2063:                                        strfor[itmp-1]='\0';
                   2064:                                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);
                   2065:                                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  2066:       }
                   2067:     }
1.187     brouard  2068:     for (i=1;i<=n;i++) { /* For each direction i */
                   2069:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2070:       fptt=(*fret); 
                   2071: #ifdef DEBUG
1.203     brouard  2072:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2073:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2074: #endif
1.203     brouard  2075:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2076:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2077: #ifdef LINMINORIGINAL
1.188     brouard  2078:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2079: #else
                   2080:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2081:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2082: #endif
                   2083:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2084:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2085:                                /* because that direction will be replaced unless the gain del is small */
                   2086:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2087:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2088:                                /* with the new direction. */
                   2089:                                del=fabs(fptt-(*fret)); 
                   2090:                                ibig=i; 
1.126     brouard  2091:       } 
                   2092: #ifdef DEBUG
                   2093:       printf("%d %.12e",i,(*fret));
                   2094:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2095:       for (j=1;j<=n;j++) {
1.224     brouard  2096:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2097:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2098:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2099:       }
                   2100:       for(j=1;j<=n;j++) {
1.225     brouard  2101:                                printf(" p(%d)=%.12e",j,p[j]);
                   2102:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2103:       }
                   2104:       printf("\n");
                   2105:       fprintf(ficlog,"\n");
                   2106: #endif
1.187     brouard  2107:     } /* end loop on each direction i */
                   2108:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2109:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2110:     /* New value of last point Pn is not computed, P(n-1) */
1.224     brouard  2111:       for(j=1;j<=n;j++) {
1.225     brouard  2112:                                if(flatdir[j] >0){
                   2113:                                        printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2114:                                        fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2115:                                }
                   2116:                                /* printf("\n"); */
                   2117:                                /* fprintf(ficlog,"\n"); */
                   2118:                        }
1.182     brouard  2119:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1.188     brouard  2120:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2121:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2122:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2123:       /* decreased of more than 3.84  */
                   2124:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2125:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2126:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2127:                        
1.188     brouard  2128:       /* Starting the program with initial values given by a former maximization will simply change */
                   2129:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2130:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2131:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2132: #ifdef DEBUG
                   2133:       int k[2],l;
                   2134:       k[0]=1;
                   2135:       k[1]=-1;
                   2136:       printf("Max: %.12e",(*func)(p));
                   2137:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2138:       for (j=1;j<=n;j++) {
                   2139:        printf(" %.12e",p[j]);
                   2140:        fprintf(ficlog," %.12e",p[j]);
                   2141:       }
                   2142:       printf("\n");
                   2143:       fprintf(ficlog,"\n");
                   2144:       for(l=0;l<=1;l++) {
                   2145:        for (j=1;j<=n;j++) {
                   2146:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2147:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2148:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2149:        }
                   2150:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2151:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2152:       }
                   2153: #endif
                   2154: 
1.224     brouard  2155: #ifdef LINMINORIGINAL
                   2156: #else
                   2157:       free_ivector(flatdir,1,n); 
                   2158: #endif
1.126     brouard  2159:       free_vector(xit,1,n); 
                   2160:       free_vector(xits,1,n); 
                   2161:       free_vector(ptt,1,n); 
                   2162:       free_vector(pt,1,n); 
                   2163:       return; 
1.192     brouard  2164:     } /* enough precision */ 
1.126     brouard  2165:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2166:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2167:       ptt[j]=2.0*p[j]-pt[j]; 
                   2168:       xit[j]=p[j]-pt[j]; 
                   2169:       pt[j]=p[j]; 
                   2170:     } 
1.181     brouard  2171:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2172: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2173:                if (*iter <=4) {
1.225     brouard  2174: #else
                   2175: #endif
1.224     brouard  2176: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2177: #else
1.161     brouard  2178:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2179: #endif
1.162     brouard  2180:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2181:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2182:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2183:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2184:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2185:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2186:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2187:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2188:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2189:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2190:       /* mu² and del² are equal when f3=f1 */
                   2191:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2192:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2193:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2194:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2195: #ifdef NRCORIGINAL
                   2196:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2197: #else
                   2198:       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  2199:       t= t- del*SQR(fp-fptt);
1.183     brouard  2200: #endif
1.202     brouard  2201:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2202: #ifdef DEBUG
1.181     brouard  2203:       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);
                   2204:       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  2205:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2206:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2207:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2208:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2209:       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);
                   2210:       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);
                   2211: #endif
1.183     brouard  2212: #ifdef POWELLORIGINAL
                   2213:       if (t < 0.0) { /* Then we use it for new direction */
                   2214: #else
1.182     brouard  2215:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2216:                                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  2217:         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  2218:         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  2219:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2220:       } 
1.181     brouard  2221:       if (directest < 0.0) { /* Then we use it for new direction */
                   2222: #endif
1.191     brouard  2223: #ifdef DEBUGLINMIN
1.224     brouard  2224:                                printf("Before linmin in direction P%d-P0\n",n);
                   2225:                                for (j=1;j<=n;j++) {
                   2226:                                        printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2227:                                        fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2228:                                        if(j % ncovmodel == 0){
                   2229:                                                printf("\n");
                   2230:                                                fprintf(ficlog,"\n");
                   2231:                                        }
                   2232:                                }
                   2233: #endif
                   2234: #ifdef LINMINORIGINAL
                   2235:                                linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2236: #else
                   2237:                                linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2238:                                flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2239: #endif
1.224     brouard  2240: 
1.191     brouard  2241: #ifdef DEBUGLINMIN
1.224     brouard  2242:                                for (j=1;j<=n;j++) { 
                   2243:                                        printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2244:                                        fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2245:                                        if(j % ncovmodel == 0){
                   2246:                                                printf("\n");
                   2247:                                                fprintf(ficlog,"\n");
                   2248:                                        }
                   2249:                                }
                   2250: #endif
                   2251:                                for (j=1;j<=n;j++) { 
                   2252:                                        xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2253:                                        xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2254:                                }
                   2255: #ifdef LINMINORIGINAL
                   2256: #else
1.225     brouard  2257:                                for (j=1, flatd=0;j<=n;j++) {
                   2258:                                        if(flatdir[j]>0)
                   2259:                                                flatd++;
                   2260:                                }
                   2261:                                if(flatd >0){
                   2262:                                        printf("%d flat directions\n",flatd);
                   2263:                                        fprintf(ficlog,"%d flat directions\n",flatd);
                   2264:                                        for (j=1;j<=n;j++) { 
                   2265:                                                if(flatdir[j]>0){
                   2266:                                                        printf("%d ",j);
                   2267:                                                        fprintf(ficlog,"%d ",j);
                   2268:                                                }
                   2269:                                        }
                   2270:                                        printf("\n");
                   2271:                                        fprintf(ficlog,"\n");
                   2272:                                }
1.191     brouard  2273: #endif
1.224     brouard  2274:                                printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2275:                                fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2276:                                
1.126     brouard  2277: #ifdef DEBUG
1.224     brouard  2278:                                printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2279:                                fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2280:                                for(j=1;j<=n;j++){
                   2281:                                        printf(" %lf",xit[j]);
                   2282:                                        fprintf(ficlog," %lf",xit[j]);
                   2283:                                }
                   2284:                                printf("\n");
                   2285:                                fprintf(ficlog,"\n");
1.126     brouard  2286: #endif
1.192     brouard  2287:       } /* end of t or directest negative */
1.224     brouard  2288: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2289: #else
1.162     brouard  2290:     } /* end if (fptt < fp)  */
1.192     brouard  2291: #endif
1.225     brouard  2292: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.224     brouard  2293:                } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2294: #else
1.224     brouard  2295: #endif
1.192     brouard  2296:   } /* loop iteration */ 
1.126     brouard  2297: } 
                   2298: 
                   2299: /**** Prevalence limit (stable or period prevalence)  ****************/
                   2300: 
1.203     brouard  2301: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij)
1.126     brouard  2302: {
1.218     brouard  2303:   /* Computes the prevalence limit in each live state at age x and for covariate ij by left multiplying the unit
1.203     brouard  2304:      matrix by transitions matrix until convergence is reached with precision ftolpl */
1.206     brouard  2305:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2306:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2307:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2308:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2309:   /* Initial matrix pimij */
                   2310:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2311:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2312:   /*  0,                   0                  , 1} */
                   2313:   /*
                   2314:    * and after some iteration: */
                   2315:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2316:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2317:   /*  0,                   0                  , 1} */
                   2318:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2319:   /* {0.51571254859325999, 0.4842874514067399, */
                   2320:   /*  0.51326036147820708, 0.48673963852179264} */
                   2321:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2322: 
1.126     brouard  2323:   int i, ii,j,k;
1.209     brouard  2324:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2325:   /* double **matprod2(); */ /* test */
1.218     brouard  2326:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2327:   double **newm;
1.209     brouard  2328:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2329:   int ncvloop=0;
1.169     brouard  2330:   
1.209     brouard  2331:   min=vector(1,nlstate);
                   2332:   max=vector(1,nlstate);
                   2333:   meandiff=vector(1,nlstate);
                   2334: 
1.218     brouard  2335:        /* Starting with matrix unity */
1.126     brouard  2336:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2337:     for (j=1;j<=nlstate+ndeath;j++){
                   2338:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2339:     }
1.169     brouard  2340:   
                   2341:   cov[1]=1.;
                   2342:   
                   2343:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2344:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2345:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2346:     ncvloop++;
1.126     brouard  2347:     newm=savm;
                   2348:     /* Covariates have to be included here again */
1.138     brouard  2349:     cov[2]=agefin;
1.187     brouard  2350:     if(nagesqr==1)
                   2351:       cov[3]= agefin*agefin;;
1.138     brouard  2352:     for (k=1; k<=cptcovn;k++) {
1.200     brouard  2353:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.218     brouard  2354:                        /* Here comes the value of the covariate 'ij' */
1.200     brouard  2355:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
1.198     brouard  2356:       /* 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])]); */
1.138     brouard  2357:     }
1.186     brouard  2358:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  2359:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
                   2360:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
1.186     brouard  2361:     for (k=1; k<=cptcovprod;k++) /* Useless */
1.200     brouard  2362:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   2363:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
1.138     brouard  2364:     
                   2365:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2366:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2367:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2368:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2369:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2370:                /* age and covariate values of ij are in 'cov' */
1.142     brouard  2371:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2372:     
1.126     brouard  2373:     savm=oldm;
                   2374:     oldm=newm;
1.209     brouard  2375: 
                   2376:     for(j=1; j<=nlstate; j++){
                   2377:       max[j]=0.;
                   2378:       min[j]=1.;
                   2379:     }
                   2380:     for(i=1;i<=nlstate;i++){
                   2381:       sumnew=0;
                   2382:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2383:       for(j=1; j<=nlstate; j++){ 
                   2384:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2385:        max[j]=FMAX(max[j],prlim[i][j]);
                   2386:        min[j]=FMIN(min[j],prlim[i][j]);
                   2387:       }
                   2388:     }
                   2389: 
1.126     brouard  2390:     maxmax=0.;
1.209     brouard  2391:     for(j=1; j<=nlstate; j++){
                   2392:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2393:       maxmax=FMAX(maxmax,meandiff[j]);
                   2394:       /* 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  2395:     } /* j loop */
1.203     brouard  2396:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2397:     /* 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  2398:     if(maxmax < ftolpl){
1.209     brouard  2399:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2400:       free_vector(min,1,nlstate);
                   2401:       free_vector(max,1,nlstate);
                   2402:       free_vector(meandiff,1,nlstate);
1.126     brouard  2403:       return prlim;
                   2404:     }
1.169     brouard  2405:   } /* age loop */
1.208     brouard  2406:     /* After some age loop it doesn't converge */
1.209     brouard  2407:   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  2408: 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  2409:   /* 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); */
                   2410:   free_vector(min,1,nlstate);
                   2411:   free_vector(max,1,nlstate);
                   2412:   free_vector(meandiff,1,nlstate);
1.208     brouard  2413:   
1.169     brouard  2414:   return prlim; /* should not reach here */
1.126     brouard  2415: }
                   2416: 
1.217     brouard  2417: 
                   2418:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   2419: 
1.218     brouard  2420:  /* 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) */
                   2421:  /* 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) */
                   2422:  double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij)
1.217     brouard  2423: {
1.218     brouard  2424:   /* Computes the prevalence limit in each live state at age x and covariate ij by left multiplying the unit
1.217     brouard  2425:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   2426:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2427:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2428:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2429:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2430:   /* Initial matrix pimij */
                   2431:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2432:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2433:   /*  0,                   0                  , 1} */
                   2434:   /*
                   2435:    * and after some iteration: */
                   2436:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2437:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2438:   /*  0,                   0                  , 1} */
                   2439:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2440:   /* {0.51571254859325999, 0.4842874514067399, */
                   2441:   /*  0.51326036147820708, 0.48673963852179264} */
                   2442:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2443: 
                   2444:   int i, ii,j,k;
                   2445:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   2446:   /* double **matprod2(); */ /* test */
                   2447:   double **out, cov[NCOVMAX+1], **bmij();
                   2448:   double **newm;
1.218     brouard  2449:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   2450:   double        **oldm, **savm;  /* for use */
                   2451: 
1.217     brouard  2452:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   2453:   int ncvloop=0;
                   2454:   
                   2455:   min=vector(1,nlstate);
                   2456:   max=vector(1,nlstate);
                   2457:   meandiff=vector(1,nlstate);
                   2458: 
1.218     brouard  2459:        dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   2460:        oldm=oldms; savm=savms;
                   2461: 
                   2462:        /* Starting with matrix unity */
                   2463:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2464:                for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  2465:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2466:     }
                   2467:   
                   2468:   cov[1]=1.;
                   2469:   
                   2470:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2471:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  2472:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   2473:   for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  2474:     ncvloop++;
1.218     brouard  2475:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   2476:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  2477:     /* Covariates have to be included here again */
                   2478:     cov[2]=agefin;
                   2479:     if(nagesqr==1)
                   2480:       cov[3]= agefin*agefin;;
                   2481:     for (k=1; k<=cptcovn;k++) {
                   2482:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
                   2483:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   2484:       /* 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])]); */
                   2485:     }
                   2486:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   2487:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
                   2488:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
                   2489:     for (k=1; k<=cptcovprod;k++) /* Useless */
                   2490:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   2491:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2492:     
                   2493:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2494:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2495:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   2496:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2497:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2498:                /* ij should be linked to the correct index of cov */
                   2499:                /* age and covariate values ij are in 'cov', but we need to pass
                   2500:                 * ij for the observed prevalence at age and status and covariate
                   2501:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   2502:                 */
                   2503:     /* 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 *\/ */
                   2504:     /* 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 *\/ */
                   2505:     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  2506:     savm=oldm;
                   2507:     oldm=newm;
                   2508:     for(j=1; j<=nlstate; j++){
                   2509:       max[j]=0.;
                   2510:       min[j]=1.;
                   2511:     }
                   2512:     for(j=1; j<=nlstate; j++){ 
                   2513:       for(i=1;i<=nlstate;i++){
1.218     brouard  2514:                                /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   2515:                                bprlim[i][j]= newm[i][j];
                   2516:                                max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   2517:                                min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  2518:       }
                   2519:     }
1.218     brouard  2520:                
1.217     brouard  2521:     maxmax=0.;
                   2522:     for(i=1; i<=nlstate; i++){
                   2523:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column */
                   2524:       maxmax=FMAX(maxmax,meandiff[i]);
                   2525:       /* 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); */
                   2526:     } /* j loop */
                   2527:     *ncvyear= -( (int)age- (int)agefin);
1.218     brouard  2528:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear);*/
1.217     brouard  2529:     if(maxmax < ftolpl){
1.220     brouard  2530:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  2531:       free_vector(min,1,nlstate);
                   2532:       free_vector(max,1,nlstate);
                   2533:       free_vector(meandiff,1,nlstate);
                   2534:       return bprlim;
                   2535:     }
                   2536:   } /* age loop */
                   2537:     /* After some age loop it doesn't converge */
                   2538:   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\
                   2539: 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);
                   2540:   /* 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); */
                   2541:   free_vector(min,1,nlstate);
                   2542:   free_vector(max,1,nlstate);
                   2543:   free_vector(meandiff,1,nlstate);
                   2544:   
                   2545:   return bprlim; /* should not reach here */
                   2546: }
                   2547: 
1.126     brouard  2548: /*************** transition probabilities ***************/ 
                   2549: 
                   2550: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   2551: {
1.138     brouard  2552:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2553:      computes the probability to be observed in state j being in state i by appying the
                   2554:      model to the ncovmodel covariates (including constant and age).
                   2555:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2556:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2557:      ncth covariate in the global vector x is given by the formula:
                   2558:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2559:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2560:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2561:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2562:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2563:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2564:   */
                   2565:   double s1, lnpijopii;
1.126     brouard  2566:   /*double t34;*/
1.164     brouard  2567:   int i,j, nc, ii, jj;
1.126     brouard  2568: 
1.223     brouard  2569:   for(i=1; i<= nlstate; i++){
                   2570:     for(j=1; j<i;j++){
                   2571:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2572:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2573:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2574:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2575:       }
                   2576:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2577:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2578:     }
                   2579:     for(j=i+1; j<=nlstate+ndeath;j++){
                   2580:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2581:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2582:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2583:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   2584:       }
                   2585:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2586:     }
                   2587:   }
1.218     brouard  2588:   
1.223     brouard  2589:   for(i=1; i<= nlstate; i++){
                   2590:     s1=0;
                   2591:     for(j=1; j<i; j++){
                   2592:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2593:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2594:     }
                   2595:     for(j=i+1; j<=nlstate+ndeath; j++){
                   2596:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2597:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2598:     }
                   2599:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   2600:     ps[i][i]=1./(s1+1.);
                   2601:     /* Computing other pijs */
                   2602:     for(j=1; j<i; j++)
                   2603:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2604:     for(j=i+1; j<=nlstate+ndeath; j++)
                   2605:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2606:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2607:   } /* end i */
1.218     brouard  2608:   
1.223     brouard  2609:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2610:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   2611:       ps[ii][jj]=0;
                   2612:       ps[ii][ii]=1;
                   2613:     }
                   2614:   }
1.218     brouard  2615:   
                   2616:   
1.223     brouard  2617:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2618:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2619:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2620:   /*   } */
                   2621:   /*   printf("\n "); */
                   2622:   /* } */
                   2623:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   2624:   /*
                   2625:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  2626:                goto end;*/
1.223     brouard  2627:   return ps;
1.126     brouard  2628: }
                   2629: 
1.218     brouard  2630: /*************** backward transition probabilities ***************/ 
                   2631: 
                   2632:  /* 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 ) */
                   2633: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   2634:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   2635: {
1.222     brouard  2636:   /* Computes the backward probability at age agefin and covariate ij
                   2637:    * and returns in **ps as well as **bmij.
                   2638:    */
1.218     brouard  2639:   int i, ii, j,k;
1.222     brouard  2640:   
                   2641:   double **out, **pmij();
                   2642:   double sumnew=0.;
1.218     brouard  2643:   double agefin;
1.222     brouard  2644:   
                   2645:   double **dnewm, **dsavm, **doldm;
                   2646:   double **bbmij;
                   2647:   
1.218     brouard  2648:   doldm=ddoldms; /* global pointers */
1.222     brouard  2649:   dnewm=ddnewms;
                   2650:   dsavm=ddsavms;
                   2651:   
                   2652:   agefin=cov[2];
                   2653:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
                   2654:      the observed prevalence (with this covariate ij) */
                   2655:   dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate);
                   2656:   /* We do have the matrix Px in savm  and we need pij */
                   2657:   for (j=1;j<=nlstate+ndeath;j++){
                   2658:     sumnew=0.; /* w1 p11 + w2 p21 only on live states */
                   2659:     for (ii=1;ii<=nlstate;ii++){
                   2660:       sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij];
                   2661:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
                   2662:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   2663:       if(sumnew >= 1.e-10){
                   2664:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
                   2665:        /*      doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
                   2666:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
                   2667:        /*      doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
                   2668:        /* }else */
                   2669:        doldm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   2670:       }else{
                   2671:        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);
                   2672:       }
                   2673:     } /*End ii */
                   2674:   } /* End j, At the end doldm is diag[1/(w_1p1i+w_2 p2i)] */
                   2675:   /* left Product of this diag matrix by dsavm=Px (newm=dsavm*doldm) */
                   2676:   bbmij=matprod2(dnewm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, doldm); /* Bug Valgrind */
                   2677:   /* dsavm=doldm; /\* dsavm is now diag [1/(w_1p1i+w_2 p2i)] but can be overwritten*\/ */
                   2678:   /* doldm=dnewm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
                   2679:   /* dnewm=dsavm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
                   2680:   /* left Product of this matrix by diag matrix of prevalences (savm) */
                   2681:   for (j=1;j<=nlstate+ndeath;j++){
                   2682:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   2683:       dsavm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij] : 0.0);
                   2684:     }
                   2685:   } /* End j, At the end oldm is diag[1/(w_1p1i+w_2 p2i)] */
                   2686:   ps=matprod2(doldm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dnewm); /* Bug Valgrind */
                   2687:   /* newm or out is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
                   2688:   /* end bmij */
                   2689:   return ps; 
1.218     brouard  2690: }
1.217     brouard  2691: /*************** transition probabilities ***************/ 
                   2692: 
1.218     brouard  2693: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  2694: {
                   2695:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2696:      computes the probability to be observed in state j being in state i by appying the
                   2697:      model to the ncovmodel covariates (including constant and age).
                   2698:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2699:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2700:      ncth covariate in the global vector x is given by the formula:
                   2701:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2702:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2703:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2704:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2705:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2706:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2707:   */
                   2708:   double s1, lnpijopii;
                   2709:   /*double t34;*/
                   2710:   int i,j, nc, ii, jj;
                   2711: 
1.218     brouard  2712:        for(i=1; i<= nlstate; i++){
                   2713:                for(j=1; j<i;j++){
                   2714:                        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2715:                                /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2716:                                lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2717:                                /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2718:                        }
                   2719:                        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2720:                        /*      printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2721:                }
                   2722:                for(j=i+1; j<=nlstate+ndeath;j++){
                   2723:                        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2724:                                /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2725:                                lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2726:                                /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   2727:                        }
                   2728:                        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2729:                }
                   2730:        }
                   2731:        
                   2732:        for(i=1; i<= nlstate; i++){
                   2733:                s1=0;
                   2734:                for(j=1; j<i; j++){
                   2735:                        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2736:                        /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2737:                }
                   2738:                for(j=i+1; j<=nlstate+ndeath; j++){
                   2739:                        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2740:                        /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2741:                }
                   2742:                /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   2743:                ps[i][i]=1./(s1+1.);
                   2744:                /* Computing other pijs */
                   2745:                for(j=1; j<i; j++)
                   2746:                        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2747:                for(j=i+1; j<=nlstate+ndeath; j++)
                   2748:                        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2749:                /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2750:        } /* end i */
                   2751:        
                   2752:        for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2753:                for(jj=1; jj<= nlstate+ndeath; jj++){
                   2754:                        ps[ii][jj]=0;
                   2755:                        ps[ii][ii]=1;
                   2756:                }
                   2757:        }
                   2758:        /* Added for backcast */ /* Transposed matrix too */
                   2759:        for(jj=1; jj<= nlstate+ndeath; jj++){
                   2760:                s1=0.;
                   2761:                for(ii=1; ii<= nlstate+ndeath; ii++){
                   2762:                        s1+=ps[ii][jj];
                   2763:                }
                   2764:                for(ii=1; ii<= nlstate; ii++){
                   2765:                        ps[ii][jj]=ps[ii][jj]/s1;
                   2766:                }
                   2767:        }
                   2768:        /* Transposition */
                   2769:        for(jj=1; jj<= nlstate+ndeath; jj++){
                   2770:                for(ii=jj; ii<= nlstate+ndeath; ii++){
                   2771:                        s1=ps[ii][jj];
                   2772:                        ps[ii][jj]=ps[jj][ii];
                   2773:                        ps[jj][ii]=s1;
                   2774:                }
                   2775:        }
                   2776:        /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2777:        /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2778:        /*      printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2779:        /*   } */
                   2780:        /*   printf("\n "); */
                   2781:        /* } */
                   2782:        /* printf("\n ");printf("%lf ",cov[2]);*/
                   2783:        /*
                   2784:                for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   2785:                goto end;*/
                   2786:        return ps;
1.217     brouard  2787: }
                   2788: 
                   2789: 
1.126     brouard  2790: /**************** Product of 2 matrices ******************/
                   2791: 
1.145     brouard  2792: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  2793: {
                   2794:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   2795:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   2796:   /* in, b, out are matrice of pointers which should have been initialized 
                   2797:      before: only the contents of out is modified. The function returns
                   2798:      a pointer to pointers identical to out */
1.145     brouard  2799:   int i, j, k;
1.126     brouard  2800:   for(i=nrl; i<= nrh; i++)
1.145     brouard  2801:     for(k=ncolol; k<=ncoloh; k++){
                   2802:       out[i][k]=0.;
                   2803:       for(j=ncl; j<=nch; j++)
                   2804:        out[i][k] +=in[i][j]*b[j][k];
                   2805:     }
1.126     brouard  2806:   return out;
                   2807: }
                   2808: 
                   2809: 
                   2810: /************* Higher Matrix Product ***************/
                   2811: 
                   2812: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
                   2813: {
1.218     brouard  2814:   /* Computes the transition matrix starting at age 'age' and combination of covariate values corresponding to ij over 
1.126     brouard  2815:      'nhstepm*hstepm*stepm' months (i.e. until
                   2816:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   2817:      nhstepm*hstepm matrices. 
                   2818:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   2819:      (typically every 2 years instead of every month which is too big 
                   2820:      for the memory).
                   2821:      Model is determined by parameters x and covariates have to be 
                   2822:      included manually here. 
                   2823: 
                   2824:      */
                   2825: 
                   2826:   int i, j, d, h, k;
1.131     brouard  2827:   double **out, cov[NCOVMAX+1];
1.126     brouard  2828:   double **newm;
1.187     brouard  2829:   double agexact;
1.214     brouard  2830:   double agebegin, ageend;
1.126     brouard  2831: 
                   2832:   /* Hstepm could be zero and should return the unit matrix */
                   2833:   for (i=1;i<=nlstate+ndeath;i++)
                   2834:     for (j=1;j<=nlstate+ndeath;j++){
                   2835:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   2836:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   2837:     }
                   2838:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2839:   for(h=1; h <=nhstepm; h++){
                   2840:     for(d=1; d <=hstepm; d++){
                   2841:       newm=savm;
                   2842:       /* Covariates have to be included here again */
                   2843:       cov[1]=1.;
1.214     brouard  2844:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  2845:       cov[2]=agexact;
                   2846:       if(nagesqr==1)
1.227     brouard  2847:        cov[3]= agexact*agexact;
1.131     brouard  2848:       for (k=1; k<=cptcovn;k++) 
1.227     brouard  2849:        cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   2850:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.186     brouard  2851:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
1.227     brouard  2852:        /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   2853:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2854:       /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
1.145     brouard  2855:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.227     brouard  2856:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2857:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   2858:       
                   2859:       
1.126     brouard  2860:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   2861:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.218     brouard  2862:                        /* right multiplication of oldm by the current matrix */
1.126     brouard  2863:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   2864:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  2865:       /* if((int)age == 70){ */
                   2866:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   2867:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   2868:       /*         printf("%d pmmij ",i); */
                   2869:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2870:       /*           printf("%f ",pmmij[i][j]); */
                   2871:       /*         } */
                   2872:       /*         printf(" oldm "); */
                   2873:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2874:       /*           printf("%f ",oldm[i][j]); */
                   2875:       /*         } */
                   2876:       /*         printf("\n"); */
                   2877:       /*       } */
                   2878:       /* } */
1.126     brouard  2879:       savm=oldm;
                   2880:       oldm=newm;
                   2881:     }
                   2882:     for(i=1; i<=nlstate+ndeath; i++)
                   2883:       for(j=1;j<=nlstate+ndeath;j++) {
1.218     brouard  2884:                                po[i][j][h]=newm[i][j];
                   2885:                                /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  2886:       }
1.128     brouard  2887:     /*printf("h=%d ",h);*/
1.126     brouard  2888:   } /* end h */
1.218     brouard  2889:        /*     printf("\n H=%d \n",h); */
1.126     brouard  2890:   return po;
                   2891: }
                   2892: 
1.217     brouard  2893: /************* Higher Back Matrix Product ***************/
1.218     brouard  2894: /* 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  2895: double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, double ***prevacurrent, int nlstate, int stepm, int ij )
1.217     brouard  2896: {
1.218     brouard  2897:   /* Computes the transition matrix starting at age 'age' over
1.217     brouard  2898:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  2899:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   2900:      nhstepm*hstepm matrices.
                   2901:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   2902:      (typically every 2 years instead of every month which is too big
1.217     brouard  2903:      for the memory).
1.218     brouard  2904:      Model is determined by parameters x and covariates have to be
                   2905:      included manually here.
1.217     brouard  2906: 
1.222     brouard  2907:   */
1.217     brouard  2908: 
                   2909:   int i, j, d, h, k;
                   2910:   double **out, cov[NCOVMAX+1];
                   2911:   double **newm;
                   2912:   double agexact;
                   2913:   double agebegin, ageend;
1.222     brouard  2914:   double **oldm, **savm;
1.217     brouard  2915: 
1.222     brouard  2916:   oldm=oldms;savm=savms;
1.217     brouard  2917:   /* Hstepm could be zero and should return the unit matrix */
                   2918:   for (i=1;i<=nlstate+ndeath;i++)
                   2919:     for (j=1;j<=nlstate+ndeath;j++){
                   2920:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   2921:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   2922:     }
                   2923:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2924:   for(h=1; h <=nhstepm; h++){
                   2925:     for(d=1; d <=hstepm; d++){
                   2926:       newm=savm;
                   2927:       /* Covariates have to be included here again */
                   2928:       cov[1]=1.;
                   2929:       agexact=age-((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
                   2930:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
                   2931:       cov[2]=agexact;
                   2932:       if(nagesqr==1)
1.222     brouard  2933:        cov[3]= agexact*agexact;
1.218     brouard  2934:       for (k=1; k<=cptcovn;k++)
1.222     brouard  2935:        cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   2936:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.217     brouard  2937:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
1.222     brouard  2938:        /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   2939:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2940:       /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
1.217     brouard  2941:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.222     brouard  2942:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2943:       /* 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  2944:                        
                   2945:                        
1.217     brouard  2946:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   2947:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.218     brouard  2948:       /* Careful transposed matrix */
1.222     brouard  2949:       /* age is in cov[2] */
1.218     brouard  2950:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  2951:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  2952:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.222     brouard  2953:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
1.217     brouard  2954:       /* if((int)age == 70){ */
                   2955:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   2956:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   2957:       /*         printf("%d pmmij ",i); */
                   2958:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2959:       /*           printf("%f ",pmmij[i][j]); */
                   2960:       /*         } */
                   2961:       /*         printf(" oldm "); */
                   2962:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2963:       /*           printf("%f ",oldm[i][j]); */
                   2964:       /*         } */
                   2965:       /*         printf("\n"); */
                   2966:       /*       } */
                   2967:       /* } */
                   2968:       savm=oldm;
                   2969:       oldm=newm;
                   2970:     }
                   2971:     for(i=1; i<=nlstate+ndeath; i++)
                   2972:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  2973:        po[i][j][h]=newm[i][j];
                   2974:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.217     brouard  2975:       }
                   2976:     /*printf("h=%d ",h);*/
                   2977:   } /* end h */
1.222     brouard  2978:   /*     printf("\n H=%d \n",h); */
1.217     brouard  2979:   return po;
                   2980: }
                   2981: 
                   2982: 
1.162     brouard  2983: #ifdef NLOPT
                   2984:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   2985:   double fret;
                   2986:   double *xt;
                   2987:   int j;
                   2988:   myfunc_data *d2 = (myfunc_data *) pd;
                   2989: /* xt = (p1-1); */
                   2990:   xt=vector(1,n); 
                   2991:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   2992: 
                   2993:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   2994:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   2995:   printf("Function = %.12lf ",fret);
                   2996:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   2997:   printf("\n");
                   2998:  free_vector(xt,1,n);
                   2999:   return fret;
                   3000: }
                   3001: #endif
1.126     brouard  3002: 
                   3003: /*************** log-likelihood *************/
                   3004: double func( double *x)
                   3005: {
1.226     brouard  3006:   int i, ii, j, k, mi, d, kk;
                   3007:   int ioffset=0;
                   3008:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3009:   double **out;
                   3010:   double lli; /* Individual log likelihood */
                   3011:   int s1, s2;
1.228     brouard  3012:   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  3013:   double bbh, survp;
                   3014:   long ipmx;
                   3015:   double agexact;
                   3016:   /*extern weight */
                   3017:   /* We are differentiating ll according to initial status */
                   3018:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3019:   /*for(i=1;i<imx;i++) 
                   3020:     printf(" %d\n",s[4][i]);
                   3021:   */
1.162     brouard  3022: 
1.226     brouard  3023:   ++countcallfunc;
1.162     brouard  3024: 
1.226     brouard  3025:   cov[1]=1.;
1.126     brouard  3026: 
1.226     brouard  3027:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3028:   ioffset=0;
1.226     brouard  3029:   if(mle==1){
                   3030:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3031:       /* Computes the values of the ncovmodel covariates of the model
                   3032:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   3033:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   3034:         to be observed in j being in i according to the model.
                   3035:       */
                   3036:       ioffset=2+nagesqr+cptcovage;
                   3037:       /* for (k=1; k<=cptcovn;k++){ /\* Simple and product covariates without age* products *\/ */
                   3038:       for (k=1; k<=ncoveff;k++){ /* Simple and product covariates without age* products */
1.232   ! brouard  3039:                                cov[++ioffset]=covar[Tvar[k]][i];
1.226     brouard  3040:       }
                   3041:       for(iqv=1; iqv <= nqfveff; iqv++){ /* Quantitatives and Fixed covariates */
1.232   ! brouard  3042:                                cov[++ioffset]=coqvar[Tvar[iqv]][i];
1.226     brouard  3043:       }
                   3044: 
                   3045:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   3046:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
                   3047:         has been calculated etc */
                   3048:       /* For an individual i, wav[i] gives the number of effective waves */
                   3049:       /* We compute the contribution to Likelihood of each effective transition
                   3050:         mw[mi][i] is real wave of the mi th effectve wave */
                   3051:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   3052:         s2=s[mw[mi+1][i]][i];
                   3053:         And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
                   3054:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   3055:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   3056:       */
                   3057:       for(mi=1; mi<= wav[i]-1; mi++){
1.231     brouard  3058:                                for(itv=1; itv <= ntveff; itv++){ /* Varying dummy covariates */
                   3059:                                        /* cov[ioffset+itv]=cotvar[mw[mi][i]][Tvar[itv]][i]; /\* Not sure, Tvar V4+V3+V5 Tvaraff ? *\/ */
                   3060:                                        cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i];
                   3061:                                }
                   3062:                                for(iqtv=1; iqtv <= nqtveff; iqtv++){ /* Varying quantitatives covariates */
                   3063:                                        if(cotqvar[mw[mi][i]][iqtv][i] == -1){
                   3064:                                                printf("i=%d, mi=%d, iqtv=%d, cotqvar[mw[mi][i]][iqtv][i]=%f",i,mi,iqtv,cotqvar[mw[mi][i]][iqtv][i]);
                   3065:                                        }
                   3066:                                        cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i];
                   3067:                                        /* cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][iqtv][i]; */
                   3068:                                }
                   3069:                                /* ioffset=2+nagesqr+cptcovn+nqv+ntv+nqtv; */
                   3070:                                for (ii=1;ii<=nlstate+ndeath;ii++)
                   3071:                                        for (j=1;j<=nlstate+ndeath;j++){
                   3072:                                                oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3073:                                                savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3074:                                        }
                   3075:                                for(d=0; d<dh[mi][i]; d++){
                   3076:                                        newm=savm;
                   3077:                                        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3078:                                        cov[2]=agexact;
                   3079:                                        if(nagesqr==1)
                   3080:                                                cov[3]= agexact*agexact;  /* Should be changed here */
                   3081:                                        for (kk=1; kk<=cptcovage;kk++) {
                   3082:                                                cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   3083:                                        }
                   3084:                                        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3085:                                                                                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3086:                                        savm=oldm;
                   3087:                                        oldm=newm;
                   3088:                                } /* end mult */
1.224     brouard  3089:                                
1.231     brouard  3090:                                /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   3091:                                /* But now since version 0.9 we anticipate for bias at large stepm.
                   3092:                                 * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   3093:                                 * (in months) between two waves is not a multiple of stepm, we rounded to 
                   3094:                                 * the nearest (and in case of equal distance, to the lowest) interval but now
                   3095:                                 * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   3096:                                 * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   3097:                                 * probability in order to take into account the bias as a fraction of the way
                   3098:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   3099:                                 * -stepm/2 to stepm/2 .
                   3100:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   3101:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   3102:                                 */
                   3103:                                s1=s[mw[mi][i]][i];
                   3104:                                s2=s[mw[mi+1][i]][i];
                   3105:                                bbh=(double)bh[mi][i]/(double)stepm; 
                   3106:                                /* bias bh is positive if real duration
                   3107:                                 * is higher than the multiple of stepm and negative otherwise.
                   3108:                                 */
                   3109:                                /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   3110:                                if( s2 > nlstate){ 
                   3111:                                        /* i.e. if s2 is a death state and if the date of death is known 
                   3112:                                                 then the contribution to the likelihood is the probability to 
                   3113:                                                 die between last step unit time and current  step unit time, 
                   3114:                                                 which is also equal to probability to die before dh 
                   3115:                                                 minus probability to die before dh-stepm . 
                   3116:                                                 In version up to 0.92 likelihood was computed
                   3117:                                                 as if date of death was unknown. Death was treated as any other
                   3118:                                                 health state: the date of the interview describes the actual state
                   3119:                                                 and not the date of a change in health state. The former idea was
                   3120:                                                 to consider that at each interview the state was recorded
                   3121:                                                 (healthy, disable or death) and IMaCh was corrected; but when we
                   3122:                                                 introduced the exact date of death then we should have modified
                   3123:                                                 the contribution of an exact death to the likelihood. This new
                   3124:                                                 contribution is smaller and very dependent of the step unit
                   3125:                                                 stepm. It is no more the probability to die between last interview
                   3126:                                                 and month of death but the probability to survive from last
                   3127:                                                 interview up to one month before death multiplied by the
                   3128:                                                 probability to die within a month. Thanks to Chris
                   3129:                                                 Jackson for correcting this bug.  Former versions increased
                   3130:                                                 mortality artificially. The bad side is that we add another loop
                   3131:                                                 which slows down the processing. The difference can be up to 10%
                   3132:                                                 lower mortality.
                   3133:                                        */
                   3134:                                        /* If, at the beginning of the maximization mostly, the
                   3135:                                                 cumulative probability or probability to be dead is
                   3136:                                                 constant (ie = 1) over time d, the difference is equal to
                   3137:                                                 0.  out[s1][3] = savm[s1][3]: probability, being at state
                   3138:                                                 s1 at precedent wave, to be dead a month before current
                   3139:                                                 wave is equal to probability, being at state s1 at
                   3140:                                                 precedent wave, to be dead at mont of the current
                   3141:                                                 wave. Then the observed probability (that this person died)
                   3142:                                                 is null according to current estimated parameter. In fact,
                   3143:                                                 it should be very low but not zero otherwise the log go to
                   3144:                                                 infinity.
                   3145:                                        */
1.183     brouard  3146: /* #ifdef INFINITYORIGINAL */
                   3147: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3148: /* #else */
                   3149: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   3150: /*         lli=log(mytinydouble); */
                   3151: /*       else */
                   3152: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3153: /* #endif */
1.226     brouard  3154:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3155:          
1.226     brouard  3156:        } else if  ( s2==-1 ) { /* alive */
                   3157:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3158:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3159:          /*survp += out[s1][j]; */
                   3160:          lli= log(survp);
                   3161:        }
                   3162:        else if  (s2==-4) { 
                   3163:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   3164:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3165:          lli= log(survp); 
                   3166:        } 
                   3167:        else if  (s2==-5) { 
                   3168:          for (j=1,survp=0. ; j<=2; j++)  
                   3169:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3170:          lli= log(survp); 
                   3171:        } 
                   3172:        else{
                   3173:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3174:          /*  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 */
                   3175:        } 
                   3176:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   3177:        /*if(lli ==000.0)*/
                   3178:        /*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); */
                   3179:        ipmx +=1;
                   3180:        sw += weight[i];
                   3181:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3182:        /* if (lli < log(mytinydouble)){ */
                   3183:        /*   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); */
                   3184:        /*   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]); */
                   3185:        /* } */
                   3186:       } /* end of wave */
                   3187:     } /* end of individual */
                   3188:   }  else if(mle==2){
                   3189:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3190:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3191:       for(mi=1; mi<= wav[i]-1; mi++){
                   3192:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3193:          for (j=1;j<=nlstate+ndeath;j++){
                   3194:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3195:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3196:          }
                   3197:        for(d=0; d<=dh[mi][i]; d++){
                   3198:          newm=savm;
                   3199:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3200:          cov[2]=agexact;
                   3201:          if(nagesqr==1)
                   3202:            cov[3]= agexact*agexact;
                   3203:          for (kk=1; kk<=cptcovage;kk++) {
                   3204:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3205:          }
                   3206:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3207:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3208:          savm=oldm;
                   3209:          oldm=newm;
                   3210:        } /* end mult */
                   3211:       
                   3212:        s1=s[mw[mi][i]][i];
                   3213:        s2=s[mw[mi+1][i]][i];
                   3214:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3215:        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 */
                   3216:        ipmx +=1;
                   3217:        sw += weight[i];
                   3218:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3219:       } /* end of wave */
                   3220:     } /* end of individual */
                   3221:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   3222:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3223:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3224:       for(mi=1; mi<= wav[i]-1; mi++){
                   3225:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3226:          for (j=1;j<=nlstate+ndeath;j++){
                   3227:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3228:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3229:          }
                   3230:        for(d=0; d<dh[mi][i]; d++){
                   3231:          newm=savm;
                   3232:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3233:          cov[2]=agexact;
                   3234:          if(nagesqr==1)
                   3235:            cov[3]= agexact*agexact;
                   3236:          for (kk=1; kk<=cptcovage;kk++) {
                   3237:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3238:          }
                   3239:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3240:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3241:          savm=oldm;
                   3242:          oldm=newm;
                   3243:        } /* end mult */
                   3244:       
                   3245:        s1=s[mw[mi][i]][i];
                   3246:        s2=s[mw[mi+1][i]][i];
                   3247:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3248:        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 */
                   3249:        ipmx +=1;
                   3250:        sw += weight[i];
                   3251:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3252:       } /* end of wave */
                   3253:     } /* end of individual */
                   3254:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   3255:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3256:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3257:       for(mi=1; mi<= wav[i]-1; mi++){
                   3258:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3259:          for (j=1;j<=nlstate+ndeath;j++){
                   3260:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3261:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3262:          }
                   3263:        for(d=0; d<dh[mi][i]; d++){
                   3264:          newm=savm;
                   3265:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3266:          cov[2]=agexact;
                   3267:          if(nagesqr==1)
                   3268:            cov[3]= agexact*agexact;
                   3269:          for (kk=1; kk<=cptcovage;kk++) {
                   3270:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3271:          }
1.126     brouard  3272:        
1.226     brouard  3273:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3274:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3275:          savm=oldm;
                   3276:          oldm=newm;
                   3277:        } /* end mult */
                   3278:       
                   3279:        s1=s[mw[mi][i]][i];
                   3280:        s2=s[mw[mi+1][i]][i];
                   3281:        if( s2 > nlstate){ 
                   3282:          lli=log(out[s1][s2] - savm[s1][s2]);
                   3283:        } else if  ( s2==-1 ) { /* alive */
                   3284:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3285:            survp += out[s1][j];
                   3286:          lli= log(survp);
                   3287:        }else{
                   3288:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3289:        }
                   3290:        ipmx +=1;
                   3291:        sw += weight[i];
                   3292:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.126     brouard  3293: /*     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  3294:       } /* end of wave */
                   3295:     } /* end of individual */
                   3296:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   3297:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3298:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3299:       for(mi=1; mi<= wav[i]-1; mi++){
                   3300:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3301:          for (j=1;j<=nlstate+ndeath;j++){
                   3302:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3303:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3304:          }
                   3305:        for(d=0; d<dh[mi][i]; d++){
                   3306:          newm=savm;
                   3307:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3308:          cov[2]=agexact;
                   3309:          if(nagesqr==1)
                   3310:            cov[3]= agexact*agexact;
                   3311:          for (kk=1; kk<=cptcovage;kk++) {
                   3312:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3313:          }
1.126     brouard  3314:        
1.226     brouard  3315:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3316:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3317:          savm=oldm;
                   3318:          oldm=newm;
                   3319:        } /* end mult */
                   3320:       
                   3321:        s1=s[mw[mi][i]][i];
                   3322:        s2=s[mw[mi+1][i]][i];
                   3323:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3324:        ipmx +=1;
                   3325:        sw += weight[i];
                   3326:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3327:        /*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]);*/
                   3328:       } /* end of wave */
                   3329:     } /* end of individual */
                   3330:   } /* End of if */
                   3331:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3332:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3333:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3334:   return -l;
1.126     brouard  3335: }
                   3336: 
                   3337: /*************** log-likelihood *************/
                   3338: double funcone( double *x)
                   3339: {
1.228     brouard  3340:   /* Same as func but slower because of a lot of printf and if */
1.126     brouard  3341:   int i, ii, j, k, mi, d, kk;
1.228     brouard  3342:   int ioffset=0;
1.131     brouard  3343:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  3344:   double **out;
                   3345:   double lli; /* Individual log likelihood */
                   3346:   double llt;
                   3347:   int s1, s2;
1.228     brouard  3348:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   3349: 
1.126     brouard  3350:   double bbh, survp;
1.187     brouard  3351:   double agexact;
1.214     brouard  3352:   double agebegin, ageend;
1.126     brouard  3353:   /*extern weight */
                   3354:   /* We are differentiating ll according to initial status */
                   3355:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3356:   /*for(i=1;i<imx;i++) 
                   3357:     printf(" %d\n",s[4][i]);
                   3358:   */
                   3359:   cov[1]=1.;
                   3360: 
                   3361:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3362:   ioffset=0;
                   3363:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.225     brouard  3364:     ioffset=2+nagesqr+cptcovage;
1.232   ! brouard  3365:     /* Fixed */
1.224     brouard  3366:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232   ! brouard  3367:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
        !          3368:     for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
        !          3369:       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)*/
        !          3370: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
        !          3371: /*    cov[2+6]=covar[Tvar[6]][i];  */
        !          3372: /*    cov[2+6]=covar[2][i]; V2  */
        !          3373: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
        !          3374: /*    cov[2+7]=covar[Tvar[7]][i];  */
        !          3375: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
        !          3376: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
        !          3377: /*    cov[2+9]=covar[Tvar[9]][i];  */
        !          3378: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  3379:     }
1.232   ! brouard  3380:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
        !          3381:     /*   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?)*\/ */
        !          3382:     /* } */
1.231     brouard  3383:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   3384:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   3385:     /* } */
1.225     brouard  3386:     
1.232   ! brouard  3387:     /* Wave varying (but not age varying) */
1.226     brouard  3388:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.232   ! brouard  3389:       for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
        !          3390:                                cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarFind[k]]][i];
        !          3391:                        }
        !          3392:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
1.231     brouard  3393:                                /* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3394:                                /* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
1.232   ! brouard  3395:                                /* k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
        !          3396:                                /* cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
1.231     brouard  3397:                                /* 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  3398:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
        !          3399:                        /*      iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
        !          3400:                        /*      /\* 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]); *\/ */
        !          3401:                        /*      cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
        !          3402:       /* } */
1.126     brouard  3403:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.231     brouard  3404:                                for (j=1;j<=nlstate+ndeath;j++){
                   3405:                                        oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3406:                                        savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3407:                                }
1.214     brouard  3408:       
                   3409:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   3410:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   3411:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.231     brouard  3412:                                /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   3413:                                        and mw[mi+1][i]. dh depends on stepm.*/
                   3414:                                newm=savm;
                   3415:                                agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3416:                                cov[2]=agexact;
                   3417:                                if(nagesqr==1)
                   3418:                                        cov[3]= agexact*agexact;
                   3419:                                for (kk=1; kk<=cptcovage;kk++) {
                   3420:                                        cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3421:                                }
                   3422:                                /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   3423:                                /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3424:                                out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3425:                                                                                 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3426:                                /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   3427:                                /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   3428:                                savm=oldm;
                   3429:                                oldm=newm;
1.126     brouard  3430:       } /* end mult */
                   3431:       
                   3432:       s1=s[mw[mi][i]][i];
                   3433:       s2=s[mw[mi+1][i]][i];
1.217     brouard  3434:       /* if(s2==-1){ */
                   3435:       /*       printf(" s1=%d, s2=%d i=%d \n", s1, s2, i); */
                   3436:       /*       /\* exit(1); *\/ */
                   3437:       /* } */
1.126     brouard  3438:       bbh=(double)bh[mi][i]/(double)stepm; 
                   3439:       /* bias is positive if real duration
                   3440:        * is higher than the multiple of stepm and negative otherwise.
                   3441:        */
                   3442:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.232   ! brouard  3443:                                lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3444:       } else if  ( s2==-1 ) { /* alive */
1.232   ! brouard  3445:                                for (j=1,survp=0. ; j<=nlstate; j++) 
        !          3446:                                        survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
        !          3447:                                lli= log(survp);
1.126     brouard  3448:       }else if (mle==1){
1.232   ! brouard  3449:                                lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  3450:       } else if(mle==2){
1.232   ! brouard  3451:                                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  3452:       } else if(mle==3){  /* exponential inter-extrapolation */
1.232   ! brouard  3453:                                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  3454:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.232   ! brouard  3455:                                lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  3456:       } else{  /* mle=0 back to 1 */
1.232   ! brouard  3457:                                lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
        !          3458:                                /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  3459:       } /* End of if */
                   3460:       ipmx +=1;
                   3461:       sw += weight[i];
                   3462:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  3463:       /*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  3464:       if(globpr){
1.232   ! brouard  3465:                                fprintf(ficresilk,"%9ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  3466:  %11.6f %11.6f %11.6f ", \
1.232   ! brouard  3467:                                                                num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
        !          3468:                                                                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
        !          3469:                                for(k=1,llt=0.,l=0.; k<=nlstate; k++){
        !          3470:                                        llt +=ll[k]*gipmx/gsw;
        !          3471:                                        fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
        !          3472:                                }
        !          3473:                                fprintf(ficresilk," %10.6f\n", -llt);
1.126     brouard  3474:       }
1.232   ! brouard  3475:        } /* end of wave */
        !          3476: } /* end of individual */
        !          3477: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
        !          3478: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
        !          3479: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
        !          3480: if(globpr==0){ /* First time we count the contributions and weights */
        !          3481:        gipmx=ipmx;
        !          3482:        gsw=sw;
        !          3483: }
        !          3484: return -l;
1.126     brouard  3485: }
                   3486: 
                   3487: 
                   3488: /*************** function likelione ***********/
                   3489: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   3490: {
                   3491:   /* This routine should help understanding what is done with 
                   3492:      the selection of individuals/waves and
                   3493:      to check the exact contribution to the likelihood.
                   3494:      Plotting could be done.
                   3495:    */
                   3496:   int k;
                   3497: 
                   3498:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  3499:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  3500:     strcat(fileresilk,fileresu);
1.126     brouard  3501:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   3502:       printf("Problem with resultfile: %s\n", fileresilk);
                   3503:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   3504:     }
1.214     brouard  3505:     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");
                   3506:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  3507:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   3508:     for(k=1; k<=nlstate; k++) 
                   3509:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   3510:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   3511:   }
                   3512: 
                   3513:   *fretone=(*funcone)(p);
                   3514:   if(*globpri !=0){
                   3515:     fclose(ficresilk);
1.205     brouard  3516:     if (mle ==0)
                   3517:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   3518:     else if(mle >=1)
                   3519:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   3520:     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  3521:     
1.208     brouard  3522:       
                   3523:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  3524:       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  3525: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   3526:     }
1.207     brouard  3527:     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  3528: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3529:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  3530: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3531:     fflush(fichtm);
1.205     brouard  3532:   }
1.126     brouard  3533:   return;
                   3534: }
                   3535: 
                   3536: 
                   3537: /*********** Maximum Likelihood Estimation ***************/
                   3538: 
                   3539: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   3540: {
1.165     brouard  3541:   int i,j, iter=0;
1.126     brouard  3542:   double **xi;
                   3543:   double fret;
                   3544:   double fretone; /* Only one call to likelihood */
                   3545:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  3546: 
                   3547: #ifdef NLOPT
                   3548:   int creturn;
                   3549:   nlopt_opt opt;
                   3550:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   3551:   double *lb;
                   3552:   double minf; /* the minimum objective value, upon return */
                   3553:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   3554:   myfunc_data dinst, *d = &dinst;
                   3555: #endif
                   3556: 
                   3557: 
1.126     brouard  3558:   xi=matrix(1,npar,1,npar);
                   3559:   for (i=1;i<=npar;i++)
                   3560:     for (j=1;j<=npar;j++)
                   3561:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   3562:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  3563:   strcpy(filerespow,"POW_"); 
1.126     brouard  3564:   strcat(filerespow,fileres);
                   3565:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   3566:     printf("Problem with resultfile: %s\n", filerespow);
                   3567:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   3568:   }
                   3569:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   3570:   for (i=1;i<=nlstate;i++)
                   3571:     for(j=1;j<=nlstate+ndeath;j++)
                   3572:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   3573:   fprintf(ficrespow,"\n");
1.162     brouard  3574: #ifdef POWELL
1.126     brouard  3575:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  3576: #endif
1.126     brouard  3577: 
1.162     brouard  3578: #ifdef NLOPT
                   3579: #ifdef NEWUOA
                   3580:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   3581: #else
                   3582:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   3583: #endif
                   3584:   lb=vector(0,npar-1);
                   3585:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   3586:   nlopt_set_lower_bounds(opt, lb);
                   3587:   nlopt_set_initial_step1(opt, 0.1);
                   3588:   
                   3589:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   3590:   d->function = func;
                   3591:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   3592:   nlopt_set_min_objective(opt, myfunc, d);
                   3593:   nlopt_set_xtol_rel(opt, ftol);
                   3594:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   3595:     printf("nlopt failed! %d\n",creturn); 
                   3596:   }
                   3597:   else {
                   3598:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   3599:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   3600:     iter=1; /* not equal */
                   3601:   }
                   3602:   nlopt_destroy(opt);
                   3603: #endif
1.126     brouard  3604:   free_matrix(xi,1,npar,1,npar);
                   3605:   fclose(ficrespow);
1.203     brouard  3606:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   3607:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  3608:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  3609: 
                   3610: }
                   3611: 
                   3612: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  3613: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  3614: {
                   3615:   double  **a,**y,*x,pd;
1.203     brouard  3616:   /* double **hess; */
1.164     brouard  3617:   int i, j;
1.126     brouard  3618:   int *indx;
                   3619: 
                   3620:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  3621:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  3622:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   3623:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   3624:   double gompertz(double p[]);
1.203     brouard  3625:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  3626: 
                   3627:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   3628:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   3629:   for (i=1;i<=npar;i++){
1.203     brouard  3630:     printf("%d-",i);fflush(stdout);
                   3631:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  3632:    
                   3633:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   3634:     
                   3635:     /*  printf(" %f ",p[i]);
                   3636:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   3637:   }
                   3638:   
                   3639:   for (i=1;i<=npar;i++) {
                   3640:     for (j=1;j<=npar;j++)  {
                   3641:       if (j>i) { 
1.203     brouard  3642:        printf(".%d-%d",i,j);fflush(stdout);
                   3643:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   3644:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  3645:        
                   3646:        hess[j][i]=hess[i][j];    
                   3647:        /*printf(" %lf ",hess[i][j]);*/
                   3648:       }
                   3649:     }
                   3650:   }
                   3651:   printf("\n");
                   3652:   fprintf(ficlog,"\n");
                   3653: 
                   3654:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   3655:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   3656:   
                   3657:   a=matrix(1,npar,1,npar);
                   3658:   y=matrix(1,npar,1,npar);
                   3659:   x=vector(1,npar);
                   3660:   indx=ivector(1,npar);
                   3661:   for (i=1;i<=npar;i++)
                   3662:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   3663:   ludcmp(a,npar,indx,&pd);
                   3664: 
                   3665:   for (j=1;j<=npar;j++) {
                   3666:     for (i=1;i<=npar;i++) x[i]=0;
                   3667:     x[j]=1;
                   3668:     lubksb(a,npar,indx,x);
                   3669:     for (i=1;i<=npar;i++){ 
                   3670:       matcov[i][j]=x[i];
                   3671:     }
                   3672:   }
                   3673: 
                   3674:   printf("\n#Hessian matrix#\n");
                   3675:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   3676:   for (i=1;i<=npar;i++) { 
                   3677:     for (j=1;j<=npar;j++) { 
1.203     brouard  3678:       printf("%.6e ",hess[i][j]);
                   3679:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  3680:     }
                   3681:     printf("\n");
                   3682:     fprintf(ficlog,"\n");
                   3683:   }
                   3684: 
1.203     brouard  3685:   /* printf("\n#Covariance matrix#\n"); */
                   3686:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   3687:   /* for (i=1;i<=npar;i++) {  */
                   3688:   /*   for (j=1;j<=npar;j++) {  */
                   3689:   /*     printf("%.6e ",matcov[i][j]); */
                   3690:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   3691:   /*   } */
                   3692:   /*   printf("\n"); */
                   3693:   /*   fprintf(ficlog,"\n"); */
                   3694:   /* } */
                   3695: 
1.126     brouard  3696:   /* Recompute Inverse */
1.203     brouard  3697:   /* for (i=1;i<=npar;i++) */
                   3698:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   3699:   /* ludcmp(a,npar,indx,&pd); */
                   3700: 
                   3701:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   3702: 
                   3703:   /* for (j=1;j<=npar;j++) { */
                   3704:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   3705:   /*   x[j]=1; */
                   3706:   /*   lubksb(a,npar,indx,x); */
                   3707:   /*   for (i=1;i<=npar;i++){  */
                   3708:   /*     y[i][j]=x[i]; */
                   3709:   /*     printf("%.3e ",y[i][j]); */
                   3710:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   3711:   /*   } */
                   3712:   /*   printf("\n"); */
                   3713:   /*   fprintf(ficlog,"\n"); */
                   3714:   /* } */
                   3715: 
                   3716:   /* Verifying the inverse matrix */
                   3717: #ifdef DEBUGHESS
                   3718:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  3719: 
1.203     brouard  3720:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   3721:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  3722: 
                   3723:   for (j=1;j<=npar;j++) {
                   3724:     for (i=1;i<=npar;i++){ 
1.203     brouard  3725:       printf("%.2f ",y[i][j]);
                   3726:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  3727:     }
                   3728:     printf("\n");
                   3729:     fprintf(ficlog,"\n");
                   3730:   }
1.203     brouard  3731: #endif
1.126     brouard  3732: 
                   3733:   free_matrix(a,1,npar,1,npar);
                   3734:   free_matrix(y,1,npar,1,npar);
                   3735:   free_vector(x,1,npar);
                   3736:   free_ivector(indx,1,npar);
1.203     brouard  3737:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  3738: 
                   3739: 
                   3740: }
                   3741: 
                   3742: /*************** hessian matrix ****************/
                   3743: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  3744: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  3745:   int i;
                   3746:   int l=1, lmax=20;
1.203     brouard  3747:   double k1,k2, res, fx;
1.132     brouard  3748:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  3749:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   3750:   int k=0,kmax=10;
                   3751:   double l1;
                   3752: 
                   3753:   fx=func(x);
                   3754:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  3755:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  3756:     l1=pow(10,l);
                   3757:     delts=delt;
                   3758:     for(k=1 ; k <kmax; k=k+1){
                   3759:       delt = delta*(l1*k);
                   3760:       p2[theta]=x[theta] +delt;
1.145     brouard  3761:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  3762:       p2[theta]=x[theta]-delt;
                   3763:       k2=func(p2)-fx;
                   3764:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  3765:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  3766:       
1.203     brouard  3767: #ifdef DEBUGHESSII
1.126     brouard  3768:       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);
                   3769:       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);
                   3770: #endif
                   3771:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   3772:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   3773:        k=kmax;
                   3774:       }
                   3775:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  3776:        k=kmax; l=lmax*10;
1.126     brouard  3777:       }
                   3778:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   3779:        delts=delt;
                   3780:       }
1.203     brouard  3781:     } /* End loop k */
1.126     brouard  3782:   }
                   3783:   delti[theta]=delts;
                   3784:   return res; 
                   3785:   
                   3786: }
                   3787: 
1.203     brouard  3788: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  3789: {
                   3790:   int i;
1.164     brouard  3791:   int l=1, lmax=20;
1.126     brouard  3792:   double k1,k2,k3,k4,res,fx;
1.132     brouard  3793:   double p2[MAXPARM+1];
1.203     brouard  3794:   int k, kmax=1;
                   3795:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  3796: 
                   3797:   int firstime=0;
1.203     brouard  3798:   
1.126     brouard  3799:   fx=func(x);
1.203     brouard  3800:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  3801:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  3802:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   3803:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  3804:     k1=func(p2)-fx;
                   3805:   
1.203     brouard  3806:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   3807:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  3808:     k2=func(p2)-fx;
                   3809:   
1.203     brouard  3810:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   3811:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  3812:     k3=func(p2)-fx;
                   3813:   
1.203     brouard  3814:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   3815:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  3816:     k4=func(p2)-fx;
1.203     brouard  3817:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   3818:     if(k1*k2*k3*k4 <0.){
1.208     brouard  3819:       firstime=1;
1.203     brouard  3820:       kmax=kmax+10;
1.208     brouard  3821:     }
                   3822:     if(kmax >=10 || firstime ==1){
1.218     brouard  3823:       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);
                   3824:       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  3825:       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);
                   3826:       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);
                   3827:     }
                   3828: #ifdef DEBUGHESSIJ
                   3829:     v1=hess[thetai][thetai];
                   3830:     v2=hess[thetaj][thetaj];
                   3831:     cv12=res;
                   3832:     /* Computing eigen value of Hessian matrix */
                   3833:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   3834:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   3835:     if ((lc2 <0) || (lc1 <0) ){
                   3836:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   3837:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   3838:       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);
                   3839:       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);
                   3840:     }
1.126     brouard  3841: #endif
                   3842:   }
                   3843:   return res;
                   3844: }
                   3845: 
1.203     brouard  3846:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   3847: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   3848: /* { */
                   3849: /*   int i; */
                   3850: /*   int l=1, lmax=20; */
                   3851: /*   double k1,k2,k3,k4,res,fx; */
                   3852: /*   double p2[MAXPARM+1]; */
                   3853: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   3854: /*   int k=0,kmax=10; */
                   3855: /*   double l1; */
                   3856:   
                   3857: /*   fx=func(x); */
                   3858: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   3859: /*     l1=pow(10,l); */
                   3860: /*     delts=delt; */
                   3861: /*     for(k=1 ; k <kmax; k=k+1){ */
                   3862: /*       delt = delti*(l1*k); */
                   3863: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   3864: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   3865: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   3866: /*       k1=func(p2)-fx; */
                   3867:       
                   3868: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   3869: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   3870: /*       k2=func(p2)-fx; */
                   3871:       
                   3872: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   3873: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   3874: /*       k3=func(p2)-fx; */
                   3875:       
                   3876: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   3877: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   3878: /*       k4=func(p2)-fx; */
                   3879: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   3880: /* #ifdef DEBUGHESSIJ */
                   3881: /*       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); */
                   3882: /*       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); */
                   3883: /* #endif */
                   3884: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   3885: /*     k=kmax; */
                   3886: /*       } */
                   3887: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   3888: /*     k=kmax; l=lmax*10; */
                   3889: /*       } */
                   3890: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   3891: /*     delts=delt; */
                   3892: /*       } */
                   3893: /*     } /\* End loop k *\/ */
                   3894: /*   } */
                   3895: /*   delti[theta]=delts; */
                   3896: /*   return res;  */
                   3897: /* } */
                   3898: 
                   3899: 
1.126     brouard  3900: /************** Inverse of matrix **************/
                   3901: void ludcmp(double **a, int n, int *indx, double *d) 
                   3902: { 
                   3903:   int i,imax,j,k; 
                   3904:   double big,dum,sum,temp; 
                   3905:   double *vv; 
                   3906:  
                   3907:   vv=vector(1,n); 
                   3908:   *d=1.0; 
                   3909:   for (i=1;i<=n;i++) { 
                   3910:     big=0.0; 
                   3911:     for (j=1;j<=n;j++) 
                   3912:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   3913:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   3914:     vv[i]=1.0/big; 
                   3915:   } 
                   3916:   for (j=1;j<=n;j++) { 
                   3917:     for (i=1;i<j;i++) { 
                   3918:       sum=a[i][j]; 
                   3919:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   3920:       a[i][j]=sum; 
                   3921:     } 
                   3922:     big=0.0; 
                   3923:     for (i=j;i<=n;i++) { 
                   3924:       sum=a[i][j]; 
                   3925:       for (k=1;k<j;k++) 
                   3926:        sum -= a[i][k]*a[k][j]; 
                   3927:       a[i][j]=sum; 
                   3928:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   3929:        big=dum; 
                   3930:        imax=i; 
                   3931:       } 
                   3932:     } 
                   3933:     if (j != imax) { 
                   3934:       for (k=1;k<=n;k++) { 
                   3935:        dum=a[imax][k]; 
                   3936:        a[imax][k]=a[j][k]; 
                   3937:        a[j][k]=dum; 
                   3938:       } 
                   3939:       *d = -(*d); 
                   3940:       vv[imax]=vv[j]; 
                   3941:     } 
                   3942:     indx[j]=imax; 
                   3943:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   3944:     if (j != n) { 
                   3945:       dum=1.0/(a[j][j]); 
                   3946:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   3947:     } 
                   3948:   } 
                   3949:   free_vector(vv,1,n);  /* Doesn't work */
                   3950: ;
                   3951: } 
                   3952: 
                   3953: void lubksb(double **a, int n, int *indx, double b[]) 
                   3954: { 
                   3955:   int i,ii=0,ip,j; 
                   3956:   double sum; 
                   3957:  
                   3958:   for (i=1;i<=n;i++) { 
                   3959:     ip=indx[i]; 
                   3960:     sum=b[ip]; 
                   3961:     b[ip]=b[i]; 
                   3962:     if (ii) 
                   3963:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   3964:     else if (sum) ii=i; 
                   3965:     b[i]=sum; 
                   3966:   } 
                   3967:   for (i=n;i>=1;i--) { 
                   3968:     sum=b[i]; 
                   3969:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   3970:     b[i]=sum/a[i][i]; 
                   3971:   } 
                   3972: } 
                   3973: 
                   3974: void pstamp(FILE *fichier)
                   3975: {
1.196     brouard  3976:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  3977: }
                   3978: 
                   3979: /************ Frequencies ********************/
1.226     brouard  3980: void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
                   3981:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   3982:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
                   3983: {  /* Some frequencies */
                   3984:   
1.227     brouard  3985:   int i, m, jk, j1, bool, z1,j, k, iv;
1.226     brouard  3986:   int iind=0, iage=0;
                   3987:   int mi; /* Effective wave */
                   3988:   int first;
                   3989:   double ***freq; /* Frequencies */
                   3990:   double *meanq;
                   3991:   double **meanqt;
                   3992:   double *pp, **prop, *posprop, *pospropt;
                   3993:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   3994:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   3995:   double agebegin, ageend;
                   3996:     
                   3997:   pp=vector(1,nlstate);
                   3998:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
                   3999:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   4000:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   4001:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   4002:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
                   4003:   meanqt=matrix(1,lastpass,1,nqtveff);
                   4004:   strcpy(fileresp,"P_");
                   4005:   strcat(fileresp,fileresu);
                   4006:   /*strcat(fileresphtm,fileresu);*/
                   4007:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   4008:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   4009:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   4010:     exit(0);
                   4011:   }
1.214     brouard  4012: 
1.226     brouard  4013:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   4014:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   4015:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4016:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4017:     fflush(ficlog);
                   4018:     exit(70); 
                   4019:   }
                   4020:   else{
                   4021:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.214     brouard  4022: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   4023: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4024:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4025:   }
                   4026:   fprintf(ficresphtm,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Frequencies and prevalence by age at begin of transition</h4>\n",fileresphtm, fileresphtm);
1.214     brouard  4027:     
1.226     brouard  4028:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   4029:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   4030:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4031:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4032:     fflush(ficlog);
                   4033:     exit(70); 
                   4034:   }
                   4035:   else{
                   4036:     fprintf(ficresphtmfr,"<html><head>\n<title>IMaCh PHTM_Frequency table %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.214     brouard  4037: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   4038: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4039:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4040:   }
                   4041:   fprintf(ficresphtmfr,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Frequencies of all effective transitions by age at begin of transition </h4>Unknown status is -1<br/>\n",fileresphtmfr, fileresphtmfr);
1.214     brouard  4042: 
1.226     brouard  4043:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+3+AGEMARGE);
                   4044:   j1=0;
1.126     brouard  4045:   
1.227     brouard  4046:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
                   4047:   j=cptcoveff;  /* Only dummy covariates of the model */
1.226     brouard  4048:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.220     brouard  4049: 
1.226     brouard  4050:   first=1;
1.220     brouard  4051: 
1.226     brouard  4052:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   4053:      reference=low_education V1=0,V2=0
                   4054:      med_educ                V1=1 V2=0, 
                   4055:      high_educ               V1=0 V2=1
                   4056:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcoveff 
                   4057:   */
1.126     brouard  4058: 
1.227     brouard  4059:   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  4060:     posproptt=0.;
                   4061:     /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   4062:       scanf("%d", i);*/
                   4063:     for (i=-5; i<=nlstate+ndeath; i++)  
                   4064:       for (jk=-5; jk<=nlstate+ndeath; jk++)  
1.231     brouard  4065:                                for(m=iagemin; m <= iagemax+3; m++)
                   4066:                                        freq[i][jk][m]=0;
                   4067:                
1.226     brouard  4068:     for (i=1; i<=nlstate; i++)  {
                   4069:       for(m=iagemin; m <= iagemax+3; m++)
1.231     brouard  4070:                                prop[i][m]=0;
1.226     brouard  4071:       posprop[i]=0;
                   4072:       pospropt[i]=0;
                   4073:     }
1.227     brouard  4074:     /* for (z1=1; z1<= nqfveff; z1++) {   */
                   4075:     /*   meanq[z1]+=0.; */
                   4076:     /*   for(m=1;m<=lastpass;m++){ */
                   4077:     /*         meanqt[m][z1]=0.; */
                   4078:     /*   } */
                   4079:     /* } */
1.231     brouard  4080:                
1.226     brouard  4081:     dateintsum=0;
                   4082:     k2cpt=0;
1.227     brouard  4083:     /* For that combination of covariate j1, we count and print the frequencies in one pass */
1.226     brouard  4084:     for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   4085:       bool=1;
1.227     brouard  4086:       if(anyvaryingduminmodel==0){ /* If All fixed covariates */
1.231     brouard  4087:                                if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
1.227     brouard  4088:          /* for (z1=1; z1<= nqfveff; z1++) {   */
                   4089:          /*   meanq[z1]+=coqvar[Tvar[z1]][iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   4090:          /* } */
1.231     brouard  4091:                                        for (z1=1; z1<=cptcoveff; z1++) {  
                   4092:                                                /* if(Tvaraff[z1] ==-20){ */
                   4093:                                                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   4094:                                                /* }else  if(Tvaraff[z1] ==-10){ */
                   4095:                                                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
                   4096:                                                /* }else  */
                   4097:                                                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
                   4098:                                                        /* Tests if this individual iind responded to j1 (V4=1 V3=0) */
                   4099:                                                        bool=0;
                   4100:                                                        /* 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", 
                   4101:                                                                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   4102:                                                                 j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
                   4103:                                                        /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   4104:                                                } /* Onlyf fixed */
                   4105:                                        } /* end z1 */
                   4106:                                } /* cptcovn > 0 */
1.227     brouard  4107:       } /* end any */
                   4108:       if (bool==1){ /* We selected an individual iind satisfying combination j1 or all fixed */
1.231     brouard  4109:                                /* for(m=firstpass; m<=lastpass; m++){ */
                   4110:                                for(mi=1; mi<wav[iind];mi++){ /* For that wave */
                   4111:                                        m=mw[mi][iind];
                   4112:                                        if(anyvaryingduminmodel==1){ /* Some are varying covariates */
                   4113:                                                for (z1=1; z1<=cptcoveff; z1++) {
                   4114:                                                        if( Fixed[Tmodelind[z1]]==1){
                   4115:                                                                iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   4116:                                                                if (cotvar[m][iv][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality */
                   4117:                                                                        bool=0;
                   4118:                                                        }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
                   4119:                                                                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   4120:                                                                        bool=0;
                   4121:                                                                }
                   4122:                                                        }
                   4123:                                                }
                   4124:                                        }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   4125:                                        /* bool =0 we keep that guy which corresponds to the combination of dummy values */
                   4126:                                        if(bool==1){
                   4127:                                                /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   4128:                                                         and mw[mi+1][iind]. dh depends on stepm. */
                   4129:                                                agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   4130:                                                ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   4131:                                                if(m >=firstpass && m <=lastpass){
                   4132:                                                        k2=anint[m][iind]+(mint[m][iind]/12.);
                   4133:                                                        /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   4134:                                                        if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   4135:                                                        if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   4136:                                                        if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   4137:                                                                prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   4138:                                                        if (m<lastpass) {
                   4139:                                                                /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   4140:                                                                /*   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]); */
                   4141:                                                                if(s[m][iind]==-1)
                   4142:                                                                        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.));
                   4143:                                                                freq[s[m][iind]][s[m+1][iind]][(int)agev[m][iind]] += weight[iind]; /* At age of beginning of transition, where status is known */
                   4144:                                                                /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   4145:                                                                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 */
                   4146:                                                        }
                   4147:                                                } /* end if between passes */  
                   4148:                                                if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99)) {
                   4149:                                                        dateintsum=dateintsum+k2;
                   4150:                                                        k2cpt++;
                   4151:                                                        /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
                   4152:                                                }
                   4153:                                        } /* end bool 2 */
                   4154:                                } /* end m */
1.226     brouard  4155:       } /* end bool */
                   4156:     } /* end iind = 1 to imx */
                   4157:     /* prop[s][age] is feeded for any initial and valid live state as well as
                   4158:        freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
1.231     brouard  4159:                
                   4160:                
1.226     brouard  4161:     /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   4162:     pstamp(ficresp);
1.227     brouard  4163:     /* if  (ncoveff>0) { */
                   4164:     if  (cptcoveff>0) {
1.226     brouard  4165:       fprintf(ficresp, "\n#********** Variable "); 
                   4166:       fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   4167:       fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
1.227     brouard  4168:       for (z1=1; z1<=cptcoveff; z1++){
1.231     brouard  4169:                                fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4170:                                fprintf(ficresphtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4171:                                fprintf(ficresphtmfr, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.226     brouard  4172:       }
                   4173:       fprintf(ficresp, "**********\n#");
                   4174:       fprintf(ficresphtm, "**********</h3>\n");
                   4175:       fprintf(ficresphtmfr, "**********</h3>\n");
                   4176:       fprintf(ficlog, "\n#********** Variable "); 
1.227     brouard  4177:       for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.226     brouard  4178:       fprintf(ficlog, "**********\n");
                   4179:     }
                   4180:     fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
                   4181:     for(i=1; i<=nlstate;i++) {
                   4182:       fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
                   4183:       fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   4184:     }
                   4185:     fprintf(ficresp, "\n");
                   4186:     fprintf(ficresphtm, "\n");
1.231     brouard  4187:                
1.226     brouard  4188:     /* Header of frequency table by age */
                   4189:     fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   4190:     fprintf(ficresphtmfr,"<th>Age</th> ");
                   4191:     for(jk=-1; jk <=nlstate+ndeath; jk++){
                   4192:       for(m=-1; m <=nlstate+ndeath; m++){
1.231     brouard  4193:                                if(jk!=0 && m!=0)
                   4194:                                        fprintf(ficresphtmfr,"<th>%d%d</th> ",jk,m);
1.226     brouard  4195:       }
                   4196:     }
                   4197:     fprintf(ficresphtmfr, "\n");
1.231     brouard  4198:                
1.226     brouard  4199:     /* For each age */
                   4200:     for(iage=iagemin; iage <= iagemax+3; iage++){
                   4201:       fprintf(ficresphtm,"<tr>");
                   4202:       if(iage==iagemax+1){
1.231     brouard  4203:                                fprintf(ficlog,"1");
                   4204:                                fprintf(ficresphtmfr,"<tr><th>0</th> ");
1.226     brouard  4205:       }else if(iage==iagemax+2){
1.231     brouard  4206:                                fprintf(ficlog,"0");
                   4207:                                fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
1.226     brouard  4208:       }else if(iage==iagemax+3){
1.231     brouard  4209:                                fprintf(ficlog,"Total");
                   4210:                                fprintf(ficresphtmfr,"<tr><th>Total</th> ");
1.226     brouard  4211:       }else{
1.231     brouard  4212:                                if(first==1){
                   4213:                                        first=0;
                   4214:                                        printf("See log file for details...\n");
                   4215:                                }
                   4216:                                fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   4217:                                fprintf(ficlog,"Age %d", iage);
1.226     brouard  4218:       }
                   4219:       for(jk=1; jk <=nlstate ; jk++){
1.231     brouard  4220:                                for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   4221:                                        pp[jk] += freq[jk][m][iage]; 
1.226     brouard  4222:       }
                   4223:       for(jk=1; jk <=nlstate ; jk++){
1.231     brouard  4224:                                for(m=-1, pos=0; m <=0 ; m++)
                   4225:                                        pos += freq[jk][m][iage];
                   4226:                                if(pp[jk]>=1.e-10){
                   4227:                                        if(first==1){
                   4228:                                                printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   4229:                                        }
                   4230:                                        fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   4231:                                }else{
                   4232:                                        if(first==1)
                   4233:                                                printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   4234:                                        fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   4235:                                }
1.226     brouard  4236:       }
1.231     brouard  4237:                        
1.226     brouard  4238:       for(jk=1; jk <=nlstate ; jk++){ 
1.231     brouard  4239:                                /* posprop[jk]=0; */
                   4240:                                for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   4241:                                        pp[jk] += freq[jk][m][iage];
1.226     brouard  4242:       }        /* pp[jk] is the total number of transitions starting from state jk and any ending status until this age */
1.231     brouard  4243:                        
1.226     brouard  4244:       for(jk=1,pos=0, pospropta=0.; jk <=nlstate ; jk++){
1.231     brouard  4245:                                pos += pp[jk]; /* pos is the total number of transitions until this age */
                   4246:                                posprop[jk] += prop[jk][iage]; /* prop is the number of transitions from a live state
                   4247:                                                                                                                                                                        from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   4248:                                pospropta += prop[jk][iage]; /* prop is the number of transitions from a live state
                   4249:                                                                                                                                                                from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
1.226     brouard  4250:       }
                   4251:       for(jk=1; jk <=nlstate ; jk++){
1.231     brouard  4252:                                if(pos>=1.e-5){
                   4253:                                        if(first==1)
                   4254:                                                printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   4255:                                        fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   4256:                                }else{
                   4257:                                        if(first==1)
                   4258:                                                printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   4259:                                        fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   4260:                                }
                   4261:                                if( iage <= iagemax){
                   4262:                                        if(pos>=1.e-5){
                   4263:                                                fprintf(ficresp," %d %.5f %.0f %.0f",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
                   4264:                                                fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
                   4265:                                                /*probs[iage][jk][j1]= pp[jk]/pos;*/
                   4266:                                                /*printf("\niage=%d jk=%d j1=%d %.5f %.0f %.0f %f",iage,jk,j1,pp[jk]/pos, pp[jk],pos,probs[iage][jk][j1]);*/
                   4267:                                        }
                   4268:                                        else{
                   4269:                                                fprintf(ficresp," %d NaNq %.0f %.0f",iage,prop[jk][iage],pospropta);
                   4270:                                                fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[jk][iage],pospropta);
                   4271:                                        }
                   4272:                                }
                   4273:                                pospropt[jk] +=posprop[jk];
1.226     brouard  4274:       } /* end loop jk */
                   4275:       /* pospropt=0.; */
                   4276:       for(jk=-1; jk <=nlstate+ndeath; jk++){
1.231     brouard  4277:                                for(m=-1; m <=nlstate+ndeath; m++){
                   4278:                                        if(freq[jk][m][iage] !=0 ) { /* minimizing output */
                   4279:                                                if(first==1){
                   4280:                                                        printf(" %d%d=%.0f",jk,m,freq[jk][m][iage]);
                   4281:                                                }
                   4282:                                                fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][iage]);
                   4283:                                        }
                   4284:                                        if(jk!=0 && m!=0)
                   4285:                                                fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[jk][m][iage]);
                   4286:                                }
1.226     brouard  4287:       } /* end loop jk */
                   4288:       posproptt=0.; 
                   4289:       for(jk=1; jk <=nlstate; jk++){
1.231     brouard  4290:                                posproptt += pospropt[jk];
1.226     brouard  4291:       }
                   4292:       fprintf(ficresphtmfr,"</tr>\n ");
                   4293:       if(iage <= iagemax){
1.231     brouard  4294:                                fprintf(ficresp,"\n");
                   4295:                                fprintf(ficresphtm,"</tr>\n");
1.226     brouard  4296:       }
                   4297:       if(first==1)
1.231     brouard  4298:                                printf("Others in log...\n");
1.226     brouard  4299:       fprintf(ficlog,"\n");
                   4300:     } /* end loop age iage */
                   4301:     fprintf(ficresphtm,"<tr><th>Tot</th>");
                   4302:     for(jk=1; jk <=nlstate ; jk++){
                   4303:       if(posproptt < 1.e-5){
1.231     brouard  4304:                                fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[jk],posproptt);   
1.226     brouard  4305:       }else{
1.231     brouard  4306:                                fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[jk]/posproptt,pospropt[jk],posproptt);    
1.226     brouard  4307:       }
                   4308:     }
                   4309:     fprintf(ficresphtm,"</tr>\n");
                   4310:     fprintf(ficresphtm,"</table>\n");
                   4311:     fprintf(ficresphtmfr,"</table>\n");
                   4312:     if(posproptt < 1.e-5){
                   4313:       fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   4314:       fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   4315:       fprintf(ficres,"\n  This combination (%d) is not valid and no result will be produced\n\n",j1);
                   4316:       invalidvarcomb[j1]=1;
                   4317:     }else{
                   4318:       fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
                   4319:       invalidvarcomb[j1]=0;
                   4320:     }
                   4321:     fprintf(ficresphtmfr,"</table>\n");
                   4322:   } /* end selected combination of covariate j1 */
                   4323:   dateintmean=dateintsum/k2cpt; 
1.231     brouard  4324:        
1.226     brouard  4325:   fclose(ficresp);
                   4326:   fclose(ficresphtm);
                   4327:   fclose(ficresphtmfr);
                   4328:   free_vector(meanq,1,nqfveff);
                   4329:   free_matrix(meanqt,1,lastpass,1,nqtveff);
                   4330:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+3+AGEMARGE);
                   4331:   free_vector(pospropt,1,nlstate);
                   4332:   free_vector(posprop,1,nlstate);
                   4333:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+3+AGEMARGE);
                   4334:   free_vector(pp,1,nlstate);
                   4335:   /* End of freqsummary */
                   4336: }
1.126     brouard  4337: 
                   4338: /************ Prevalence ********************/
1.227     brouard  4339: 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)
                   4340: {  
                   4341:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   4342:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   4343:      We still use firstpass and lastpass as another selection.
                   4344:   */
1.126     brouard  4345:  
1.227     brouard  4346:   int i, m, jk, j1, bool, z1,j, iv;
                   4347:   int mi; /* Effective wave */
                   4348:   int iage;
                   4349:   double agebegin, ageend;
                   4350: 
                   4351:   double **prop;
                   4352:   double posprop; 
                   4353:   double  y2; /* in fractional years */
                   4354:   int iagemin, iagemax;
                   4355:   int first; /** to stop verbosity which is redirected to log file */
                   4356: 
                   4357:   iagemin= (int) agemin;
                   4358:   iagemax= (int) agemax;
                   4359:   /*pp=vector(1,nlstate);*/
                   4360:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
                   4361:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   4362:   j1=0;
1.222     brouard  4363:   
1.227     brouard  4364:   /*j=cptcoveff;*/
                   4365:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  4366:   
1.227     brouard  4367:   first=1;
                   4368:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of covariate */
                   4369:     for (i=1; i<=nlstate; i++)  
                   4370:       for(iage=iagemin-AGEMARGE; iage <= iagemax+3+AGEMARGE; iage++)
                   4371:        prop[i][iage]=0.0;
                   4372:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   4373:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   4374:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   4375:     
                   4376:     for (i=1; i<=imx; i++) { /* Each individual */
                   4377:       bool=1;
                   4378:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   4379:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   4380:        m=mw[mi][i];
                   4381:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   4382:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   4383:        for (z1=1; z1<=cptcoveff; z1++){
                   4384:          if( Fixed[Tmodelind[z1]]==1){
                   4385:            iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   4386:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality */
                   4387:              bool=0;
                   4388:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
                   4389:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   4390:              bool=0;
                   4391:            }
                   4392:        }
                   4393:        if(bool==1){ /* Otherwise we skip that wave/person */
                   4394:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   4395:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   4396:          if(m >=firstpass && m <=lastpass){
                   4397:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   4398:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   4399:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   4400:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   4401:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+3+AGEMARGE){
                   4402:                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); 
                   4403:                exit(1);
                   4404:              }
                   4405:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   4406:                /*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]]);*/
                   4407:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   4408:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   4409:              } /* end valid statuses */ 
                   4410:            } /* end selection of dates */
                   4411:          } /* end selection of waves */
                   4412:        } /* end bool */
                   4413:       } /* end wave */
                   4414:     } /* end individual */
                   4415:     for(i=iagemin; i <= iagemax+3; i++){  
                   4416:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   4417:        posprop += prop[jk][i]; 
                   4418:       } 
                   4419:       
                   4420:       for(jk=1; jk <=nlstate ; jk++){      
                   4421:        if( i <=  iagemax){ 
                   4422:          if(posprop>=1.e-5){ 
                   4423:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   4424:          } else{
                   4425:            if(first==1){
                   4426:              first=0;
                   4427:              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]);
                   4428:            }
                   4429:          }
                   4430:        } 
                   4431:       }/* end jk */ 
                   4432:     }/* end i */ 
1.222     brouard  4433:      /*} *//* end i1 */
1.227     brouard  4434:   } /* end j1 */
1.222     brouard  4435:   
1.227     brouard  4436:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   4437:   /*free_vector(pp,1,nlstate);*/
                   4438:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+3+AGEMARGE);
                   4439: }  /* End of prevalence */
1.126     brouard  4440: 
                   4441: /************* Waves Concatenation ***************/
                   4442: 
                   4443: 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)
                   4444: {
                   4445:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   4446:      Death is a valid wave (if date is known).
                   4447:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   4448:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4449:      and mw[mi+1][i]. dh depends on stepm.
1.227     brouard  4450:   */
1.126     brouard  4451: 
1.224     brouard  4452:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  4453:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   4454:      double sum=0., jmean=0.;*/
1.224     brouard  4455:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  4456:   int j, k=0,jk, ju, jl;
                   4457:   double sum=0.;
                   4458:   first=0;
1.214     brouard  4459:   firstwo=0;
1.217     brouard  4460:   firsthree=0;
1.218     brouard  4461:   firstfour=0;
1.164     brouard  4462:   jmin=100000;
1.126     brouard  4463:   jmax=-1;
                   4464:   jmean=0.;
1.224     brouard  4465: 
                   4466: /* Treating live states */
1.214     brouard  4467:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  4468:     mi=0;  /* First valid wave */
1.227     brouard  4469:     mli=0; /* Last valid wave */
1.126     brouard  4470:     m=firstpass;
1.214     brouard  4471:     while(s[m][i] <= nlstate){  /* a live state */
1.227     brouard  4472:       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 */
                   4473:        mli=m-1;/* mw[++mi][i]=m-1; */
                   4474:       }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 */
                   4475:        mw[++mi][i]=m;
                   4476:        mli=m;
1.224     brouard  4477:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   4478:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  4479:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  4480:       }
1.227     brouard  4481:       else{ /* m >= lastpass, eventual special issue with warning */
1.224     brouard  4482: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  4483:        break;
1.224     brouard  4484: #else
1.227     brouard  4485:        if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){
                   4486:          if(firsthree == 0){
                   4487:            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);
                   4488:            firsthree=1;
                   4489:          }
                   4490:          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);
                   4491:          mw[++mi][i]=m;
                   4492:          mli=m;
                   4493:        }
                   4494:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   4495:          nbwarn++;
                   4496:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified? */
                   4497:            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);
                   4498:            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);
                   4499:          }
                   4500:          break;
                   4501:        }
                   4502:        break;
1.224     brouard  4503: #endif
1.227     brouard  4504:       }/* End m >= lastpass */
1.126     brouard  4505:     }/* end while */
1.224     brouard  4506: 
1.227     brouard  4507:     /* 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  4508:     /* After last pass */
1.224     brouard  4509: /* Treating death states */
1.214     brouard  4510:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  4511:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   4512:       /* } */
1.126     brouard  4513:       mi++;    /* Death is another wave */
                   4514:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  4515:       /* Only death is a correct wave */
1.126     brouard  4516:       mw[mi][i]=m;
1.224     brouard  4517:     }
                   4518: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.227     brouard  4519:     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  4520:       /* m++; */
                   4521:       /* mi++; */
                   4522:       /* s[m][i]=nlstate+1;  /\* We are setting the status to the last of non live state *\/ */
                   4523:       /* mw[mi][i]=m; */
1.218     brouard  4524:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.227     brouard  4525:        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 */
                   4526:          nbwarn++;
                   4527:          if(firstfiv==0){
                   4528:            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 );
                   4529:            firstfiv=1;
                   4530:          }else{
                   4531:            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 );
                   4532:          }
                   4533:        }else{ /* Death occured afer last wave potential bias */
                   4534:          nberr++;
                   4535:          if(firstwo==0){
                   4536:            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 );
                   4537:            firstwo=1;
                   4538:          }
                   4539:          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 );
                   4540:        }
1.218     brouard  4541:       }else{ /* end date of interview is known */
1.227     brouard  4542:        /* death is known but not confirmed by death status at any wave */
                   4543:        if(firstfour==0){
                   4544:          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 );
                   4545:          firstfour=1;
                   4546:        }
                   4547:        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  4548:       }
1.224     brouard  4549:     } /* end if date of death is known */
                   4550: #endif
                   4551:     wav[i]=mi; /* mi should be the last effective wave (or mli) */
                   4552:     /* wav[i]=mw[mi][i]; */
1.126     brouard  4553:     if(mi==0){
                   4554:       nbwarn++;
                   4555:       if(first==0){
1.227     brouard  4556:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   4557:        first=1;
1.126     brouard  4558:       }
                   4559:       if(first==1){
1.227     brouard  4560:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  4561:       }
                   4562:     } /* end mi==0 */
                   4563:   } /* End individuals */
1.214     brouard  4564:   /* wav and mw are no more changed */
1.223     brouard  4565:        
1.214     brouard  4566:   
1.126     brouard  4567:   for(i=1; i<=imx; i++){
                   4568:     for(mi=1; mi<wav[i];mi++){
                   4569:       if (stepm <=0)
1.227     brouard  4570:        dh[mi][i]=1;
1.126     brouard  4571:       else{
1.227     brouard  4572:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                   4573:          if (agedc[i] < 2*AGESUP) {
                   4574:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   4575:            if(j==0) j=1;  /* Survives at least one month after exam */
                   4576:            else if(j<0){
                   4577:              nberr++;
                   4578:              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]);
                   4579:              j=1; /* Temporary Dangerous patch */
                   4580:              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);
                   4581:              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]);
                   4582:              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);
                   4583:            }
                   4584:            k=k+1;
                   4585:            if (j >= jmax){
                   4586:              jmax=j;
                   4587:              ijmax=i;
                   4588:            }
                   4589:            if (j <= jmin){
                   4590:              jmin=j;
                   4591:              ijmin=i;
                   4592:            }
                   4593:            sum=sum+j;
                   4594:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   4595:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   4596:          }
                   4597:        }
                   4598:        else{
                   4599:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  4600: /*       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  4601:                                        
1.227     brouard  4602:          k=k+1;
                   4603:          if (j >= jmax) {
                   4604:            jmax=j;
                   4605:            ijmax=i;
                   4606:          }
                   4607:          else if (j <= jmin){
                   4608:            jmin=j;
                   4609:            ijmin=i;
                   4610:          }
                   4611:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   4612:          /*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]);*/
                   4613:          if(j<0){
                   4614:            nberr++;
                   4615:            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]);
                   4616:            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]);
                   4617:          }
                   4618:          sum=sum+j;
                   4619:        }
                   4620:        jk= j/stepm;
                   4621:        jl= j -jk*stepm;
                   4622:        ju= j -(jk+1)*stepm;
                   4623:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   4624:          if(jl==0){
                   4625:            dh[mi][i]=jk;
                   4626:            bh[mi][i]=0;
                   4627:          }else{ /* We want a negative bias in order to only have interpolation ie
                   4628:                  * to avoid the price of an extra matrix product in likelihood */
                   4629:            dh[mi][i]=jk+1;
                   4630:            bh[mi][i]=ju;
                   4631:          }
                   4632:        }else{
                   4633:          if(jl <= -ju){
                   4634:            dh[mi][i]=jk;
                   4635:            bh[mi][i]=jl;       /* bias is positive if real duration
                   4636:                                 * is higher than the multiple of stepm and negative otherwise.
                   4637:                                 */
                   4638:          }
                   4639:          else{
                   4640:            dh[mi][i]=jk+1;
                   4641:            bh[mi][i]=ju;
                   4642:          }
                   4643:          if(dh[mi][i]==0){
                   4644:            dh[mi][i]=1; /* At least one step */
                   4645:            bh[mi][i]=ju; /* At least one step */
                   4646:            /*  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);*/
                   4647:          }
                   4648:        } /* end if mle */
1.126     brouard  4649:       }
                   4650:     } /* end wave */
                   4651:   }
                   4652:   jmean=sum/k;
                   4653:   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  4654:   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  4655: }
1.126     brouard  4656: 
                   4657: /*********** Tricode ****************************/
1.220     brouard  4658:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.126     brouard  4659: {
1.144     brouard  4660:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   4661:   /*     Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
1.169     brouard  4662:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.224     brouard  4663:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   4664:    * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
1.144     brouard  4665:   */
1.130     brouard  4666: 
1.145     brouard  4667:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136     brouard  4668:   int modmaxcovj=0; /* Modality max of covariates j */
1.145     brouard  4669:   int cptcode=0; /* Modality max of covariates j */
                   4670:   int modmincovj=0; /* Modality min of covariates j */
                   4671: 
                   4672: 
1.220     brouard  4673:   /* cptcoveff=0;  */
1.224     brouard  4674:        /* *cptcov=0; */
1.126     brouard  4675:  
1.144     brouard  4676:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  4677: 
1.224     brouard  4678:   /* Loop on covariates without age and products and no quantitative variable */
                   4679:   /* for (j=1; j<=(cptcovs); j++) { /\* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only *\/ */
1.227     brouard  4680:   for (k=1; k<=cptcovt; k++) { /* From model V1 + V2*age + V3 + V3*V4 keeps V1 + V3 = 2 only */
                   4681:     for (j=-1; (j < maxncov); j++) Ndum[j]=0;
                   4682:     if(Dummy[k]==0 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
                   4683:       switch(Fixed[k]) {
                   4684:       case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
1.231     brouard  4685:                                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*/
                   4686:                                        ij=(int)(covar[Tvar[k]][i]);
                   4687:                                        /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   4688:                                         * If product of Vn*Vm, still boolean *:
                   4689:                                         * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   4690:                                         * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   4691:                                        /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   4692:                                                 modality of the nth covariate of individual i. */
                   4693:                                        if (ij > modmaxcovj)
                   4694:                                                modmaxcovj=ij; 
                   4695:                                        else if (ij < modmincovj) 
                   4696:                                                modmincovj=ij; 
                   4697:                                        if ((ij < -1) && (ij > NCOVMAX)){
                   4698:                                                printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   4699:                                                exit(1);
                   4700:                                        }else
                   4701:                                                Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   4702:                                        /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   4703:                                        /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   4704:                                        /* getting the maximum value of the modality of the covariate
                   4705:                                                 (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   4706:                                                 female ies 1, then modmaxcovj=1.
                   4707:                                        */
                   4708:                                } /* end for loop on individuals i */
                   4709:                                printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   4710:                                fprintf(ficlog," Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   4711:                                cptcode=modmaxcovj;
                   4712:                                /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   4713:                                /*for (i=0; i<=cptcode; i++) {*/
                   4714:                                for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   4715:                                        printf("Frequencies of covariates %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   4716:                                        fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   4717:                                        if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   4718:                                                if( j != -1){
                   4719:                                                        ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   4720:                                                                                                                                 covariate for which somebody answered excluding 
                   4721:                                                                                                                                 undefined. Usually 2: 0 and 1. */
                   4722:                                                }
                   4723:                                                ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   4724:                                                                                                                                                covariate for which somebody answered including 
                   4725:                                                                                                                                                undefined. Usually 3: -1, 0 and 1. */
                   4726:                                        }       /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   4727:                                                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   4728:                                } /* Ndum[-1] number of undefined modalities */
                   4729:                        
                   4730:                                /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   4731:                                /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   4732:                                /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   4733:                                /* modmincovj=3; modmaxcovj = 7; */
                   4734:                                /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   4735:                                /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   4736:                          /*             defining two dummy variables: variables V1_1 and V1_2.*/
                   4737:              /* nbcode[Tvar[j]][ij]=k; */
                   4738:              /* nbcode[Tvar[j]][1]=0; */
                   4739:              /* nbcode[Tvar[j]][2]=1; */
                   4740:              /* nbcode[Tvar[j]][3]=2; */
                   4741:              /* To be continued (not working yet). */
                   4742:              ij=0; /* ij is similar to i but can jump over null modalities */
                   4743:                                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*/
                   4744:          if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   4745:                  break;
                   4746:                }
                   4747:                                        ij++;
                   4748:                                        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*/
                   4749:                                        cptcode = ij; /* New max modality for covar j */
                   4750:                                } /* end of loop on modality i=-1 to 1 or more */
                   4751:                                break;
1.227     brouard  4752:       case 1: /* Testing on varying covariate, could be simple and
                   4753:               * should look at waves or product of fixed *
                   4754:               * varying. No time to test -1, assuming 0 and 1 only */
1.231     brouard  4755:                                ij=0;
                   4756:                                for(i=0; i<=1;i++){
                   4757:                                        nbcode[Tvar[k]][++ij]=i;
                   4758:                                }
                   4759:                                break;
1.227     brouard  4760:       default:
1.231     brouard  4761:                                break;
1.227     brouard  4762:       } /* end switch */
                   4763:     } /* end dummy test */
1.225     brouard  4764:     
1.192     brouard  4765:     /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
                   4766:     /*         /\*recode from 0 *\/ */
                   4767:     /*                                      k is a modality. If we have model=V1+V1*sex  */
                   4768:     /*                                      then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
                   4769:     /*                                   But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
                   4770:     /*         } */
                   4771:     /*         /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
                   4772:     /*         if (ij > ncodemax[j]) { */
                   4773:     /*           printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
                   4774:     /*           fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
                   4775:     /*           break; */
                   4776:     /*         } */
                   4777:     /*   }  /\* end of loop on modality k *\/ */
1.137     brouard  4778:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   4779:   
1.225     brouard  4780:   for (k=-1; k< maxncov; k++) Ndum[k]=0; 
1.227     brouard  4781:   /* Look at fixed dummy (single or product) covariates to check empty modalities */
1.187     brouard  4782:   for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
1.225     brouard  4783:     /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
1.227     brouard  4784:     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 */ 
                   4785:     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 */
                   4786:     /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
1.225     brouard  4787:   } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   4788:   
                   4789:   ij=0;
1.227     brouard  4790:   /* for (i=0; i<=  maxncov-1; i++) { /\* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) *\/ */
                   4791:   for (k=1; k<=  cptcovt; k++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
1.225     brouard  4792:     /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.227     brouard  4793:     /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
                   4794:     if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy and non empty in the model */
                   4795:       /* If product not in single variable we don't print results */
1.225     brouard  4796:       /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
1.230     brouard  4797:       ++ij;/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, */
                   4798:       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*/
                   4799:       Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
1.231     brouard  4800:       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 */
1.227     brouard  4801:       if(Fixed[k]!=0)
                   4802:         anyvaryingduminmodel=1;
1.231     brouard  4803:                        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   4804:                        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   4805:                        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   4806:                        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   4807:                        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   4808:                        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
1.227     brouard  4809:     } 
1.225     brouard  4810:   } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   4811:   /* ij--; */
                   4812:   /* cptcoveff=ij; /\*Number of total covariates*\/ */
                   4813:   *cptcov=ij; /*Number of total real effective covariates: effective
1.231     brouard  4814:                                                         * because they can be excluded from the model and real
                   4815:                                                         * if in the model but excluded because missing values, but how to get k from ij?*/
1.227     brouard  4816:   for(j=ij+1; j<= cptcovt; j++){
                   4817:     Tvaraff[j]=0;
                   4818:     Tmodelind[j]=0;
                   4819:   }
1.228     brouard  4820:   for(j=ntveff+1; j<= cptcovt; j++){
                   4821:     TmodelInvind[j]=0;
                   4822:   }
1.227     brouard  4823:   /* To be sorted */
                   4824:   ;
1.126     brouard  4825: }
                   4826: 
1.145     brouard  4827: 
1.126     brouard  4828: /*********** Health Expectancies ****************/
                   4829: 
1.127     brouard  4830: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
1.126     brouard  4831: 
                   4832: {
                   4833:   /* Health expectancies, no variances */
1.164     brouard  4834:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  4835:   int nhstepma, nstepma; /* Decreasing with age */
                   4836:   double age, agelim, hf;
                   4837:   double ***p3mat;
                   4838:   double eip;
                   4839: 
                   4840:   pstamp(ficreseij);
                   4841:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   4842:   fprintf(ficreseij,"# Age");
                   4843:   for(i=1; i<=nlstate;i++){
                   4844:     for(j=1; j<=nlstate;j++){
                   4845:       fprintf(ficreseij," e%1d%1d ",i,j);
                   4846:     }
                   4847:     fprintf(ficreseij," e%1d. ",i);
                   4848:   }
                   4849:   fprintf(ficreseij,"\n");
                   4850: 
                   4851:   
                   4852:   if(estepm < stepm){
                   4853:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4854:   }
                   4855:   else  hstepm=estepm;   
                   4856:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   4857:    * This is mainly to measure the difference between two models: for example
                   4858:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   4859:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   4860:    * progression in between and thus overestimating or underestimating according
                   4861:    * to the curvature of the survival function. If, for the same date, we 
                   4862:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   4863:    * to compare the new estimate of Life expectancy with the same linear 
                   4864:    * hypothesis. A more precise result, taking into account a more precise
                   4865:    * curvature will be obtained if estepm is as small as stepm. */
                   4866: 
                   4867:   /* For example we decided to compute the life expectancy with the smallest unit */
                   4868:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   4869:      nhstepm is the number of hstepm from age to agelim 
                   4870:      nstepm is the number of stepm from age to agelin. 
                   4871:      Look at hpijx to understand the reason of that which relies in memory size
                   4872:      and note for a fixed period like estepm months */
                   4873:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   4874:      survival function given by stepm (the optimization length). Unfortunately it
                   4875:      means that if the survival funtion is printed only each two years of age and if
                   4876:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   4877:      results. So we changed our mind and took the option of the best precision.
                   4878:   */
                   4879:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   4880: 
                   4881:   agelim=AGESUP;
                   4882:   /* If stepm=6 months */
                   4883:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   4884:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   4885:     
                   4886: /* nhstepm age range expressed in number of stepm */
                   4887:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   4888:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   4889:   /* if (stepm >= YEARM) hstepm=1;*/
                   4890:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   4891:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4892: 
                   4893:   for (age=bage; age<=fage; age ++){ 
                   4894:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   4895:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   4896:     /* if (stepm >= YEARM) hstepm=1;*/
                   4897:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   4898: 
                   4899:     /* If stepm=6 months */
                   4900:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   4901:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   4902:     
                   4903:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   4904:     
                   4905:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   4906:     
                   4907:     printf("%d|",(int)age);fflush(stdout);
                   4908:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   4909:     
                   4910:     /* Computing expectancies */
                   4911:     for(i=1; i<=nlstate;i++)
                   4912:       for(j=1; j<=nlstate;j++)
                   4913:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   4914:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   4915:          
                   4916:          /* 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]);*/
                   4917: 
                   4918:        }
                   4919: 
                   4920:     fprintf(ficreseij,"%3.0f",age );
                   4921:     for(i=1; i<=nlstate;i++){
                   4922:       eip=0;
                   4923:       for(j=1; j<=nlstate;j++){
                   4924:        eip +=eij[i][j][(int)age];
                   4925:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   4926:       }
                   4927:       fprintf(ficreseij,"%9.4f", eip );
                   4928:     }
                   4929:     fprintf(ficreseij,"\n");
                   4930:     
                   4931:   }
                   4932:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4933:   printf("\n");
                   4934:   fprintf(ficlog,"\n");
                   4935:   
                   4936: }
                   4937: 
1.127     brouard  4938: 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[] )
1.126     brouard  4939: 
                   4940: {
                   4941:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  4942:      to initial status i, ei. .
1.126     brouard  4943:   */
                   4944:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   4945:   int nhstepma, nstepma; /* Decreasing with age */
                   4946:   double age, agelim, hf;
                   4947:   double ***p3matp, ***p3matm, ***varhe;
                   4948:   double **dnewm,**doldm;
                   4949:   double *xp, *xm;
                   4950:   double **gp, **gm;
                   4951:   double ***gradg, ***trgradg;
                   4952:   int theta;
                   4953: 
                   4954:   double eip, vip;
                   4955: 
                   4956:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   4957:   xp=vector(1,npar);
                   4958:   xm=vector(1,npar);
                   4959:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   4960:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   4961:   
                   4962:   pstamp(ficresstdeij);
                   4963:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   4964:   fprintf(ficresstdeij,"# Age");
                   4965:   for(i=1; i<=nlstate;i++){
                   4966:     for(j=1; j<=nlstate;j++)
                   4967:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   4968:     fprintf(ficresstdeij," e%1d. ",i);
                   4969:   }
                   4970:   fprintf(ficresstdeij,"\n");
                   4971: 
                   4972:   pstamp(ficrescveij);
                   4973:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   4974:   fprintf(ficrescveij,"# Age");
                   4975:   for(i=1; i<=nlstate;i++)
                   4976:     for(j=1; j<=nlstate;j++){
                   4977:       cptj= (j-1)*nlstate+i;
                   4978:       for(i2=1; i2<=nlstate;i2++)
                   4979:        for(j2=1; j2<=nlstate;j2++){
                   4980:          cptj2= (j2-1)*nlstate+i2;
                   4981:          if(cptj2 <= cptj)
                   4982:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   4983:        }
                   4984:     }
                   4985:   fprintf(ficrescveij,"\n");
                   4986:   
                   4987:   if(estepm < stepm){
                   4988:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4989:   }
                   4990:   else  hstepm=estepm;   
                   4991:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   4992:    * This is mainly to measure the difference between two models: for example
                   4993:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   4994:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   4995:    * progression in between and thus overestimating or underestimating according
                   4996:    * to the curvature of the survival function. If, for the same date, we 
                   4997:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   4998:    * to compare the new estimate of Life expectancy with the same linear 
                   4999:    * hypothesis. A more precise result, taking into account a more precise
                   5000:    * curvature will be obtained if estepm is as small as stepm. */
                   5001: 
                   5002:   /* For example we decided to compute the life expectancy with the smallest unit */
                   5003:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5004:      nhstepm is the number of hstepm from age to agelim 
                   5005:      nstepm is the number of stepm from age to agelin. 
                   5006:      Look at hpijx to understand the reason of that which relies in memory size
                   5007:      and note for a fixed period like estepm months */
                   5008:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   5009:      survival function given by stepm (the optimization length). Unfortunately it
                   5010:      means that if the survival funtion is printed only each two years of age and if
                   5011:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5012:      results. So we changed our mind and took the option of the best precision.
                   5013:   */
                   5014:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5015: 
                   5016:   /* If stepm=6 months */
                   5017:   /* nhstepm age range expressed in number of stepm */
                   5018:   agelim=AGESUP;
                   5019:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   5020:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5021:   /* if (stepm >= YEARM) hstepm=1;*/
                   5022:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5023:   
                   5024:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5025:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5026:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   5027:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   5028:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   5029:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   5030: 
                   5031:   for (age=bage; age<=fage; age ++){ 
                   5032:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5033:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5034:     /* if (stepm >= YEARM) hstepm=1;*/
                   5035:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  5036:                
1.126     brouard  5037:     /* If stepm=6 months */
                   5038:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   5039:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   5040:     
                   5041:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  5042:                
1.126     brouard  5043:     /* Computing  Variances of health expectancies */
                   5044:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   5045:        decrease memory allocation */
                   5046:     for(theta=1; theta <=npar; theta++){
                   5047:       for(i=1; i<=npar; i++){ 
1.222     brouard  5048:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5049:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  5050:       }
                   5051:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
                   5052:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
1.218     brouard  5053:                        
1.126     brouard  5054:       for(j=1; j<= nlstate; j++){
1.222     brouard  5055:        for(i=1; i<=nlstate; i++){
                   5056:          for(h=0; h<=nhstepm-1; h++){
                   5057:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   5058:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   5059:          }
                   5060:        }
1.126     brouard  5061:       }
1.218     brouard  5062:                        
1.126     brouard  5063:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  5064:        for(h=0; h<=nhstepm-1; h++){
                   5065:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   5066:        }
1.126     brouard  5067:     }/* End theta */
                   5068:     
                   5069:     
                   5070:     for(h=0; h<=nhstepm-1; h++)
                   5071:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  5072:        for(theta=1; theta <=npar; theta++)
                   5073:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  5074:     
1.218     brouard  5075:                
1.222     brouard  5076:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  5077:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  5078:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  5079:                
1.222     brouard  5080:     printf("%d|",(int)age);fflush(stdout);
                   5081:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   5082:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  5083:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  5084:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   5085:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   5086:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   5087:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   5088:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  5089:       }
                   5090:     }
1.218     brouard  5091:                
1.126     brouard  5092:     /* Computing expectancies */
                   5093:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   5094:     for(i=1; i<=nlstate;i++)
                   5095:       for(j=1; j<=nlstate;j++)
1.222     brouard  5096:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   5097:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  5098:                                        
1.222     brouard  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]);*/
1.218     brouard  5100:                                        
1.222     brouard  5101:        }
1.218     brouard  5102:                
1.126     brouard  5103:     fprintf(ficresstdeij,"%3.0f",age );
                   5104:     for(i=1; i<=nlstate;i++){
                   5105:       eip=0.;
                   5106:       vip=0.;
                   5107:       for(j=1; j<=nlstate;j++){
1.222     brouard  5108:        eip += eij[i][j][(int)age];
                   5109:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   5110:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   5111:        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  5112:       }
                   5113:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   5114:     }
                   5115:     fprintf(ficresstdeij,"\n");
1.218     brouard  5116:                
1.126     brouard  5117:     fprintf(ficrescveij,"%3.0f",age );
                   5118:     for(i=1; i<=nlstate;i++)
                   5119:       for(j=1; j<=nlstate;j++){
1.222     brouard  5120:        cptj= (j-1)*nlstate+i;
                   5121:        for(i2=1; i2<=nlstate;i2++)
                   5122:          for(j2=1; j2<=nlstate;j2++){
                   5123:            cptj2= (j2-1)*nlstate+i2;
                   5124:            if(cptj2 <= cptj)
                   5125:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   5126:          }
1.126     brouard  5127:       }
                   5128:     fprintf(ficrescveij,"\n");
1.218     brouard  5129:                
1.126     brouard  5130:   }
                   5131:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   5132:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   5133:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   5134:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   5135:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5136:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5137:   printf("\n");
                   5138:   fprintf(ficlog,"\n");
1.218     brouard  5139:        
1.126     brouard  5140:   free_vector(xm,1,npar);
                   5141:   free_vector(xp,1,npar);
                   5142:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   5143:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   5144:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   5145: }
1.218     brouard  5146:  
1.126     brouard  5147: /************ Variance ******************/
1.209     brouard  5148:  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[])
1.218     brouard  5149:  {
                   5150:    /* Variance of health expectancies */
                   5151:    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   5152:    /* double **newm;*/
                   5153:    /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
                   5154:   
                   5155:    /* int movingaverage(); */
                   5156:    double **dnewm,**doldm;
                   5157:    double **dnewmp,**doldmp;
                   5158:    int i, j, nhstepm, hstepm, h, nstepm ;
                   5159:    int k;
                   5160:    double *xp;
                   5161:    double **gp, **gm;  /* for var eij */
                   5162:    double ***gradg, ***trgradg; /*for var eij */
                   5163:    double **gradgp, **trgradgp; /* for var p point j */
                   5164:    double *gpp, *gmp; /* for var p point j */
                   5165:    double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   5166:    double ***p3mat;
                   5167:    double age,agelim, hf;
                   5168:    /* double ***mobaverage; */
                   5169:    int theta;
                   5170:    char digit[4];
                   5171:    char digitp[25];
                   5172: 
                   5173:    char fileresprobmorprev[FILENAMELENGTH];
                   5174: 
                   5175:    if(popbased==1){
                   5176:      if(mobilav!=0)
                   5177:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   5178:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   5179:    }
                   5180:    else 
                   5181:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  5182: 
1.218     brouard  5183:    /* if (mobilav!=0) { */
                   5184:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   5185:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   5186:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   5187:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   5188:    /*   } */
                   5189:    /* } */
                   5190: 
                   5191:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   5192:    sprintf(digit,"%-d",ij);
                   5193:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   5194:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   5195:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   5196:    strcat(fileresprobmorprev,fileresu);
                   5197:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   5198:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   5199:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   5200:    }
                   5201:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   5202:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   5203:    pstamp(ficresprobmorprev);
                   5204:    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);
                   5205:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   5206:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   5207:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   5208:      for(i=1; i<=nlstate;i++)
                   5209:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   5210:    }  
                   5211:    fprintf(ficresprobmorprev,"\n");
                   5212:   
                   5213:    fprintf(ficgp,"\n# Routine varevsij");
                   5214:    fprintf(ficgp,"\nunset title \n");
                   5215:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   5216:    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");
                   5217:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   5218:    /*   } */
                   5219:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5220:    pstamp(ficresvij);
                   5221:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   5222:    if(popbased==1)
                   5223:      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);
                   5224:    else
                   5225:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   5226:    fprintf(ficresvij,"# Age");
                   5227:    for(i=1; i<=nlstate;i++)
                   5228:      for(j=1; j<=nlstate;j++)
                   5229:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   5230:    fprintf(ficresvij,"\n");
                   5231: 
                   5232:    xp=vector(1,npar);
                   5233:    dnewm=matrix(1,nlstate,1,npar);
                   5234:    doldm=matrix(1,nlstate,1,nlstate);
                   5235:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   5236:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5237: 
                   5238:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   5239:    gpp=vector(nlstate+1,nlstate+ndeath);
                   5240:    gmp=vector(nlstate+1,nlstate+ndeath);
                   5241:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  5242:   
1.218     brouard  5243:    if(estepm < stepm){
                   5244:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   5245:    }
                   5246:    else  hstepm=estepm;   
                   5247:    /* For example we decided to compute the life expectancy with the smallest unit */
                   5248:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5249:       nhstepm is the number of hstepm from age to agelim 
                   5250:       nstepm is the number of stepm from age to agelim. 
                   5251:       Look at function hpijx to understand why because of memory size limitations, 
                   5252:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   5253:       survival function given by stepm (the optimization length). Unfortunately it
                   5254:       means that if the survival funtion is printed every two years of age and if
                   5255:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5256:       results. So we changed our mind and took the option of the best precision.
                   5257:    */
                   5258:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5259:    agelim = AGESUP;
                   5260:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   5261:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   5262:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5263:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5264:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   5265:      gp=matrix(0,nhstepm,1,nlstate);
                   5266:      gm=matrix(0,nhstepm,1,nlstate);
                   5267:                
                   5268:                
                   5269:      for(theta=1; theta <=npar; theta++){
                   5270:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   5271:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5272:        }
                   5273:                        
                   5274:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
                   5275:                        
                   5276:        if (popbased==1) {
                   5277:         if(mobilav ==0){
                   5278:           for(i=1; i<=nlstate;i++)
                   5279:             prlim[i][i]=probs[(int)age][i][ij];
                   5280:         }else{ /* mobilav */ 
                   5281:           for(i=1; i<=nlstate;i++)
                   5282:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   5283:         }
                   5284:        }
                   5285:                        
                   5286:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  /* Returns p3mat[i][j][h] for h=1 to nhstepm */
                   5287:        for(j=1; j<= nlstate; j++){
                   5288:         for(h=0; h<=nhstepm; h++){
                   5289:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   5290:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   5291:         }
                   5292:        }
                   5293:        /* Next for computing probability of death (h=1 means
                   5294:          computed over hstepm matrices product = hstepm*stepm months) 
                   5295:          as a weighted average of prlim.
                   5296:        */
                   5297:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   5298:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   5299:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   5300:        }    
                   5301:        /* end probability of death */
                   5302:                        
                   5303:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   5304:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   5305:                        
                   5306:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij);
                   5307:                        
                   5308:        if (popbased==1) {
                   5309:         if(mobilav ==0){
                   5310:           for(i=1; i<=nlstate;i++)
                   5311:             prlim[i][i]=probs[(int)age][i][ij];
                   5312:         }else{ /* mobilav */ 
                   5313:           for(i=1; i<=nlstate;i++)
                   5314:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   5315:         }
                   5316:        }
                   5317:                        
                   5318:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   5319:                        
                   5320:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   5321:         for(h=0; h<=nhstepm; h++){
                   5322:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   5323:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   5324:         }
                   5325:        }
                   5326:        /* This for computing probability of death (h=1 means
                   5327:          computed over hstepm matrices product = hstepm*stepm months) 
                   5328:          as a weighted average of prlim.
                   5329:        */
                   5330:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   5331:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   5332:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   5333:        }    
                   5334:        /* end probability of death */
                   5335:                        
                   5336:        for(j=1; j<= nlstate; j++) /* vareij */
                   5337:         for(h=0; h<=nhstepm; h++){
                   5338:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   5339:         }
                   5340:                        
                   5341:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   5342:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   5343:        }
                   5344:                        
                   5345:      } /* End theta */
                   5346:                
                   5347:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   5348:                
                   5349:      for(h=0; h<=nhstepm; h++) /* veij */
                   5350:        for(j=1; j<=nlstate;j++)
                   5351:         for(theta=1; theta <=npar; theta++)
                   5352:           trgradg[h][j][theta]=gradg[h][theta][j];
                   5353:                
                   5354:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   5355:        for(theta=1; theta <=npar; theta++)
                   5356:         trgradgp[j][theta]=gradgp[theta][j];
                   5357:                
                   5358:                
                   5359:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   5360:      for(i=1;i<=nlstate;i++)
                   5361:        for(j=1;j<=nlstate;j++)
                   5362:         vareij[i][j][(int)age] =0.;
                   5363:                
                   5364:      for(h=0;h<=nhstepm;h++){
                   5365:        for(k=0;k<=nhstepm;k++){
                   5366:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   5367:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   5368:         for(i=1;i<=nlstate;i++)
                   5369:           for(j=1;j<=nlstate;j++)
                   5370:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   5371:        }
                   5372:      }
                   5373:                
                   5374:      /* pptj */
                   5375:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   5376:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   5377:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   5378:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   5379:         varppt[j][i]=doldmp[j][i];
                   5380:      /* end ppptj */
                   5381:      /*  x centered again */
                   5382:                
                   5383:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij);
                   5384:                
                   5385:      if (popbased==1) {
                   5386:        if(mobilav ==0){
                   5387:         for(i=1; i<=nlstate;i++)
                   5388:           prlim[i][i]=probs[(int)age][i][ij];
                   5389:        }else{ /* mobilav */ 
                   5390:         for(i=1; i<=nlstate;i++)
                   5391:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   5392:        }
                   5393:      }
                   5394:                
                   5395:      /* This for computing probability of death (h=1 means
                   5396:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   5397:        as a weighted average of prlim.
                   5398:      */
                   5399:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
                   5400:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   5401:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   5402:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   5403:      }    
                   5404:      /* end probability of death */
                   5405:                
                   5406:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   5407:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   5408:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   5409:        for(i=1; i<=nlstate;i++){
                   5410:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   5411:        }
                   5412:      } 
                   5413:      fprintf(ficresprobmorprev,"\n");
                   5414:                
                   5415:      fprintf(ficresvij,"%.0f ",age );
                   5416:      for(i=1; i<=nlstate;i++)
                   5417:        for(j=1; j<=nlstate;j++){
                   5418:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   5419:        }
                   5420:      fprintf(ficresvij,"\n");
                   5421:      free_matrix(gp,0,nhstepm,1,nlstate);
                   5422:      free_matrix(gm,0,nhstepm,1,nlstate);
                   5423:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   5424:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   5425:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5426:    } /* End age */
                   5427:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   5428:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   5429:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   5430:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   5431:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   5432:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   5433:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   5434:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   5435:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   5436:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   5437:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   5438:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   5439:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   5440:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   5441:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   5442:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   5443:    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);
                   5444:    /*  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  5445:     */
1.218     brouard  5446:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   5447:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  5448: 
1.218     brouard  5449:    free_vector(xp,1,npar);
                   5450:    free_matrix(doldm,1,nlstate,1,nlstate);
                   5451:    free_matrix(dnewm,1,nlstate,1,npar);
                   5452:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5453:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   5454:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5455:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   5456:    fclose(ficresprobmorprev);
                   5457:    fflush(ficgp);
                   5458:    fflush(fichtm); 
                   5459:  }  /* end varevsij */
1.126     brouard  5460: 
                   5461: /************ Variance of prevlim ******************/
1.209     brouard  5462:  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[])
1.126     brouard  5463: {
1.205     brouard  5464:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  5465:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  5466: 
1.126     brouard  5467:   double **dnewm,**doldm;
                   5468:   int i, j, nhstepm, hstepm;
                   5469:   double *xp;
                   5470:   double *gp, *gm;
                   5471:   double **gradg, **trgradg;
1.208     brouard  5472:   double **mgm, **mgp;
1.126     brouard  5473:   double age,agelim;
                   5474:   int theta;
                   5475:   
                   5476:   pstamp(ficresvpl);
                   5477:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
                   5478:   fprintf(ficresvpl,"# Age");
                   5479:   for(i=1; i<=nlstate;i++)
                   5480:       fprintf(ficresvpl," %1d-%1d",i,i);
                   5481:   fprintf(ficresvpl,"\n");
                   5482: 
                   5483:   xp=vector(1,npar);
                   5484:   dnewm=matrix(1,nlstate,1,npar);
                   5485:   doldm=matrix(1,nlstate,1,nlstate);
                   5486:   
                   5487:   hstepm=1*YEARM; /* Every year of age */
                   5488:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   5489:   agelim = AGESUP;
                   5490:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   5491:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   5492:     if (stepm >= YEARM) hstepm=1;
                   5493:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   5494:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  5495:     mgp=matrix(1,npar,1,nlstate);
                   5496:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  5497:     gp=vector(1,nlstate);
                   5498:     gm=vector(1,nlstate);
                   5499: 
                   5500:     for(theta=1; theta <=npar; theta++){
                   5501:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   5502:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5503:       }
1.209     brouard  5504:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
                   5505:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
                   5506:       else
                   5507:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
1.208     brouard  5508:       for(i=1;i<=nlstate;i++){
1.126     brouard  5509:        gp[i] = prlim[i][i];
1.208     brouard  5510:        mgp[theta][i] = prlim[i][i];
                   5511:       }
1.126     brouard  5512:       for(i=1; i<=npar; i++) /* Computes gradient */
                   5513:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.209     brouard  5514:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
                   5515:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
                   5516:       else
                   5517:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
1.208     brouard  5518:       for(i=1;i<=nlstate;i++){
1.126     brouard  5519:        gm[i] = prlim[i][i];
1.208     brouard  5520:        mgm[theta][i] = prlim[i][i];
                   5521:       }
1.126     brouard  5522:       for(i=1;i<=nlstate;i++)
                   5523:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  5524:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  5525:     } /* End theta */
                   5526: 
                   5527:     trgradg =matrix(1,nlstate,1,npar);
                   5528: 
                   5529:     for(j=1; j<=nlstate;j++)
                   5530:       for(theta=1; theta <=npar; theta++)
                   5531:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  5532:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   5533:     /*   printf("\nmgm mgp %d ",(int)age); */
                   5534:     /*   for(j=1; j<=nlstate;j++){ */
                   5535:     /*         printf(" %d ",j); */
                   5536:     /*         for(theta=1; theta <=npar; theta++) */
                   5537:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   5538:     /*         printf("\n "); */
                   5539:     /*   } */
                   5540:     /* } */
                   5541:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   5542:     /*   printf("\n gradg %d ",(int)age); */
                   5543:     /*   for(j=1; j<=nlstate;j++){ */
                   5544:     /*         printf("%d ",j); */
                   5545:     /*         for(theta=1; theta <=npar; theta++) */
                   5546:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   5547:     /*         printf("\n "); */
                   5548:     /*   } */
                   5549:     /* } */
1.126     brouard  5550: 
                   5551:     for(i=1;i<=nlstate;i++)
                   5552:       varpl[i][(int)age] =0.;
1.209     brouard  5553:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.205     brouard  5554:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   5555:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   5556:     }else{
1.126     brouard  5557:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   5558:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  5559:     }
1.126     brouard  5560:     for(i=1;i<=nlstate;i++)
                   5561:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   5562: 
                   5563:     fprintf(ficresvpl,"%.0f ",age );
                   5564:     for(i=1; i<=nlstate;i++)
                   5565:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   5566:     fprintf(ficresvpl,"\n");
                   5567:     free_vector(gp,1,nlstate);
                   5568:     free_vector(gm,1,nlstate);
1.208     brouard  5569:     free_matrix(mgm,1,npar,1,nlstate);
                   5570:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  5571:     free_matrix(gradg,1,npar,1,nlstate);
                   5572:     free_matrix(trgradg,1,nlstate,1,npar);
                   5573:   } /* End age */
                   5574: 
                   5575:   free_vector(xp,1,npar);
                   5576:   free_matrix(doldm,1,nlstate,1,npar);
                   5577:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   5578: 
                   5579: }
                   5580: 
                   5581: /************ Variance of one-step probabilities  ******************/
                   5582: 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  5583:  {
                   5584:    int i, j=0,  k1, l1, tj;
                   5585:    int k2, l2, j1,  z1;
                   5586:    int k=0, l;
                   5587:    int first=1, first1, first2;
                   5588:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   5589:    double **dnewm,**doldm;
                   5590:    double *xp;
                   5591:    double *gp, *gm;
                   5592:    double **gradg, **trgradg;
                   5593:    double **mu;
                   5594:    double age, cov[NCOVMAX+1];
                   5595:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   5596:    int theta;
                   5597:    char fileresprob[FILENAMELENGTH];
                   5598:    char fileresprobcov[FILENAMELENGTH];
                   5599:    char fileresprobcor[FILENAMELENGTH];
                   5600:    double ***varpij;
                   5601: 
                   5602:    strcpy(fileresprob,"PROB_"); 
                   5603:    strcat(fileresprob,fileres);
                   5604:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   5605:      printf("Problem with resultfile: %s\n", fileresprob);
                   5606:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   5607:    }
                   5608:    strcpy(fileresprobcov,"PROBCOV_"); 
                   5609:    strcat(fileresprobcov,fileresu);
                   5610:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   5611:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   5612:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   5613:    }
                   5614:    strcpy(fileresprobcor,"PROBCOR_"); 
                   5615:    strcat(fileresprobcor,fileresu);
                   5616:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   5617:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   5618:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   5619:    }
                   5620:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   5621:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   5622:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   5623:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   5624:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   5625:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   5626:    pstamp(ficresprob);
                   5627:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   5628:    fprintf(ficresprob,"# Age");
                   5629:    pstamp(ficresprobcov);
                   5630:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   5631:    fprintf(ficresprobcov,"# Age");
                   5632:    pstamp(ficresprobcor);
                   5633:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   5634:    fprintf(ficresprobcor,"# Age");
1.126     brouard  5635: 
                   5636: 
1.222     brouard  5637:    for(i=1; i<=nlstate;i++)
                   5638:      for(j=1; j<=(nlstate+ndeath);j++){
                   5639:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   5640:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   5641:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   5642:      }  
                   5643:    /* fprintf(ficresprob,"\n");
                   5644:       fprintf(ficresprobcov,"\n");
                   5645:       fprintf(ficresprobcor,"\n");
                   5646:    */
                   5647:    xp=vector(1,npar);
                   5648:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   5649:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   5650:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   5651:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   5652:    first=1;
                   5653:    fprintf(ficgp,"\n# Routine varprob");
                   5654:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   5655:    fprintf(fichtm,"\n");
                   5656: 
                   5657:    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);
                   5658:    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);
                   5659:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  5660: and drawn. It helps understanding how is the covariance between two incidences.\
                   5661:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  5662:    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  5663: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   5664: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   5665: standard deviations wide on each axis. <br>\
                   5666:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   5667:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   5668: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   5669: 
1.222     brouard  5670:    cov[1]=1;
                   5671:    /* tj=cptcoveff; */
1.225     brouard  5672:    tj = (int) pow(2,cptcoveff);
1.222     brouard  5673:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   5674:    j1=0;
1.224     brouard  5675:    for(j1=1; j1<=tj;j1++){  /* For each valid combination of covariates or only once*/
1.222     brouard  5676:      if  (cptcovn>0) {
                   5677:        fprintf(ficresprob, "\n#********** Variable "); 
1.225     brouard  5678:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5679:        fprintf(ficresprob, "**********\n#\n");
                   5680:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.225     brouard  5681:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5682:        fprintf(ficresprobcov, "**********\n#\n");
1.220     brouard  5683:                        
1.222     brouard  5684:        fprintf(ficgp, "\n#********** Variable "); 
1.225     brouard  5685:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5686:        fprintf(ficgp, "**********\n#\n");
1.220     brouard  5687:                        
                   5688:                        
1.222     brouard  5689:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.225     brouard  5690:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5691:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  5692:                        
1.222     brouard  5693:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.225     brouard  5694:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5695:        fprintf(ficresprobcor, "**********\n#");    
                   5696:        if(invalidvarcomb[j1]){
                   5697:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   5698:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   5699:         continue;
                   5700:        }
                   5701:      }
                   5702:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   5703:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   5704:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   5705:      gm=vector(1,(nlstate)*(nlstate+ndeath));
                   5706:      for (age=bage; age<=fage; age ++){ 
                   5707:        cov[2]=age;
                   5708:        if(nagesqr==1)
                   5709:         cov[3]= age*age;
                   5710:        for (k=1; k<=cptcovn;k++) {
                   5711:         cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
                   5712:         /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
                   5713:                                                                    * 1  1 1 1 1
                   5714:                                                                    * 2  2 1 1 1
                   5715:                                                                    * 3  1 2 1 1
                   5716:                                                                    */
                   5717:         /* nbcode[1][1]=0 nbcode[1][2]=1;*/
                   5718:        }
                   5719:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   5720:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   5721:        for (k=1; k<=cptcovprod;k++)
                   5722:         cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.220     brouard  5723:                        
                   5724:                        
1.222     brouard  5725:        for(theta=1; theta <=npar; theta++){
                   5726:         for(i=1; i<=npar; i++)
                   5727:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  5728:                                
1.222     brouard  5729:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  5730:                                
1.222     brouard  5731:         k=0;
                   5732:         for(i=1; i<= (nlstate); i++){
                   5733:           for(j=1; j<=(nlstate+ndeath);j++){
                   5734:             k=k+1;
                   5735:             gp[k]=pmmij[i][j];
                   5736:           }
                   5737:         }
1.220     brouard  5738:                                
1.222     brouard  5739:         for(i=1; i<=npar; i++)
                   5740:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  5741:                                
1.222     brouard  5742:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   5743:         k=0;
                   5744:         for(i=1; i<=(nlstate); i++){
                   5745:           for(j=1; j<=(nlstate+ndeath);j++){
                   5746:             k=k+1;
                   5747:             gm[k]=pmmij[i][j];
                   5748:           }
                   5749:         }
1.220     brouard  5750:                                
1.222     brouard  5751:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   5752:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   5753:        }
1.126     brouard  5754: 
1.222     brouard  5755:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   5756:         for(theta=1; theta <=npar; theta++)
                   5757:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  5758:                        
1.222     brouard  5759:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   5760:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  5761:                        
1.222     brouard  5762:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  5763:                        
1.222     brouard  5764:        k=0;
                   5765:        for(i=1; i<=(nlstate); i++){
                   5766:         for(j=1; j<=(nlstate+ndeath);j++){
                   5767:           k=k+1;
                   5768:           mu[k][(int) age]=pmmij[i][j];
                   5769:         }
                   5770:        }
                   5771:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   5772:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   5773:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  5774:                        
1.222     brouard  5775:        /*printf("\n%d ",(int)age);
                   5776:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   5777:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   5778:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   5779:         }*/
1.220     brouard  5780:                        
1.222     brouard  5781:        fprintf(ficresprob,"\n%d ",(int)age);
                   5782:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   5783:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  5784:                        
1.222     brouard  5785:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   5786:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   5787:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   5788:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   5789:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   5790:        }
                   5791:        i=0;
                   5792:        for (k=1; k<=(nlstate);k++){
                   5793:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   5794:           i++;
                   5795:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   5796:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   5797:           for (j=1; j<=i;j++){
                   5798:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   5799:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   5800:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   5801:           }
                   5802:         }
                   5803:        }/* end of loop for state */
                   5804:      } /* end of loop for age */
                   5805:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   5806:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   5807:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   5808:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   5809:     
                   5810:      /* Confidence intervalle of pij  */
                   5811:      /*
                   5812:        fprintf(ficgp,"\nunset parametric;unset label");
                   5813:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   5814:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   5815:        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);
                   5816:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   5817:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   5818:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   5819:      */
                   5820:                
                   5821:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   5822:      first1=1;first2=2;
                   5823:      for (k2=1; k2<=(nlstate);k2++){
                   5824:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   5825:         if(l2==k2) continue;
                   5826:         j=(k2-1)*(nlstate+ndeath)+l2;
                   5827:         for (k1=1; k1<=(nlstate);k1++){
                   5828:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   5829:             if(l1==k1) continue;
                   5830:             i=(k1-1)*(nlstate+ndeath)+l1;
                   5831:             if(i<=j) continue;
                   5832:             for (age=bage; age<=fage; age ++){ 
                   5833:               if ((int)age %5==0){
                   5834:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   5835:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   5836:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   5837:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   5838:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   5839:                 c12=cv12/sqrt(v1*v2);
                   5840:                 /* Computing eigen value of matrix of covariance */
                   5841:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5842:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5843:                 if ((lc2 <0) || (lc1 <0) ){
                   5844:                   if(first2==1){
                   5845:                     first1=0;
                   5846:                     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);
                   5847:                   }
                   5848:                   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);
                   5849:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   5850:                   /* lc2=fabs(lc2); */
                   5851:                 }
1.220     brouard  5852:                                                                
1.222     brouard  5853:                 /* Eigen vectors */
                   5854:                 v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   5855:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   5856:                 v21=(lc1-v1)/cv12*v11;
                   5857:                 v12=-v21;
                   5858:                 v22=v11;
                   5859:                 tnalp=v21/v11;
                   5860:                 if(first1==1){
                   5861:                   first1=0;
                   5862:                   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);
                   5863:                 }
                   5864:                 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);
                   5865:                 /*printf(fignu*/
                   5866:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   5867:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   5868:                 if(first==1){
                   5869:                   first=0;
                   5870:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   5871:                   fprintf(ficgp,"\nset parametric;unset label");
                   5872:                   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);
                   5873:                   fprintf(ficgp,"\nset ter svg size 640, 480");
                   5874:                   fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  5875:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  5876: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  5877:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   5878:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   5879:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   5880:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   5881:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   5882:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   5883:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   5884:                   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",      \
                   5885:                           mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),                                                                         \
                   5886:                           mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   5887:                 }else{
                   5888:                   first=0;
                   5889:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   5890:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   5891:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   5892:                   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", \
                   5893:                           mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),                                 \
                   5894:                           mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   5895:                 }/* if first */
                   5896:               } /* age mod 5 */
                   5897:             } /* end loop age */
                   5898:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   5899:             first=1;
                   5900:           } /*l12 */
                   5901:         } /* k12 */
                   5902:        } /*l1 */
                   5903:      }/* k1 */
                   5904:    }  /* loop on combination of covariates j1 */
                   5905:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   5906:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   5907:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   5908:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   5909:    free_vector(xp,1,npar);
                   5910:    fclose(ficresprob);
                   5911:    fclose(ficresprobcov);
                   5912:    fclose(ficresprobcor);
                   5913:    fflush(ficgp);
                   5914:    fflush(fichtmcov);
                   5915:  }
1.126     brouard  5916: 
                   5917: 
                   5918: /******************* Printing html file ***********/
1.201     brouard  5919: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  5920:                  int lastpass, int stepm, int weightopt, char model[],\
                   5921:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.217     brouard  5922:                  int popforecast, int prevfcast, int backcast, int estepm , \
1.213     brouard  5923:                  double jprev1, double mprev1,double anprev1, double dateprev1, \
                   5924:                  double jprev2, double mprev2,double anprev2, double dateprev2){
1.126     brouard  5925:   int jj1, k1, i1, cpt;
                   5926: 
                   5927:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   5928:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   5929: </ul>");
1.214     brouard  5930:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   5931:    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",
                   5932:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
                   5933:    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  5934:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   5935:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  5936:    fprintf(fichtm,"\
                   5937:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  5938:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  5939:    fprintf(fichtm,"\
1.217     brouard  5940:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   5941:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   5942:    fprintf(fichtm,"\
1.126     brouard  5943:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  5944:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  5945:    fprintf(fichtm,"\
1.217     brouard  5946:  - Period (stable) back prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
                   5947:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   5948:    fprintf(fichtm,"\
1.211     brouard  5949:  - (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  5950:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  5951:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  5952:    if(prevfcast==1){
                   5953:      fprintf(fichtm,"\
                   5954:  - Prevalence projections by age and states:                           \
1.201     brouard  5955:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  5956:    }
1.126     brouard  5957: 
1.222     brouard  5958:    fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
1.126     brouard  5959: 
1.225     brouard  5960:    m=pow(2,cptcoveff);
1.222     brouard  5961:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  5962: 
1.222     brouard  5963:    jj1=0;
                   5964:    for(k1=1; k1<=m;k1++){
1.220     brouard  5965: 
1.222     brouard  5966:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   5967:      jj1++;
                   5968:      if (cptcovn > 0) {
                   5969:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  5970:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.222     brouard  5971:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
                   5972:         printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout);
                   5973:        }
1.230     brouard  5974:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.222     brouard  5975:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   5976:        if(invalidvarcomb[k1]){
                   5977:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   5978:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   5979:         continue;
                   5980:        }
                   5981:      }
                   5982:      /* aij, bij */
                   5983:      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.svg\">%s_%d-1.svg</a><br> \
1.211     brouard  5984: <img src=\"%s_%d-1.svg\">",model,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
1.222     brouard  5985:      /* Pij */
                   5986:      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.svg\">%s_%d-2.svg</a><br> \
1.201     brouard  5987: <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);     
1.222     brouard  5988:      /* Quasi-incidences */
                   5989:      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  5990:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  5991:  incidence (rates) are the limit when h tends to zero of the ratio of the probability  <sub>h</sub>P<sub>ij</sub> \
                   5992: divided by h: <sub>h</sub>P<sub>ij</sub>/h : <a href=\"%s_%d-3.svg\">%s_%d-3.svg</a><br> \
1.201     brouard  5993: <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1); 
1.222     brouard  5994:      /* Survival functions (period) in state j */
                   5995:      for(cpt=1; cpt<=nlstate;cpt++){
                   5996:        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.svg\">%s%d_%d.svg</a><br> \
1.201     brouard  5997: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1);
1.222     brouard  5998:      }
                   5999:      /* State specific survival functions (period) */
                   6000:      for(cpt=1; cpt<=nlstate;cpt++){
                   6001:        fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
1.220     brouard  6002:  Or probability to survive in various states (1 to %d) being in state %d at different ages.    \
1.201     brouard  6003:  <a href=\"%s%d_%d.svg\">%s%d_%d.svg</a><br> <img src=\"%s_%d-%d.svg\">", cpt, nlstate, cpt, subdirf2(optionfilefiname,"LIJT_"),cpt,jj1,subdirf2(optionfilefiname,"LIJT_"),cpt,jj1,subdirf2(optionfilefiname,"LIJT_"),cpt,jj1);
1.222     brouard  6004:      }
                   6005:      /* Period (stable) prevalence in each health state */
                   6006:      for(cpt=1; cpt<=nlstate;cpt++){
                   6007:        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.svg\">%s_%d-%d.svg</a><br> \
1.201     brouard  6008: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1);
1.222     brouard  6009:      }
                   6010:      if(backcast==1){
                   6011:        /* Period (stable) back prevalence in each health state */
                   6012:        for(cpt=1; cpt<=nlstate;cpt++){
                   6013:         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.svg\">%s_%d-%d.svg</a><br> \
1.217     brouard  6014: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"PB_"),cpt,jj1,subdirf2(optionfilefiname,"PB_"),cpt,jj1,subdirf2(optionfilefiname,"PB_"),cpt,jj1);
1.222     brouard  6015:        }
1.217     brouard  6016:      }
1.222     brouard  6017:      if(prevfcast==1){
                   6018:        /* Projection of prevalence up to period (stable) prevalence in each health state */
                   6019:        for(cpt=1; cpt<=nlstate;cpt++){
                   6020:         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.svg\">%s%d_%d.svg</a><br> \
1.213     brouard  6021: <img src=\"%s_%d-%d.svg\">", dateprev1, dateprev2, cpt, cpt, nlstate, subdirf2(optionfilefiname,"PROJ_"),cpt,jj1,subdirf2(optionfilefiname,"PROJ_"),cpt,jj1,subdirf2(optionfilefiname,"PROJ_"),cpt,jj1);
1.222     brouard  6022:        }
                   6023:      }
1.220     brouard  6024:         
1.222     brouard  6025:      for(cpt=1; cpt<=nlstate;cpt++) {
                   6026:        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.svg\">%s_%d%d.svg</a> <br> \
1.201     brouard  6027: <img src=\"%s_%d%d.svg\">",cpt,nlstate,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1);
1.222     brouard  6028:      }
                   6029:      /* } /\* end i1 *\/ */
                   6030:    }/* End k1 */
                   6031:    fprintf(fichtm,"</ul>");
1.126     brouard  6032: 
1.222     brouard  6033:    fprintf(fichtm,"\
1.126     brouard  6034: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  6035:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  6036:  - 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  6037: But because parameters are usually highly correlated (a higher incidence of disability \
                   6038: and a higher incidence of recovery can give very close observed transition) it might \
                   6039: be very useful to look not only at linear confidence intervals estimated from the \
                   6040: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   6041: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   6042: covariance matrix of the one-step probabilities. \
                   6043: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  6044: 
1.222     brouard  6045:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   6046:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   6047:    fprintf(fichtm,"\
1.126     brouard  6048:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  6049:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  6050: 
1.222     brouard  6051:    fprintf(fichtm,"\
1.126     brouard  6052:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  6053:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   6054:    fprintf(fichtm,"\
1.126     brouard  6055:  - 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): \
                   6056:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  6057:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  6058:    fprintf(fichtm,"\
1.126     brouard  6059:  - (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): \
                   6060:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  6061:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  6062:    fprintf(fichtm,"\
1.128     brouard  6063:  - 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  6064:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   6065:    fprintf(fichtm,"\
1.128     brouard  6066:  - 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  6067:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   6068:    fprintf(fichtm,"\
1.126     brouard  6069:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  6070:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  6071: 
                   6072: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   6073: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   6074: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   6075: /*     <br>",fileres,fileres,fileres,fileres); */
                   6076: /*  else  */
                   6077: /*    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  6078:    fflush(fichtm);
                   6079:    fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
1.126     brouard  6080: 
1.225     brouard  6081:    m=pow(2,cptcoveff);
1.222     brouard  6082:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  6083: 
1.222     brouard  6084:    jj1=0;
                   6085:    for(k1=1; k1<=m;k1++){
                   6086:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   6087:      jj1++;
1.126     brouard  6088:      if (cptcovn > 0) {
                   6089:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  6090:        for (cpt=1; cpt<=cptcoveff;cpt++)  /**< cptcoveff number of variables */
1.222     brouard  6091:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
1.126     brouard  6092:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  6093: 
1.222     brouard  6094:        if(invalidvarcomb[k1]){
                   6095:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   6096:         continue;
                   6097:        }
1.126     brouard  6098:      }
                   6099:      for(cpt=1; cpt<=nlstate;cpt++) {
1.218     brouard  6100:        fprintf(fichtm,"\n<br>- Observed (cross-sectional) and period (incidence based) \
                   6101: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d-%d.svg\"> %s_%d-%d.svg</a>\n <br>\
1.205     brouard  6102: <img src=\"%s_%d-%d.svg\">",cpt,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1);  
1.126     brouard  6103:      }
                   6104:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  6105: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   6106: true period expectancies (those weighted with period prevalences are also\
                   6107:  drawn in addition to the population based expectancies computed using\
1.218     brouard  6108:  observed and cahotic prevalences:  <a href=\"%s_%d.svg\">%s_%d.svg</a>\n<br>\
1.205     brouard  6109: <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);
1.222     brouard  6110:      /* } /\* end i1 *\/ */
                   6111:    }/* End k1 */
                   6112:    fprintf(fichtm,"</ul>");
                   6113:    fflush(fichtm);
1.126     brouard  6114: }
                   6115: 
                   6116: /******************* Gnuplot file **************/
1.223     brouard  6117: void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , int prevfcast, int backcast, char pathc[], double p[]){
1.126     brouard  6118: 
                   6119:   char dirfileres[132],optfileres[132];
1.223     brouard  6120:   char gplotcondition[132];
1.164     brouard  6121:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.211     brouard  6122:   int lv=0, vlv=0, kl=0;
1.130     brouard  6123:   int ng=0;
1.201     brouard  6124:   int vpopbased;
1.223     brouard  6125:   int ioffset; /* variable offset for columns */
1.219     brouard  6126: 
1.126     brouard  6127: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   6128: /*     printf("Problem with file %s",optionfilegnuplot); */
                   6129: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   6130: /*   } */
                   6131: 
                   6132:   /*#ifdef windows */
                   6133:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  6134:   /*#endif */
1.225     brouard  6135:   m=pow(2,cptcoveff);
1.126     brouard  6136: 
1.202     brouard  6137:   /* Contribution to likelihood */
                   6138:   /* Plot the probability implied in the likelihood */
1.223     brouard  6139:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   6140:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   6141:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   6142:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  6143: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  6144:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   6145: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  6146:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   6147:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   6148:   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));
                   6149:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   6150:   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));
                   6151:   for (i=1; i<= nlstate ; i ++) {
                   6152:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   6153:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   6154:     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);
                   6155:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   6156:       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);
                   6157:     }
                   6158:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   6159:   }
                   6160:   /* 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 */               
                   6161:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   6162:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   6163:   fprintf(ficgp,"\nset out;unset log\n");
                   6164:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  6165: 
1.126     brouard  6166:   strcpy(dirfileres,optionfilefiname);
                   6167:   strcpy(optfileres,"vpl");
1.223     brouard  6168:   /* 1eme*/
1.211     brouard  6169:   for (cpt=1; cpt<= nlstate ; cpt ++) { /* For each live state */
1.230     brouard  6170:     for (k1=1; k1<= m && selected(k1) ; k1 ++) { /* For each valid combination of covariate */
1.211     brouard  6171:       /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
                   6172:       fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files ");
1.225     brouard  6173:       for (k=1; k<=cptcoveff; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   6174:        lv= decodtabm(k1,k,cptcoveff); /* Should be the value of the covariate corresponding to k1 combination */
1.223     brouard  6175:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6176:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6177:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6178:        vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
                   6179:        /* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
                   6180:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  6181:       }
                   6182:       fprintf(ficgp,"\n#\n");
1.223     brouard  6183:       if(invalidvarcomb[k1]){
                   6184:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6185:        continue;
                   6186:       }
1.211     brouard  6187: 
1.223     brouard  6188:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);
                   6189:       fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);
                   6190:       fprintf(ficgp,"set xlabel \"Age\" \n\
1.219     brouard  6191: set ylabel \"Probability\" \n  \
                   6192: set ter svg size 640, 480\n    \
1.201     brouard  6193: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);
1.219     brouard  6194:                        
1.223     brouard  6195:       for (i=1; i<= nlstate ; i ++) {
                   6196:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   6197:        else        fprintf(ficgp," %%*lf (%%*lf)");
                   6198:       }
                   6199:       fprintf(ficgp,"\" t\"Period (stable) prevalence\" w l lt 0,\"%s\" every :::%d::%d u 1:($2+1.96*$3) \"%%lf",subdirf2(fileresu,"VPL_"),k1-1,k1-1);
                   6200:       for (i=1; i<= nlstate ; i ++) {
                   6201:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   6202:        else fprintf(ficgp," %%*lf (%%*lf)");
                   6203:       } 
                   6204:       fprintf(ficgp,"\" t\"95%% CI\" w l lt 1,\"%s\" every :::%d::%d u 1:($2-1.96*$3) \"%%lf",subdirf2(fileresu,"VPL_"),k1-1,k1-1); 
                   6205:       for (i=1; i<= nlstate ; i ++) {
                   6206:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   6207:        else fprintf(ficgp," %%*lf (%%*lf)");
                   6208:       }  
                   6209:       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));
                   6210:       if(backcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
                   6211:        /* 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); */
                   6212:        fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1 */
1.225     brouard  6213:        if(cptcoveff ==0){
1.223     brouard  6214:          fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line ",  2+(cpt-1),  cpt );
                   6215:        }else{
                   6216:          kl=0;
1.225     brouard  6217:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   6218:            lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
1.223     brouard  6219:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6220:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6221:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6222:            vlv= nbcode[Tvaraff[k]][lv];
                   6223:            kl++;
                   6224:            /* 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 *\/ */
                   6225:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   6226:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   6227:            /* ''  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*/
1.225     brouard  6228:            if(k==cptcoveff){
1.227     brouard  6229:              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], \
                   6230:                      4+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.223     brouard  6231:            }else{
                   6232:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   6233:              kl++;
                   6234:            }
                   6235:          } /* end covariate */
                   6236:        } /* end if no covariate */
                   6237:       } /* end if backcast */
                   6238:       fprintf(ficgp,"\nset out \n");
1.201     brouard  6239:     } /* k1 */
                   6240:   } /* cpt */
1.126     brouard  6241:   /*2 eme*/
                   6242:   for (k1=1; k1<= m ; k1 ++) { 
1.220     brouard  6243: 
1.223     brouard  6244:     fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.225     brouard  6245:     for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6246:       lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
1.223     brouard  6247:       /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6248:       /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6249:       /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6250:       vlv= nbcode[Tvaraff[k]][lv];
                   6251:       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6252:     }
                   6253:     fprintf(ficgp,"\n#\n");
                   6254:     if(invalidvarcomb[k1]){
                   6255:       fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6256:       continue;
                   6257:     }
1.219     brouard  6258:                        
1.223     brouard  6259:     fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);
                   6260:     for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
                   6261:       if(vpopbased==0)
                   6262:        fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
                   6263:       else
                   6264:        fprintf(ficgp,"\nreplot ");
                   6265:       for (i=1; i<= nlstate+1 ; i ++) {
                   6266:        k=2*i;
                   6267:        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);
                   6268:        for (j=1; j<= nlstate+1 ; j ++) {
                   6269:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   6270:          else fprintf(ficgp," %%*lf (%%*lf)");
                   6271:        }   
                   6272:        if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   6273:        else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
                   6274:        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);
                   6275:        for (j=1; j<= nlstate+1 ; j ++) {
                   6276:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   6277:          else fprintf(ficgp," %%*lf (%%*lf)");
                   6278:        }   
                   6279:        fprintf(ficgp,"\" t\"\" w l lt 0,");
                   6280:        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);
                   6281:        for (j=1; j<= nlstate+1 ; j ++) {
                   6282:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   6283:          else fprintf(ficgp," %%*lf (%%*lf)");
                   6284:        }   
                   6285:        if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   6286:        else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   6287:       } /* state */
                   6288:     } /* vpopbased */
                   6289:     fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
1.201     brouard  6290:   } /* k1 */
1.219     brouard  6291:        
                   6292:        
1.126     brouard  6293:   /*3eme*/
                   6294:   for (k1=1; k1<= m ; k1 ++) { 
1.220     brouard  6295: 
1.126     brouard  6296:     for (cpt=1; cpt<= nlstate ; cpt ++) {
1.211     brouard  6297:       fprintf(ficgp,"\n# 3d: Life expectancy with EXP_ files:  cov=%d state=%d",k1, cpt);
1.225     brouard  6298:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6299:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
1.223     brouard  6300:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6301:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6302:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6303:        vlv= nbcode[Tvaraff[k]][lv];
                   6304:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  6305:       }
                   6306:       fprintf(ficgp,"\n#\n");
1.223     brouard  6307:       if(invalidvarcomb[k1]){
                   6308:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6309:        continue;
                   6310:       }
1.219     brouard  6311:                        
1.126     brouard  6312:       /*       k=2+nlstate*(2*cpt-2); */
                   6313:       k=2+(nlstate+1)*(cpt-1);
1.201     brouard  6314:       fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);
1.199     brouard  6315:       fprintf(ficgp,"set ter svg size 640, 480\n\
1.201     brouard  6316: 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.126     brouard  6317:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
1.223     brouard  6318:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   6319:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   6320:        fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   6321:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   6322:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  6323:                                
1.126     brouard  6324:       */
                   6325:       for (i=1; i< nlstate ; i ++) {
1.223     brouard  6326:        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);
                   6327:        /*      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  6328:                                
1.126     brouard  6329:       } 
1.201     brouard  6330:       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+nlstate,cpt);
1.126     brouard  6331:     }
                   6332:   }
                   6333:   
1.223     brouard  6334:   /* 4eme */
1.201     brouard  6335:   /* Survival functions (period) from state i in state j by initial state i */
                   6336:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
1.220     brouard  6337: 
1.201     brouard  6338:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.211     brouard  6339:       fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
1.225     brouard  6340:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6341:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
1.223     brouard  6342:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6343:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6344:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6345:        vlv= nbcode[Tvaraff[k]][lv];
                   6346:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  6347:       }
                   6348:       fprintf(ficgp,"\n#\n");
1.223     brouard  6349:       if(invalidvarcomb[k1]){
                   6350:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6351:        continue;
                   6352:       }
1.220     brouard  6353:                        
1.201     brouard  6354:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);
                   6355:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
1.220     brouard  6356: set ter svg size 640, 480\n                                                                                                                                                                                    \
                   6357: unset log y\n                                                                                                                                                                                                                                          \
1.201     brouard  6358: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  6359:       k=3;
1.201     brouard  6360:       for (i=1; i<= nlstate ; i ++){
1.223     brouard  6361:        if(i==1){
                   6362:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   6363:        }else{
                   6364:          fprintf(ficgp,", '' ");
                   6365:        }
                   6366:        l=(nlstate+ndeath)*(i-1)+1;
                   6367:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   6368:        for (j=2; j<= nlstate+ndeath ; j ++)
                   6369:          fprintf(ficgp,"+$%d",k+l+j-1);
                   6370:        fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
1.201     brouard  6371:       } /* nlstate */
                   6372:       fprintf(ficgp,"\nset out\n");
                   6373:     } /* end cpt state*/ 
                   6374:   } /* end covariate */  
1.220     brouard  6375:        
                   6376: /* 5eme */
1.201     brouard  6377:   /* Survival functions (period) from state i in state j by final state j */
1.202     brouard  6378:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
1.201     brouard  6379:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.223     brouard  6380:                        
1.201     brouard  6381:       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);
1.225     brouard  6382:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.227     brouard  6383:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6384:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6385:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6386:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6387:        vlv= nbcode[Tvaraff[k]][lv];
                   6388:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  6389:       }
                   6390:       fprintf(ficgp,"\n#\n");
1.223     brouard  6391:       if(invalidvarcomb[k1]){
1.227     brouard  6392:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6393:        continue;
1.223     brouard  6394:       }
1.227     brouard  6395:       
1.201     brouard  6396:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);
                   6397:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
1.227     brouard  6398: set ter svg size 640, 480\n                                            \
                   6399: unset log y\n                                                          \
1.201     brouard  6400: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  6401:       k=3;
1.201     brouard  6402:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
1.227     brouard  6403:        if(j==1)
                   6404:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   6405:        else
                   6406:          fprintf(ficgp,", '' ");
                   6407:        l=(nlstate+ndeath)*(cpt-1) +j;
                   6408:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   6409:        /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   6410:        /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   6411:        fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
1.201     brouard  6412:       } /* nlstate */
                   6413:       fprintf(ficgp,", '' ");
                   6414:       fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   6415:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
1.227     brouard  6416:        l=(nlstate+ndeath)*(cpt-1) +j;
                   6417:        if(j < nlstate)
                   6418:          fprintf(ficgp,"$%d +",k+l);
                   6419:        else
                   6420:          fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
1.201     brouard  6421:       }
                   6422:       fprintf(ficgp,"\nset out\n");
                   6423:     } /* end cpt state*/ 
                   6424:   } /* end covariate */  
1.227     brouard  6425:   
1.220     brouard  6426: /* 6eme */
1.202     brouard  6427:   /* CV preval stable (period) for each covariate */
1.211     brouard  6428:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
1.153     brouard  6429:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.227     brouard  6430:       
1.211     brouard  6431:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.225     brouard  6432:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.227     brouard  6433:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6434:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6435:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6436:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6437:        vlv= nbcode[Tvaraff[k]][lv];
                   6438:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  6439:       }
                   6440:       fprintf(ficgp,"\n#\n");
1.223     brouard  6441:       if(invalidvarcomb[k1]){
1.227     brouard  6442:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6443:        continue;
1.223     brouard  6444:       }
1.227     brouard  6445:       
1.201     brouard  6446:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);
1.126     brouard  6447:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.227     brouard  6448: set ter svg size 640, 480\n                                            \
                   6449: unset log y\n                                                          \
1.153     brouard  6450: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  6451:       k=3; /* Offset */
1.153     brouard  6452:       for (i=1; i<= nlstate ; i ++){
1.227     brouard  6453:        if(i==1)
                   6454:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   6455:        else
                   6456:          fprintf(ficgp,", '' ");
                   6457:        l=(nlstate+ndeath)*(i-1)+1;
                   6458:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   6459:        for (j=2; j<= nlstate ; j ++)
                   6460:          fprintf(ficgp,"+$%d",k+l+j-1);
                   6461:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  6462:       } /* nlstate */
1.201     brouard  6463:       fprintf(ficgp,"\nset out\n");
1.153     brouard  6464:     } /* end cpt state*/ 
                   6465:   } /* end covariate */  
1.227     brouard  6466:   
                   6467:   
1.220     brouard  6468: /* 7eme */
1.218     brouard  6469:   if(backcast == 1){
1.217     brouard  6470:     /* CV back preval stable (period) for each covariate */
1.218     brouard  6471:     for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
                   6472:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.227     brouard  6473:        fprintf(ficgp,"\n#\n#\n#CV Back preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
                   6474:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6475:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6476:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6477:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
1.223     brouard  6478:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.227     brouard  6479:          vlv= nbcode[Tvaraff[k]][lv];
                   6480:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6481:        }
                   6482:        fprintf(ficgp,"\n#\n");
                   6483:        if(invalidvarcomb[k1]){
                   6484:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6485:          continue;
                   6486:        }
                   6487:        
                   6488:        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1);
                   6489:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
                   6490: set ter svg size 640, 480\n                                            \
                   6491: unset log y\n                                                          \
1.218     brouard  6492: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  6493:        k=3; /* Offset */
                   6494:        for (i=1; i<= nlstate ; i ++){
                   6495:          if(i==1)
                   6496:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   6497:          else
                   6498:            fprintf(ficgp,", '' ");
                   6499:          /* l=(nlstate+ndeath)*(i-1)+1; */
                   6500:          l=(nlstate+ndeath)*(cpt-1)+1;
                   6501:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   6502:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l+(cpt-1)+i-1); /\* a vérifier *\/ */
                   6503:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+(cpt-1)+i-1); /* a vérifier */
                   6504:          /* for (j=2; j<= nlstate ; j ++) */
                   6505:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   6506:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
                   6507:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",i,cpt);
                   6508:        } /* nlstate */
                   6509:        fprintf(ficgp,"\nset out\n");
1.218     brouard  6510:       } /* end cpt state*/ 
                   6511:     } /* end covariate */  
                   6512:   } /* End if backcast */
                   6513:   
1.223     brouard  6514:   /* 8eme */
1.218     brouard  6515:   if(prevfcast==1){
                   6516:     /* Projection from cross-sectional to stable (period) for each covariate */
                   6517:     
                   6518:     for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
1.211     brouard  6519:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.227     brouard  6520:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to stable (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
                   6521:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   6522:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   6523:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6524:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6525:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6526:          vlv= nbcode[Tvaraff[k]][lv];
                   6527:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6528:        }
                   6529:        fprintf(ficgp,"\n#\n");
                   6530:        if(invalidvarcomb[k1]){
                   6531:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6532:          continue;
                   6533:        }
                   6534:        
                   6535:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
                   6536:        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1);
                   6537:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   6538: set ter svg size 640, 480\n                                            \
                   6539: unset log y\n                                                          \
1.219     brouard  6540: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  6541:        for (i=1; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   6542:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   6543:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   6544:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   6545:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   6546:          if(i==1){
                   6547:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   6548:          }else{
                   6549:            fprintf(ficgp,",\\\n '' ");
                   6550:          }
                   6551:          if(cptcoveff ==0){ /* No covariate */
                   6552:            ioffset=2; /* Age is in 2 */
                   6553:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   6554:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   6555:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   6556:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   6557:            fprintf(ficgp," u %d:(", ioffset); 
                   6558:            if(i==nlstate+1)
                   6559:              fprintf(ficgp," $%d/(1.-$%d)) t 'pw.%d' with line ",      \
                   6560:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   6561:            else
                   6562:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   6563:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   6564:          }else{ /* more than 2 covariates */
                   6565:            if(cptcoveff ==1){
                   6566:              ioffset=4; /* Age is in 4 */
                   6567:            }else{
                   6568:              ioffset=6; /* Age is in 6 */
                   6569:              /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   6570:              /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   6571:            }   
                   6572:            fprintf(ficgp," u %d:(",ioffset); 
                   6573:            kl=0;
                   6574:            strcpy(gplotcondition,"(");
                   6575:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
                   6576:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   6577:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6578:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6579:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6580:              vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   6581:              kl++;
                   6582:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   6583:              kl++;
                   6584:              if(k <cptcoveff && cptcoveff>1)
                   6585:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   6586:            }
                   6587:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   6588:            /* 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 *\/ */
                   6589:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   6590:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   6591:            /* ''  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*/
                   6592:            if(i==nlstate+1){
                   6593:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p.%d' with line ", gplotcondition, \
                   6594:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   6595:            }else{
                   6596:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   6597:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   6598:            }
                   6599:          } /* end if covariate */
                   6600:        } /* nlstate */
                   6601:        fprintf(ficgp,"\nset out\n");
1.223     brouard  6602:       } /* end cpt state*/
                   6603:     } /* end covariate */
                   6604:   } /* End if prevfcast */
1.227     brouard  6605:   
                   6606:   
1.223     brouard  6607:   /* proba elementaires */
                   6608:   fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
1.126     brouard  6609:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  6610:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  6611:     for(k=1; k <=(nlstate+ndeath); k++){
                   6612:       if (k != i) {
1.227     brouard  6613:        fprintf(ficgp,"#   current state %d\n",k);
                   6614:        for(j=1; j <=ncovmodel; j++){
                   6615:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   6616:          jk++; 
                   6617:        }
                   6618:        fprintf(ficgp,"\n");
1.126     brouard  6619:       }
                   6620:     }
1.223     brouard  6621:   }
1.187     brouard  6622:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  6623:   
1.145     brouard  6624:   /*goto avoid;*/
1.200     brouard  6625:   fprintf(ficgp,"\n##############\n#Graphics of probabilities or incidences\n#############\n");
1.187     brouard  6626:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   6627:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   6628:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   6629:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   6630:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6631:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   6632:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6633:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   6634:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   6635:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6636:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   6637:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   6638:   fprintf(ficgp,"#\n");
1.223     brouard  6639:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
                   6640:     fprintf(ficgp,"# ng=%d\n",ng);
1.225     brouard  6641:     fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);
1.223     brouard  6642:     for(jk=1; jk <=m; jk++) {
                   6643:       fprintf(ficgp,"#    jk=%d\n",jk);
                   6644:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);
                   6645:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   6646:       if (ng==1){
                   6647:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   6648:        fprintf(ficgp,"\nunset log y");
                   6649:       }else if (ng==2){
                   6650:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   6651:        fprintf(ficgp,"\nset log y");
                   6652:       }else if (ng==3){
                   6653:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   6654:        fprintf(ficgp,"\nset log y");
                   6655:       }else
                   6656:        fprintf(ficgp,"\nunset title ");
                   6657:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   6658:       i=1;
                   6659:       for(k2=1; k2<=nlstate; k2++) {
                   6660:        k3=i;
                   6661:        for(k=1; k<=(nlstate+ndeath); k++) {
                   6662:          if (k != k2){
                   6663:            switch( ng) {
                   6664:            case 1:
                   6665:              if(nagesqr==0)
                   6666:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   6667:              else /* nagesqr =1 */
                   6668:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   6669:              break;
                   6670:            case 2: /* ng=2 */
                   6671:              if(nagesqr==0)
                   6672:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   6673:              else /* nagesqr =1 */
                   6674:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   6675:              break;
                   6676:            case 3:
                   6677:              if(nagesqr==0)
                   6678:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   6679:              else /* nagesqr =1 */
                   6680:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   6681:              break;
                   6682:            }
                   6683:            ij=1;/* To be checked else nbcode[0][0] wrong */
                   6684:            for(j=3; j <=ncovmodel-nagesqr; j++) {
                   6685:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
                   6686:              if(ij <=cptcovage) { /* Bug valgrind */
                   6687:                if((j-2)==Tage[ij]) { /* Bug valgrind */
                   6688:                  fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   6689:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   6690:                  ij++;
                   6691:                }
                   6692:              }
                   6693:              else
1.227     brouard  6694:                fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]); /* Valgrind bug nbcode */
1.223     brouard  6695:            }
                   6696:          }else{
                   6697:            i=i-ncovmodel;
                   6698:            if(ng !=1 ) /* For logit formula of log p11 is more difficult to get */
                   6699:              fprintf(ficgp," (1.");
                   6700:          }
1.227     brouard  6701:          
1.223     brouard  6702:          if(ng != 1){
                   6703:            fprintf(ficgp,")/(1");
1.227     brouard  6704:            
1.223     brouard  6705:            for(k1=1; k1 <=nlstate; k1++){ 
                   6706:              if(nagesqr==0)
                   6707:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                   6708:              else /* nagesqr =1 */
                   6709:                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  6710:               
1.223     brouard  6711:              ij=1;
                   6712:              for(j=3; j <=ncovmodel-nagesqr; j++){
                   6713:                if(ij <=cptcovage) { /* Bug valgrind */
                   6714:                  if((j-2)==Tage[ij]) { /* Bug valgrind */
                   6715:                    fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   6716:                    /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   6717:                    ij++;
                   6718:                  }
                   6719:                }
                   6720:                else
1.225     brouard  6721:                  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  6722:              }
                   6723:              fprintf(ficgp,")");
                   6724:            }
                   6725:            fprintf(ficgp,")");
                   6726:            if(ng ==2)
                   6727:              fprintf(ficgp," t \"p%d%d\" ", k2,k);
                   6728:            else /* ng= 3 */
                   6729:              fprintf(ficgp," t \"i%d%d\" ", k2,k);
                   6730:          }else{ /* end ng <> 1 */
                   6731:            if( k !=k2) /* logit p11 is hard to draw */
                   6732:              fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
                   6733:          }
                   6734:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   6735:            fprintf(ficgp,",");
                   6736:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   6737:            fprintf(ficgp,",");
                   6738:          i=i+ncovmodel;
                   6739:        } /* end k */
                   6740:       } /* end k2 */
                   6741:       fprintf(ficgp,"\n set out\n");
                   6742:     } /* end jk */
                   6743:   } /* end ng */
                   6744:   /* avoid: */
                   6745:   fflush(ficgp); 
1.126     brouard  6746: }  /* end gnuplot */
                   6747: 
                   6748: 
                   6749: /*************** Moving average **************/
1.219     brouard  6750: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  6751:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  6752:    
1.222     brouard  6753:    int i, cpt, cptcod;
                   6754:    int modcovmax =1;
                   6755:    int mobilavrange, mob;
                   6756:    int iage=0;
                   6757: 
                   6758:    double sum=0.;
                   6759:    double age;
                   6760:    double *sumnewp, *sumnewm;
                   6761:    double *agemingood, *agemaxgood; /* Currently identical for all covariates */
                   6762:   
                   6763:   
1.225     brouard  6764:    /* modcovmax=2*cptcoveff;/\* Max number of modalities. We suppose  */
1.222     brouard  6765:    /*             a covariate has 2 modalities, should be equal to ncovcombmax  *\/ */
                   6766: 
                   6767:    sumnewp = vector(1,ncovcombmax);
                   6768:    sumnewm = vector(1,ncovcombmax);
                   6769:    agemingood = vector(1,ncovcombmax); 
                   6770:    agemaxgood = vector(1,ncovcombmax);
                   6771: 
                   6772:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   6773:      sumnewm[cptcod]=0.;
                   6774:      sumnewp[cptcod]=0.;
                   6775:      agemingood[cptcod]=0;
                   6776:      agemaxgood[cptcod]=0;
                   6777:    }
                   6778:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   6779:   
                   6780:    if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   6781:      if(mobilav==1) mobilavrange=5; /* default */
                   6782:      else mobilavrange=mobilav;
                   6783:      for (age=bage; age<=fage; age++)
                   6784:        for (i=1; i<=nlstate;i++)
                   6785:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   6786:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   6787:      /* We keep the original values on the extreme ages bage, fage and for 
                   6788:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   6789:        we use a 5 terms etc. until the borders are no more concerned. 
                   6790:      */ 
                   6791:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   6792:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   6793:         for (i=1; i<=nlstate;i++){
                   6794:           for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   6795:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   6796:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   6797:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   6798:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   6799:             }
                   6800:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   6801:           }
                   6802:         }
                   6803:        }/* end age */
                   6804:      }/* end mob */
                   6805:    }else
                   6806:      return -1;
                   6807:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   6808:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   6809:      if(invalidvarcomb[cptcod]){
                   6810:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   6811:        continue;
                   6812:      }
1.219     brouard  6813: 
1.222     brouard  6814:      agemingood[cptcod]=fage-(mob-1)/2;
                   6815:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, finding the youngest wrong */
                   6816:        sumnewm[cptcod]=0.;
                   6817:        for (i=1; i<=nlstate;i++){
                   6818:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   6819:        }
                   6820:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   6821:         agemingood[cptcod]=age;
                   6822:        }else{ /* bad */
                   6823:         for (i=1; i<=nlstate;i++){
                   6824:           mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   6825:         } /* i */
                   6826:        } /* end bad */
                   6827:      }/* age */
                   6828:      sum=0.;
                   6829:      for (i=1; i<=nlstate;i++){
                   6830:        sum+=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   6831:      }
                   6832:      if(fabs(sum - 1.) > 1.e-3) { /* bad */
                   6833:        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);
                   6834:        /* for (i=1; i<=nlstate;i++){ */
                   6835:        /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   6836:        /* } /\* i *\/ */
                   6837:      } /* end bad */
                   6838:      /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   6839:      /* From youngest, finding the oldest wrong */
                   6840:      agemaxgood[cptcod]=bage+(mob-1)/2;
                   6841:      for (age=bage+(mob-1)/2; age<=fage; age++){
                   6842:        sumnewm[cptcod]=0.;
                   6843:        for (i=1; i<=nlstate;i++){
                   6844:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   6845:        }
                   6846:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   6847:         agemaxgood[cptcod]=age;
                   6848:        }else{ /* bad */
                   6849:         for (i=1; i<=nlstate;i++){
                   6850:           mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   6851:         } /* i */
                   6852:        } /* end bad */
                   6853:      }/* age */
                   6854:      sum=0.;
                   6855:      for (i=1; i<=nlstate;i++){
                   6856:        sum+=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   6857:      }
                   6858:      if(fabs(sum - 1.) > 1.e-3) { /* bad */
                   6859:        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);
                   6860:        /* for (i=1; i<=nlstate;i++){ */
                   6861:        /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   6862:        /* } /\* i *\/ */
                   6863:      } /* end bad */
                   6864:                
                   6865:      for (age=bage; age<=fage; age++){
                   6866:        printf("%d %d ", cptcod, (int)age);
                   6867:        sumnewp[cptcod]=0.;
                   6868:        sumnewm[cptcod]=0.;
                   6869:        for (i=1; i<=nlstate;i++){
                   6870:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   6871:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   6872:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   6873:        }
                   6874:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   6875:      }
                   6876:      /* printf("\n"); */
                   6877:      /* } */
                   6878:      /* brutal averaging */
                   6879:      for (i=1; i<=nlstate;i++){
                   6880:        for (age=1; age<=bage; age++){
                   6881:         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   6882:         /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
                   6883:        }       
                   6884:        for (age=fage; age<=AGESUP; age++){
                   6885:         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   6886:         /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
                   6887:        }
                   6888:      } /* end i status */
                   6889:      for (i=nlstate+1; i<=nlstate+ndeath;i++){
                   6890:        for (age=1; age<=AGESUP; age++){
                   6891:         /*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*/
                   6892:         mobaverage[(int)age][i][cptcod]=0.;
                   6893:        }
                   6894:      }
                   6895:    }/* end cptcod */
                   6896:    free_vector(sumnewm,1, ncovcombmax);
                   6897:    free_vector(sumnewp,1, ncovcombmax);
                   6898:    free_vector(agemaxgood,1, ncovcombmax);
                   6899:    free_vector(agemingood,1, ncovcombmax);
                   6900:    return 0;
                   6901:  }/* End movingaverage */
1.218     brouard  6902:  
1.126     brouard  6903: 
                   6904: /************** Forecasting ******************/
1.225     brouard  6905: 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  6906:   /* proj1, year, month, day of starting projection 
                   6907:      agemin, agemax range of age
                   6908:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   6909:      anproj2 year of en of projection (same day and month as proj1).
                   6910:   */
1.164     brouard  6911:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126     brouard  6912:   double agec; /* generic age */
                   6913:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   6914:   double *popeffectif,*popcount;
                   6915:   double ***p3mat;
1.218     brouard  6916:   /* double ***mobaverage; */
1.126     brouard  6917:   char fileresf[FILENAMELENGTH];
                   6918: 
                   6919:   agelim=AGESUP;
1.211     brouard  6920:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   6921:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   6922:      We still use firstpass and lastpass as another selection.
                   6923:   */
1.214     brouard  6924:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   6925:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  6926:  
1.201     brouard  6927:   strcpy(fileresf,"F_"); 
                   6928:   strcat(fileresf,fileresu);
1.126     brouard  6929:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   6930:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   6931:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   6932:   }
1.215     brouard  6933:   printf("Computing forecasting: result on file '%s', please wait... \n", fileresf);
                   6934:   fprintf(ficlog,"Computing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  6935: 
1.225     brouard  6936:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  6937: 
                   6938: 
                   6939:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   6940:   if (stepm<=12) stepsize=1;
                   6941:   if(estepm < stepm){
                   6942:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6943:   }
                   6944:   else  hstepm=estepm;   
                   6945: 
                   6946:   hstepm=hstepm/stepm; 
                   6947:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   6948:                                fractional in yp1 */
                   6949:   anprojmean=yp;
                   6950:   yp2=modf((yp1*12),&yp);
                   6951:   mprojmean=yp;
                   6952:   yp1=modf((yp2*30.5),&yp);
                   6953:   jprojmean=yp;
                   6954:   if(jprojmean==0) jprojmean=1;
                   6955:   if(mprojmean==0) jprojmean=1;
                   6956: 
1.227     brouard  6957:   i1=pow(2,cptcoveff);
1.126     brouard  6958:   if (cptcovn < 1){i1=1;}
                   6959:   
                   6960:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   6961:   
                   6962:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  6963:   
1.126     brouard  6964: /*           if (h==(int)(YEARM*yearp)){ */
1.227     brouard  6965:   for(k=1;k<=i1;k++){
                   6966:     if(invalidvarcomb[k]){
                   6967:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   6968:       continue;
                   6969:     }
                   6970:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   6971:     for(j=1;j<=cptcoveff;j++) {
                   6972:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   6973:     }
                   6974:     fprintf(ficresf," yearproj age");
                   6975:     for(j=1; j<=nlstate+ndeath;j++){ 
                   6976:       for(i=1; i<=nlstate;i++)               
                   6977:        fprintf(ficresf," p%d%d",i,j);
                   6978:       fprintf(ficresf," wp.%d",j);
                   6979:     }
                   6980:     for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
                   6981:       fprintf(ficresf,"\n");
                   6982:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   6983:       for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   6984:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   6985:        nhstepm = nhstepm/hstepm; 
                   6986:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6987:        oldm=oldms;savm=savms;
                   6988:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
                   6989:        
                   6990:        for (h=0; h<=nhstepm; h++){
                   6991:          if (h*hstepm/YEARM*stepm ==yearp) {
                   6992:            fprintf(ficresf,"\n");
                   6993:            for(j=1;j<=cptcoveff;j++) 
                   6994:              fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   6995:            fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   6996:          } 
                   6997:          for(j=1; j<=nlstate+ndeath;j++) {
                   6998:            ppij=0.;
                   6999:            for(i=1; i<=nlstate;i++) {
                   7000:              if (mobilav==1) 
                   7001:                ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][k];
                   7002:              else {
                   7003:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   7004:              }
                   7005:              if (h*hstepm/YEARM*stepm== yearp) {
                   7006:                fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   7007:              }
                   7008:            } /* end i */
                   7009:            if (h*hstepm/YEARM*stepm==yearp) {
                   7010:              fprintf(ficresf," %.3f", ppij);
                   7011:            }
                   7012:          }/* end j */
                   7013:        } /* end h */
                   7014:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7015:       } /* end agec */
                   7016:     } /* end yearp */
                   7017:   } /* end  k */
1.219     brouard  7018:        
1.126     brouard  7019:   fclose(ficresf);
1.215     brouard  7020:   printf("End of Computing forecasting \n");
                   7021:   fprintf(ficlog,"End of Computing forecasting\n");
                   7022: 
1.126     brouard  7023: }
                   7024: 
1.218     brouard  7025: /* /\************** Back Forecasting ******************\/ */
1.225     brouard  7026: /* 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  7027: /*   /\* back1, year, month, day of starting backection  */
                   7028: /*      agemin, agemax range of age */
                   7029: /*      dateprev1 dateprev2 range of dates during which prevalence is computed */
                   7030: /*      anback2 year of en of backection (same day and month as back1). */
                   7031: /*   *\/ */
                   7032: /*   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1; */
                   7033: /*   double agec; /\* generic age *\/ */
                   7034: /*   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean; */
                   7035: /*   double *popeffectif,*popcount; */
                   7036: /*   double ***p3mat; */
                   7037: /*   /\* double ***mobaverage; *\/ */
                   7038: /*   char fileresfb[FILENAMELENGTH]; */
                   7039:        
                   7040: /*   agelim=AGESUP; */
                   7041: /*   /\* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people */
                   7042: /*      in each health status at the date of interview (if between dateprev1 and dateprev2). */
                   7043: /*      We still use firstpass and lastpass as another selection. */
                   7044: /*   *\/ */
                   7045: /*   /\* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ *\/ */
                   7046: /*   /\*             firstpass, lastpass,  stepm,  weightopt, model); *\/ */
                   7047: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   7048:        
                   7049: /*   strcpy(fileresfb,"FB_");  */
                   7050: /*   strcat(fileresfb,fileresu); */
                   7051: /*   if((ficresfb=fopen(fileresfb,"w"))==NULL) { */
                   7052: /*     printf("Problem with back forecast resultfile: %s\n", fileresfb); */
                   7053: /*     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb); */
                   7054: /*   } */
                   7055: /*   printf("Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
                   7056: /*   fprintf(ficlog,"Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
                   7057:        
1.225     brouard  7058: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.218     brouard  7059:        
                   7060: /*   /\* if (mobilav!=0) { *\/ */
                   7061: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   7062: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   7063: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7064: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7065: /*   /\*   } *\/ */
                   7066: /*   /\* } *\/ */
                   7067:        
                   7068: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   7069: /*   if (stepm<=12) stepsize=1; */
                   7070: /*   if(estepm < stepm){ */
                   7071: /*     printf ("Problem %d lower than %d\n",estepm, stepm); */
                   7072: /*   } */
                   7073: /*   else  hstepm=estepm;    */
                   7074:        
                   7075: /*   hstepm=hstepm/stepm;  */
                   7076: /*   yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   7077: /*                                fractional in yp1 *\/ */
                   7078: /*   anprojmean=yp; */
                   7079: /*   yp2=modf((yp1*12),&yp); */
                   7080: /*   mprojmean=yp; */
                   7081: /*   yp1=modf((yp2*30.5),&yp); */
                   7082: /*   jprojmean=yp; */
                   7083: /*   if(jprojmean==0) jprojmean=1; */
                   7084: /*   if(mprojmean==0) jprojmean=1; */
                   7085:        
1.225     brouard  7086: /*   i1=cptcoveff; */
1.218     brouard  7087: /*   if (cptcovn < 1){i1=1;} */
1.217     brouard  7088:   
1.218     brouard  7089: /*   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);  */
1.217     brouard  7090:   
1.218     brouard  7091: /*   fprintf(ficresfb,"#****** Routine prevbackforecast **\n"); */
                   7092:        
                   7093: /*     /\*           if (h==(int)(YEARM*yearp)){ *\/ */
                   7094: /*   for(cptcov=1, k=0;cptcov<=i1;cptcov++){ */
1.225     brouard  7095: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
1.218     brouard  7096: /*       k=k+1; */
                   7097: /*       fprintf(ficresfb,"\n#****** hbijx=probability over h years, hp.jx is weighted by observed prev \n#"); */
1.225     brouard  7098: /*       for(j=1;j<=cptcoveff;j++) { */
1.218     brouard  7099: /*                             fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   7100: /*       } */
                   7101: /*       fprintf(ficresfb," yearbproj age"); */
                   7102: /*       for(j=1; j<=nlstate+ndeath;j++){  */
                   7103: /*                             for(i=1; i<=nlstate;i++)               */
                   7104: /*           fprintf(ficresfb," p%d%d",i,j); */
                   7105: /*                             fprintf(ficresfb," p.%d",j); */
                   7106: /*       } */
                   7107: /*       for (yearp=0; yearp>=(anback2-anback1);yearp -=stepsize) {  */
                   7108: /*                             /\* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  *\/ */
                   7109: /*                             fprintf(ficresfb,"\n"); */
                   7110: /*                             fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp);    */
                   7111: /*                             for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   7112: /*                                     nhstepm=(int) rint((agelim-agec)*YEARM/stepm);  */
                   7113: /*                                     nhstepm = nhstepm/hstepm;  */
                   7114: /*                                     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7115: /*                                     oldm=oldms;savm=savms; */
                   7116: /*                                     hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm,oldm,savm, dnewm, doldm, dsavm, k);       */
                   7117: /*                                     for (h=0; h<=nhstepm; h++){ */
                   7118: /*                                             if (h*hstepm/YEARM*stepm ==yearp) { */
                   7119: /*               fprintf(ficresfb,"\n"); */
1.225     brouard  7120: /*               for(j=1;j<=cptcoveff;j++)  */
1.218     brouard  7121: /*                 fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   7122: /*                                                     fprintf(ficresfb,"%.f %.f ",anback1+yearp,agec+h*hstepm/YEARM*stepm); */
                   7123: /*                                             }  */
                   7124: /*                                             for(j=1; j<=nlstate+ndeath;j++) { */
                   7125: /*                                                     ppij=0.; */
                   7126: /*                                                     for(i=1; i<=nlstate;i++) { */
                   7127: /*                                                             if (mobilav==1)  */
                   7128: /*                                                                     ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod]; */
                   7129: /*                                                             else { */
                   7130: /*                                                                     ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod]; */
                   7131: /*                                                             } */
                   7132: /*                                                             if (h*hstepm/YEARM*stepm== yearp) { */
                   7133: /*                                                                     fprintf(ficresfb," %.3f", p3mat[i][j][h]); */
                   7134: /*                                                             } */
                   7135: /*                                                     } /\* end i *\/ */
                   7136: /*                                                     if (h*hstepm/YEARM*stepm==yearp) { */
                   7137: /*                                                             fprintf(ficresfb," %.3f", ppij); */
                   7138: /*                                                     } */
                   7139: /*                                             }/\* end j *\/ */
                   7140: /*                                     } /\* end h *\/ */
                   7141: /*                                     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7142: /*                             } /\* end agec *\/ */
                   7143: /*       } /\* end yearp *\/ */
                   7144: /*     } /\* end cptcod *\/ */
                   7145: /*   } /\* end  cptcov *\/ */
                   7146:        
                   7147: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   7148:        
                   7149: /*   fclose(ficresfb); */
                   7150: /*   printf("End of Computing Back forecasting \n"); */
                   7151: /*   fprintf(ficlog,"End of Computing Back forecasting\n"); */
1.217     brouard  7152:        
1.218     brouard  7153: /* } */
1.217     brouard  7154: 
1.126     brouard  7155: /************** Forecasting *****not tested NB*************/
1.227     brouard  7156: /* 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  7157:   
1.227     brouard  7158: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   7159: /*   int *popage; */
                   7160: /*   double calagedatem, agelim, kk1, kk2; */
                   7161: /*   double *popeffectif,*popcount; */
                   7162: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   7163: /*   /\* double ***mobaverage; *\/ */
                   7164: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  7165: 
1.227     brouard  7166: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7167: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7168: /*   agelim=AGESUP; */
                   7169: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  7170:   
1.227     brouard  7171: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  7172:   
                   7173:   
1.227     brouard  7174: /*   strcpy(filerespop,"POP_");  */
                   7175: /*   strcat(filerespop,fileresu); */
                   7176: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   7177: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   7178: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   7179: /*   } */
                   7180: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   7181: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  7182: 
1.227     brouard  7183: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  7184: 
1.227     brouard  7185: /*   /\* if (mobilav!=0) { *\/ */
                   7186: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   7187: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   7188: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7189: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7190: /*   /\*   } *\/ */
                   7191: /*   /\* } *\/ */
1.126     brouard  7192: 
1.227     brouard  7193: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   7194: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  7195:   
1.227     brouard  7196: /*   agelim=AGESUP; */
1.126     brouard  7197:   
1.227     brouard  7198: /*   hstepm=1; */
                   7199: /*   hstepm=hstepm/stepm;  */
1.218     brouard  7200:        
1.227     brouard  7201: /*   if (popforecast==1) { */
                   7202: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   7203: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   7204: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   7205: /*     }  */
                   7206: /*     popage=ivector(0,AGESUP); */
                   7207: /*     popeffectif=vector(0,AGESUP); */
                   7208: /*     popcount=vector(0,AGESUP); */
1.126     brouard  7209:     
1.227     brouard  7210: /*     i=1;    */
                   7211: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  7212:     
1.227     brouard  7213: /*     imx=i; */
                   7214: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   7215: /*   } */
1.218     brouard  7216:   
1.227     brouard  7217: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   7218: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   7219: /*       k=k+1; */
                   7220: /*       fprintf(ficrespop,"\n#******"); */
                   7221: /*       for(j=1;j<=cptcoveff;j++) { */
                   7222: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   7223: /*       } */
                   7224: /*       fprintf(ficrespop,"******\n"); */
                   7225: /*       fprintf(ficrespop,"# Age"); */
                   7226: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   7227: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  7228:       
1.227     brouard  7229: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   7230: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  7231:        
1.227     brouard  7232: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   7233: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   7234: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  7235:          
1.227     brouard  7236: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7237: /*       oldm=oldms;savm=savms; */
                   7238: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  7239:          
1.227     brouard  7240: /*       for (h=0; h<=nhstepm; h++){ */
                   7241: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   7242: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   7243: /*         }  */
                   7244: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   7245: /*           kk1=0.;kk2=0; */
                   7246: /*           for(i=1; i<=nlstate;i++) {               */
                   7247: /*             if (mobilav==1)  */
                   7248: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   7249: /*             else { */
                   7250: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   7251: /*             } */
                   7252: /*           } */
                   7253: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   7254: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   7255: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   7256: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   7257: /*           } */
                   7258: /*         } */
                   7259: /*         for(i=1; i<=nlstate;i++){ */
                   7260: /*           kk1=0.; */
                   7261: /*           for(j=1; j<=nlstate;j++){ */
                   7262: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   7263: /*           } */
                   7264: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   7265: /*         } */
1.218     brouard  7266:            
1.227     brouard  7267: /*         if (h==(int)(calagedatem+12*cpt)) */
                   7268: /*           for(j=1; j<=nlstate;j++)  */
                   7269: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   7270: /*       } */
                   7271: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7272: /*     } */
                   7273: /*       } */
1.218     brouard  7274:       
1.227     brouard  7275: /*       /\******\/ */
1.218     brouard  7276:       
1.227     brouard  7277: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   7278: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   7279: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   7280: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   7281: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  7282:          
1.227     brouard  7283: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7284: /*       oldm=oldms;savm=savms; */
                   7285: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   7286: /*       for (h=0; h<=nhstepm; h++){ */
                   7287: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   7288: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   7289: /*         }  */
                   7290: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   7291: /*           kk1=0.;kk2=0; */
                   7292: /*           for(i=1; i<=nlstate;i++) {               */
                   7293: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   7294: /*           } */
                   7295: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   7296: /*         } */
                   7297: /*       } */
                   7298: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7299: /*     } */
                   7300: /*       } */
                   7301: /*     }  */
                   7302: /*   } */
1.218     brouard  7303:   
1.227     brouard  7304: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  7305:   
1.227     brouard  7306: /*   if (popforecast==1) { */
                   7307: /*     free_ivector(popage,0,AGESUP); */
                   7308: /*     free_vector(popeffectif,0,AGESUP); */
                   7309: /*     free_vector(popcount,0,AGESUP); */
                   7310: /*   } */
                   7311: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7312: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7313: /*   fclose(ficrespop); */
                   7314: /* } /\* End of popforecast *\/ */
1.218     brouard  7315:  
1.126     brouard  7316: int fileappend(FILE *fichier, char *optionfich)
                   7317: {
                   7318:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   7319:     printf("Problem with file: %s\n", optionfich);
                   7320:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   7321:     return (0);
                   7322:   }
                   7323:   fflush(fichier);
                   7324:   return (1);
                   7325: }
                   7326: 
                   7327: 
                   7328: /**************** function prwizard **********************/
                   7329: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   7330: {
                   7331: 
                   7332:   /* Wizard to print covariance matrix template */
                   7333: 
1.164     brouard  7334:   char ca[32], cb[32];
                   7335:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  7336:   int numlinepar;
                   7337: 
                   7338:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7339:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7340:   for(i=1; i <=nlstate; i++){
                   7341:     jj=0;
                   7342:     for(j=1; j <=nlstate+ndeath; j++){
                   7343:       if(j==i) continue;
                   7344:       jj++;
                   7345:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   7346:       printf("%1d%1d",i,j);
                   7347:       fprintf(ficparo,"%1d%1d",i,j);
                   7348:       for(k=1; k<=ncovmodel;k++){
                   7349:        /*        printf(" %lf",param[i][j][k]); */
                   7350:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   7351:        printf(" 0.");
                   7352:        fprintf(ficparo," 0.");
                   7353:       }
                   7354:       printf("\n");
                   7355:       fprintf(ficparo,"\n");
                   7356:     }
                   7357:   }
                   7358:   printf("# Scales (for hessian or gradient estimation)\n");
                   7359:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   7360:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   7361:   for(i=1; i <=nlstate; i++){
                   7362:     jj=0;
                   7363:     for(j=1; j <=nlstate+ndeath; j++){
                   7364:       if(j==i) continue;
                   7365:       jj++;
                   7366:       fprintf(ficparo,"%1d%1d",i,j);
                   7367:       printf("%1d%1d",i,j);
                   7368:       fflush(stdout);
                   7369:       for(k=1; k<=ncovmodel;k++){
                   7370:        /*      printf(" %le",delti3[i][j][k]); */
                   7371:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   7372:        printf(" 0.");
                   7373:        fprintf(ficparo," 0.");
                   7374:       }
                   7375:       numlinepar++;
                   7376:       printf("\n");
                   7377:       fprintf(ficparo,"\n");
                   7378:     }
                   7379:   }
                   7380:   printf("# Covariance matrix\n");
                   7381: /* # 121 Var(a12)\n\ */
                   7382: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   7383: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   7384: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   7385: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   7386: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   7387: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   7388: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   7389:   fflush(stdout);
                   7390:   fprintf(ficparo,"# Covariance matrix\n");
                   7391:   /* # 121 Var(a12)\n\ */
                   7392:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   7393:   /* #   ...\n\ */
                   7394:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   7395:   
                   7396:   for(itimes=1;itimes<=2;itimes++){
                   7397:     jj=0;
                   7398:     for(i=1; i <=nlstate; i++){
                   7399:       for(j=1; j <=nlstate+ndeath; j++){
                   7400:        if(j==i) continue;
                   7401:        for(k=1; k<=ncovmodel;k++){
                   7402:          jj++;
                   7403:          ca[0]= k+'a'-1;ca[1]='\0';
                   7404:          if(itimes==1){
                   7405:            printf("#%1d%1d%d",i,j,k);
                   7406:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   7407:          }else{
                   7408:            printf("%1d%1d%d",i,j,k);
                   7409:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   7410:            /*  printf(" %.5le",matcov[i][j]); */
                   7411:          }
                   7412:          ll=0;
                   7413:          for(li=1;li <=nlstate; li++){
                   7414:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   7415:              if(lj==li) continue;
                   7416:              for(lk=1;lk<=ncovmodel;lk++){
                   7417:                ll++;
                   7418:                if(ll<=jj){
                   7419:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   7420:                  if(ll<jj){
                   7421:                    if(itimes==1){
                   7422:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7423:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7424:                    }else{
                   7425:                      printf(" 0.");
                   7426:                      fprintf(ficparo," 0.");
                   7427:                    }
                   7428:                  }else{
                   7429:                    if(itimes==1){
                   7430:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   7431:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   7432:                    }else{
                   7433:                      printf(" 0.");
                   7434:                      fprintf(ficparo," 0.");
                   7435:                    }
                   7436:                  }
                   7437:                }
                   7438:              } /* end lk */
                   7439:            } /* end lj */
                   7440:          } /* end li */
                   7441:          printf("\n");
                   7442:          fprintf(ficparo,"\n");
                   7443:          numlinepar++;
                   7444:        } /* end k*/
                   7445:       } /*end j */
                   7446:     } /* end i */
                   7447:   } /* end itimes */
                   7448: 
                   7449: } /* end of prwizard */
                   7450: /******************* Gompertz Likelihood ******************************/
                   7451: double gompertz(double x[])
                   7452: { 
                   7453:   double A,B,L=0.0,sump=0.,num=0.;
                   7454:   int i,n=0; /* n is the size of the sample */
                   7455: 
1.220     brouard  7456:   for (i=1;i<=imx ; i++) {
1.126     brouard  7457:     sump=sump+weight[i];
                   7458:     /*    sump=sump+1;*/
                   7459:     num=num+1;
                   7460:   }
                   7461:  
                   7462:  
                   7463:   /* for (i=0; i<=imx; i++) 
                   7464:      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]);*/
                   7465: 
                   7466:   for (i=1;i<=imx ; i++)
                   7467:     {
                   7468:       if (cens[i] == 1 && wav[i]>1)
                   7469:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   7470:       
                   7471:       if (cens[i] == 0 && wav[i]>1)
                   7472:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   7473:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   7474:       
                   7475:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   7476:       if (wav[i] > 1 ) { /* ??? */
                   7477:        L=L+A*weight[i];
                   7478:        /*      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]);*/
                   7479:       }
                   7480:     }
                   7481: 
                   7482:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   7483:  
                   7484:   return -2*L*num/sump;
                   7485: }
                   7486: 
1.136     brouard  7487: #ifdef GSL
                   7488: /******************* Gompertz_f Likelihood ******************************/
                   7489: double gompertz_f(const gsl_vector *v, void *params)
                   7490: { 
                   7491:   double A,B,LL=0.0,sump=0.,num=0.;
                   7492:   double *x= (double *) v->data;
                   7493:   int i,n=0; /* n is the size of the sample */
                   7494: 
                   7495:   for (i=0;i<=imx-1 ; i++) {
                   7496:     sump=sump+weight[i];
                   7497:     /*    sump=sump+1;*/
                   7498:     num=num+1;
                   7499:   }
                   7500:  
                   7501:  
                   7502:   /* for (i=0; i<=imx; i++) 
                   7503:      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]);*/
                   7504:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   7505:   for (i=1;i<=imx ; i++)
                   7506:     {
                   7507:       if (cens[i] == 1 && wav[i]>1)
                   7508:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   7509:       
                   7510:       if (cens[i] == 0 && wav[i]>1)
                   7511:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   7512:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   7513:       
                   7514:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   7515:       if (wav[i] > 1 ) { /* ??? */
                   7516:        LL=LL+A*weight[i];
                   7517:        /*      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]);*/
                   7518:       }
                   7519:     }
                   7520: 
                   7521:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   7522:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   7523:  
                   7524:   return -2*LL*num/sump;
                   7525: }
                   7526: #endif
                   7527: 
1.126     brouard  7528: /******************* Printing html file ***********/
1.201     brouard  7529: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  7530:                  int lastpass, int stepm, int weightopt, char model[],\
                   7531:                  int imx,  double p[],double **matcov,double agemortsup){
                   7532:   int i,k;
                   7533: 
                   7534:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   7535:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   7536:   for (i=1;i<=2;i++) 
                   7537:     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  7538:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  7539:   fprintf(fichtm,"</ul>");
                   7540: 
                   7541: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   7542: 
                   7543:  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>");
                   7544: 
                   7545:  for (k=agegomp;k<(agemortsup-2);k++) 
                   7546:    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]);
                   7547: 
                   7548:  
                   7549:   fflush(fichtm);
                   7550: }
                   7551: 
                   7552: /******************* Gnuplot file **************/
1.201     brouard  7553: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  7554: 
                   7555:   char dirfileres[132],optfileres[132];
1.164     brouard  7556: 
1.126     brouard  7557:   int ng;
                   7558: 
                   7559: 
                   7560:   /*#ifdef windows */
                   7561:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   7562:     /*#endif */
                   7563: 
                   7564: 
                   7565:   strcpy(dirfileres,optionfilefiname);
                   7566:   strcpy(optfileres,"vpl");
1.199     brouard  7567:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  7568:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  7569:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  7570:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  7571:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   7572: 
                   7573: } 
                   7574: 
1.136     brouard  7575: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   7576: {
1.126     brouard  7577: 
1.136     brouard  7578:   /*-------- data file ----------*/
                   7579:   FILE *fic;
                   7580:   char dummy[]="                         ";
1.223     brouard  7581:   int i=0, j=0, n=0, iv=0;
                   7582:   int lstra;
1.136     brouard  7583:   int linei, month, year,iout;
                   7584:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  7585:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  7586:   char *stratrunc;
1.223     brouard  7587: 
1.126     brouard  7588: 
                   7589: 
1.136     brouard  7590:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  7591:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   7592:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  7593:   }
1.126     brouard  7594: 
1.136     brouard  7595:   i=1;
                   7596:   linei=0;
                   7597:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   7598:     linei=linei+1;
                   7599:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   7600:       if(line[j] == '\t')
                   7601:        line[j] = ' ';
                   7602:     }
                   7603:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   7604:       ;
                   7605:     };
                   7606:     line[j+1]=0;  /* Trims blanks at end of line */
                   7607:     if(line[0]=='#'){
                   7608:       fprintf(ficlog,"Comment line\n%s\n",line);
                   7609:       printf("Comment line\n%s\n",line);
                   7610:       continue;
                   7611:     }
                   7612:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  7613:     strcpy(line, linetmp);
1.223     brouard  7614:     
                   7615:     /* Loops on waves */
                   7616:     for (j=maxwav;j>=1;j--){
                   7617:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.232   ! brouard  7618:                                cutv(stra, strb, line, ' '); 
        !          7619:                                if(strb[0]=='.') { /* Missing value */
        !          7620:                                        lval=-1;
        !          7621:                                        cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
        !          7622:                                        cotvar[j][ntv+iv][i]=-1; /* For performance reasons */
        !          7623:                                        if(isalpha(strb[1])) { /* .m or .d Really Missing value */
        !          7624:                                                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);
        !          7625:                                                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);
        !          7626:                                                return 1;
        !          7627:                                        }
        !          7628:                                }else{
        !          7629:                                        errno=0;
        !          7630:                                        /* what_kind_of_number(strb); */
        !          7631:                                        dval=strtod(strb,&endptr); 
        !          7632:                                        /* if( strb[0]=='\0' || (*endptr != '\0')){ */
        !          7633:                                        /* if(strb != endptr && *endptr == '\0') */
        !          7634:                                        /*    dval=dlval; */
        !          7635:                                        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
        !          7636:                                        if( strb[0]=='\0' || (*endptr != '\0')){
        !          7637:                                                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);
        !          7638:                                                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);
        !          7639:                                                return 1;
        !          7640:                                        }
        !          7641:                                        cotqvar[j][iv][i]=dval; 
        !          7642:                                        cotvar[j][ntv+iv][i]=dval; 
        !          7643:                                }
        !          7644:                                strcpy(line,stra);
1.223     brouard  7645:       }/* end loop ntqv */
1.225     brouard  7646:       
1.223     brouard  7647:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.232   ! brouard  7648:                                cutv(stra, strb, line, ' '); 
        !          7649:                                if(strb[0]=='.') { /* Missing value */
        !          7650:                                        lval=-1;
        !          7651:                                }else{
        !          7652:                                        errno=0;
        !          7653:                                        lval=strtol(strb,&endptr,10); 
        !          7654:                                        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
        !          7655:                                        if( strb[0]=='\0' || (*endptr != '\0')){
        !          7656:                                                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);
        !          7657:                                                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);
        !          7658:                                                return 1;
        !          7659:                                        }
        !          7660:                                }
        !          7661:                                if(lval <-1 || lval >1){
        !          7662:                                        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.223     brouard  7663:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   7664:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.232   ! brouard  7665:  For example, for multinomial values like 1, 2 and 3,\n                                                                        \
        !          7666:  build V1=0 V2=0 for the reference value (1),\n                                                                                                        \
        !          7667:         V1=1 V2=0 for (2) \n                                                                                                                                                                           \
1.223     brouard  7668:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.232   ! brouard  7669:  output of IMaCh is often meaningless.\n                                                                                                                               \
1.223     brouard  7670:  Exiting.\n",lval,linei, i,line,j);
1.232   ! brouard  7671:                                        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.223     brouard  7672:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   7673:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.232   ! brouard  7674:  For example, for multinomial values like 1, 2 and 3,\n                                                                        \
        !          7675:  build V1=0 V2=0 for the reference value (1),\n                                                                                                        \
        !          7676:         V1=1 V2=0 for (2) \n                                                                                                                                                                           \
1.223     brouard  7677:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.232   ! brouard  7678:  output of IMaCh is often meaningless.\n                                                                                                                               \
1.223     brouard  7679:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.232   ! brouard  7680:                                        return 1;
        !          7681:                                }
        !          7682:                                cotvar[j][iv][i]=(double)(lval);
        !          7683:                                strcpy(line,stra);
1.223     brouard  7684:       }/* end loop ntv */
1.225     brouard  7685:       
1.223     brouard  7686:       /* Statuses  at wave */
1.137     brouard  7687:       cutv(stra, strb, line, ' '); 
1.223     brouard  7688:       if(strb[0]=='.') { /* Missing value */
1.232   ! brouard  7689:                                lval=-1;
1.136     brouard  7690:       }else{
1.232   ! brouard  7691:                                errno=0;
        !          7692:                                lval=strtol(strb,&endptr,10); 
        !          7693:                                /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
        !          7694:                                if( strb[0]=='\0' || (*endptr != '\0')){
        !          7695:                                        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);
        !          7696:                                        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);
        !          7697:                                        return 1;
        !          7698:                                }
1.136     brouard  7699:       }
1.225     brouard  7700:       
1.136     brouard  7701:       s[j][i]=lval;
1.225     brouard  7702:       
1.223     brouard  7703:       /* Date of Interview */
1.136     brouard  7704:       strcpy(line,stra);
                   7705:       cutv(stra, strb,line,' ');
1.169     brouard  7706:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  7707:       }
1.169     brouard  7708:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  7709:        month=99;
                   7710:        year=9999;
1.136     brouard  7711:       }else{
1.225     brouard  7712:        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);
                   7713:        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);
                   7714:        return 1;
1.136     brouard  7715:       }
                   7716:       anint[j][i]= (double) year; 
                   7717:       mint[j][i]= (double)month; 
                   7718:       strcpy(line,stra);
1.223     brouard  7719:     } /* End loop on waves */
1.225     brouard  7720:     
1.223     brouard  7721:     /* Date of death */
1.136     brouard  7722:     cutv(stra, strb,line,' '); 
1.169     brouard  7723:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  7724:     }
1.169     brouard  7725:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  7726:       month=99;
                   7727:       year=9999;
                   7728:     }else{
1.141     brouard  7729:       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  7730:       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);
                   7731:       return 1;
1.136     brouard  7732:     }
                   7733:     andc[i]=(double) year; 
                   7734:     moisdc[i]=(double) month; 
                   7735:     strcpy(line,stra);
                   7736:     
1.223     brouard  7737:     /* Date of birth */
1.136     brouard  7738:     cutv(stra, strb,line,' '); 
1.169     brouard  7739:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  7740:     }
1.169     brouard  7741:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  7742:       month=99;
                   7743:       year=9999;
                   7744:     }else{
1.141     brouard  7745:       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);
                   7746:       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  7747:       return 1;
1.136     brouard  7748:     }
                   7749:     if (year==9999) {
1.141     brouard  7750:       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);
                   7751:       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  7752:       return 1;
                   7753:       
1.136     brouard  7754:     }
                   7755:     annais[i]=(double)(year);
                   7756:     moisnais[i]=(double)(month); 
                   7757:     strcpy(line,stra);
1.225     brouard  7758:     
1.223     brouard  7759:     /* Sample weight */
1.136     brouard  7760:     cutv(stra, strb,line,' '); 
                   7761:     errno=0;
                   7762:     dval=strtod(strb,&endptr); 
                   7763:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  7764:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   7765:       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  7766:       fflush(ficlog);
                   7767:       return 1;
                   7768:     }
                   7769:     weight[i]=dval; 
                   7770:     strcpy(line,stra);
1.225     brouard  7771:     
1.223     brouard  7772:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   7773:       cutv(stra, strb, line, ' '); 
                   7774:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  7775:        lval=-1;
1.223     brouard  7776:       }else{
1.225     brouard  7777:        errno=0;
                   7778:        /* what_kind_of_number(strb); */
                   7779:        dval=strtod(strb,&endptr);
                   7780:        /* if(strb != endptr && *endptr == '\0') */
                   7781:        /*   dval=dlval; */
                   7782:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   7783:        if( strb[0]=='\0' || (*endptr != '\0')){
                   7784:          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);
                   7785:          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);
                   7786:          return 1;
                   7787:        }
                   7788:        coqvar[iv][i]=dval; 
1.226     brouard  7789:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  7790:       }
                   7791:       strcpy(line,stra);
                   7792:     }/* end loop nqv */
1.136     brouard  7793:     
1.223     brouard  7794:     /* Covariate values */
1.136     brouard  7795:     for (j=ncovcol;j>=1;j--){
                   7796:       cutv(stra, strb,line,' '); 
1.223     brouard  7797:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  7798:        lval=-1;
1.136     brouard  7799:       }else{
1.225     brouard  7800:        errno=0;
                   7801:        lval=strtol(strb,&endptr,10); 
                   7802:        if( strb[0]=='\0' || (*endptr != '\0')){
                   7803:          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);
                   7804:          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);
                   7805:          return 1;
                   7806:        }
1.136     brouard  7807:       }
                   7808:       if(lval <-1 || lval >1){
1.225     brouard  7809:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  7810:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   7811:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  7812:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   7813:  build V1=0 V2=0 for the reference value (1),\n                                \
                   7814:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  7815:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  7816:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  7817:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  7818:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  7819:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   7820:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  7821:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   7822:  build V1=0 V2=0 for the reference value (1),\n                                \
                   7823:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  7824:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  7825:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  7826:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  7827:        return 1;
1.136     brouard  7828:       }
                   7829:       covar[j][i]=(double)(lval);
                   7830:       strcpy(line,stra);
                   7831:     }  
                   7832:     lstra=strlen(stra);
1.225     brouard  7833:     
1.136     brouard  7834:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   7835:       stratrunc = &(stra[lstra-9]);
                   7836:       num[i]=atol(stratrunc);
                   7837:     }
                   7838:     else
                   7839:       num[i]=atol(stra);
                   7840:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   7841:       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;}*/
                   7842:     
                   7843:     i=i+1;
                   7844:   } /* End loop reading  data */
1.225     brouard  7845:   
1.136     brouard  7846:   *imax=i-1; /* Number of individuals */
                   7847:   fclose(fic);
1.225     brouard  7848:   
1.136     brouard  7849:   return (0);
1.164     brouard  7850:   /* endread: */
1.225     brouard  7851:   printf("Exiting readdata: ");
                   7852:   fclose(fic);
                   7853:   return (1);
1.223     brouard  7854: }
1.126     brouard  7855: 
1.230     brouard  7856: void removespace(char **stri){/*, char stro[]) {*/
                   7857:   char *p1 = *stri, *p2 = *stri;
1.145     brouard  7858:   do
                   7859:     while (*p2 == ' ')
                   7860:       p2++;
1.169     brouard  7861:   while (*p1++ == *p2++);
1.230     brouard  7862:   *stri=p1; 
1.145     brouard  7863: }
                   7864: 
1.230     brouard  7865: int decoderesult ( char resultline[])
                   7866: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   7867: {
                   7868:   int j=0, k=0;
                   7869:   char resultsav[MAXLINE];
                   7870:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   7871: 
                   7872:   removespace(&resultline);
                   7873:   printf("decoderesult=%s\n",resultline);
                   7874: 
                   7875:   if (strstr(resultline,"v") !=0){
                   7876:     printf("Error. 'v' must be in upper case 'V' result: %s ",resultline);
                   7877:     fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultline);fflush(ficlog);
                   7878:     return 1;
                   7879:   }
                   7880:   trimbb(resultsav, resultline);
                   7881:   if (strlen(resultsav) >1){
                   7882:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' */
                   7883:   }
                   7884: 
                   7885:   for(k=1; k<=j;k++){ /* Loop on total covariates of the model */
                   7886:     cutl(stra,strb,resultsav,' '); /* keeps in strb after the first ' ' 
                   7887:                                     resultsav= V4=1 V5=25.1 V3=0 strb=V3=0 stra= V4=1 V5=25.1 */
                   7888:     cutl(strc,strd,strb,'=');  /* strb:V4=1 strc=1 strd=V4 */
                   7889:     Tvalsel[k]=atof(strc); /* 1 */
                   7890: 
                   7891:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
                   7892:     Tvarsel[k]=atoi(strc);
                   7893:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   7894:     /* cptcovsel++;     */
                   7895:     if (nbocc(stra,'=') >0)
                   7896:       strcpy(resultsav,stra); /* and analyzes it */
                   7897:   }
                   7898:   return (0);
                   7899: }
                   7900: int selected( int kvar){ /* Selected combination of covariates */
                   7901:   if(Tvarsel[kvar])
                   7902:     return (0);
                   7903:   else
                   7904:     return(1);
                   7905: }
                   7906: int decodemodel( char model[], int lastobs)
                   7907:  /**< This routine decodes the model and returns:
1.224     brouard  7908:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   7909:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   7910:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   7911:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   7912:        * - cptcovage number of covariates with age*products =2
                   7913:        * - cptcovs number of simple covariates
                   7914:        * - 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
                   7915:        *     which is a new column after the 9 (ncovcol) variables. 
                   7916:        * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   7917:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   7918:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   7919:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   7920:        */
1.136     brouard  7921: {
1.145     brouard  7922:   int i, j, k, ks;
1.227     brouard  7923:   int  j1, k1, k2, k3, k4;
1.136     brouard  7924:   char modelsav[80];
1.145     brouard  7925:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  7926:   char *strpt;
1.136     brouard  7927: 
1.145     brouard  7928:   /*removespace(model);*/
1.136     brouard  7929:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  7930:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  7931:     if (strstr(model,"AGE") !=0){
1.192     brouard  7932:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   7933:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  7934:       return 1;
                   7935:     }
1.141     brouard  7936:     if (strstr(model,"v") !=0){
                   7937:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   7938:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   7939:       return 1;
                   7940:     }
1.187     brouard  7941:     strcpy(modelsav,model); 
                   7942:     if ((strpt=strstr(model,"age*age")) !=0){
                   7943:       printf(" strpt=%s, model=%s\n",strpt, model);
                   7944:       if(strpt != model){
1.231     brouard  7945:                                printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  7946:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  7947:  corresponding column of parameters.\n",model);
1.231     brouard  7948:                                fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  7949:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  7950:  corresponding column of parameters.\n",model); fflush(ficlog);
1.231     brouard  7951:                                return 1;
1.225     brouard  7952:       }
1.187     brouard  7953:       nagesqr=1;
                   7954:       if (strstr(model,"+age*age") !=0)
1.231     brouard  7955:                                substrchaine(modelsav, model, "+age*age");
1.187     brouard  7956:       else if (strstr(model,"age*age+") !=0)
1.231     brouard  7957:                                substrchaine(modelsav, model, "age*age+");
1.187     brouard  7958:       else 
1.231     brouard  7959:                                substrchaine(modelsav, model, "age*age");
1.187     brouard  7960:     }else
                   7961:       nagesqr=0;
                   7962:     if (strlen(modelsav) >1){
                   7963:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   7964:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.224     brouard  7965:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.187     brouard  7966:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  7967:                     * cst, age and age*age 
                   7968:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   7969:       /* including age products which are counted in cptcovage.
                   7970:        * but the covariates which are products must be treated 
                   7971:        * separately: ncovn=4- 2=2 (V1+V3). */
1.187     brouard  7972:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   7973:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.225     brouard  7974:       
                   7975:       
1.187     brouard  7976:       /*   Design
                   7977:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   7978:        *  <          ncovcol=8                >
                   7979:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   7980:        *   k=  1    2      3       4     5       6      7        8
                   7981:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   7982:        *  covar[k,i], value of kth covariate if not including age for individual i:
1.224     brouard  7983:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   7984:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  7985:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   7986:        *  Tage[++cptcovage]=k
                   7987:        *       if products, new covar are created after ncovcol with k1
                   7988:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   7989:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   7990:        *  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
                   7991:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   7992:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   7993:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   7994:        *  <          ncovcol=8                >
                   7995:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   7996:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   7997:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   7998:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   7999:        * p Tprod[1]@2={                         6, 5}
                   8000:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   8001:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   8002:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   8003:        *How to reorganize?
                   8004:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   8005:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   8006:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   8007:        * Struct []
                   8008:        */
1.225     brouard  8009:       
1.187     brouard  8010:       /* This loop fills the array Tvar from the string 'model'.*/
                   8011:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   8012:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   8013:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   8014:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   8015:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   8016:       /*       k=1 Tvar[1]=2 (from V2) */
                   8017:       /*       k=5 Tvar[5] */
                   8018:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  8019:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  8020:       /*       } */
1.198     brouard  8021:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  8022:       /*
                   8023:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  8024:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   8025:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   8026:       }
1.187     brouard  8027:       cptcovage=0;
                   8028:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
1.232   ! brouard  8029:                                cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
1.225     brouard  8030:                                         modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
1.232   ! brouard  8031:                                if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
        !          8032:                                /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
        !          8033:                                /*scanf("%d",i);*/
        !          8034:                                if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
        !          8035:                                        cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
        !          8036:                                        if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
        !          8037:                                                /* covar is not filled and then is empty */
        !          8038:                                                cptcovprod--;
        !          8039:                                                cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
        !          8040:                                                Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
        !          8041:                                                Typevar[k]=1;  /* 1 for age product */
        !          8042:                                                cptcovage++; /* Sums the number of covariates which include age as a product */
        !          8043:                                                Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
        !          8044:                                                /*printf("stre=%s ", stre);*/
        !          8045:                                        } else if (strcmp(strd,"age")==0) { /* or age*Vn */
        !          8046:                                                cptcovprod--;
        !          8047:                                                cutl(stre,strb,strc,'V');
        !          8048:                                                Tvar[k]=atoi(stre);
        !          8049:                                                Typevar[k]=1;  /* 1 for age product */
        !          8050:                                                cptcovage++;
        !          8051:                                                Tage[cptcovage]=k;
        !          8052:                                        } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
        !          8053:                                                /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
        !          8054:                                                cptcovn++;
        !          8055:                                                cptcovprodnoage++;k1++;
        !          8056:                                                cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
        !          8057:                                                Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* For model-covariate k tells which data-covariate to use but
        !          8058:                                                                                                                                                                                                because this model-covariate is a construction we invent a new column
        !          8059:                                                                                                                                                                                                which is after existing variables ncovcol+nqv+ntv+nqtv + k1
        !          8060:                                                                                                                                                                                                If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
        !          8061:                                                                                                                                                                                                Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
        !          8062:                                                Typevar[k]=2;  /* 2 for double fixed dummy covariates */
        !          8063:                                                cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
        !          8064:                                                Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
        !          8065:                                                Tposprod[k]=k1; /* Tpsprod[3]=1, Tposprod[2]=5 */
        !          8066:                                                Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
        !          8067:                                                Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
        !          8068:                                                k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
        !          8069:                                                /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
        !          8070:                                                /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
1.225     brouard  8071:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
1.232   ! brouard  8072:                                                /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
        !          8073:                                                for (i=1; i<=lastobs;i++){
        !          8074:                                                        /* Computes the new covariate which is a product of
        !          8075:                                                                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
        !          8076:                                                        covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
        !          8077:                                                }
        !          8078:                                        } /* End age is not in the model */
        !          8079:                                } /* End if model includes a product */
        !          8080:                                else { /* no more sum */
        !          8081:                                        /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
        !          8082:                                        /*  scanf("%d",i);*/
        !          8083:                                        cutl(strd,strc,strb,'V');
        !          8084:                                        ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
        !          8085:                                        cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
        !          8086:                                        Tvar[k]=atoi(strd);
        !          8087:                                        Typevar[k]=0;  /* 0 for simple covariates */
        !          8088:                                }
        !          8089:                                strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  8090:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  8091:                                  scanf("%d",i);*/
1.187     brouard  8092:       } /* end of loop + on total covariates */
                   8093:     } /* end if strlen(modelsave == 0) age*age might exist */
                   8094:   } /* end if strlen(model == 0) */
1.136     brouard  8095:   
                   8096:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   8097:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  8098:   
1.136     brouard  8099:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  8100:      printf("cptcovprod=%d ", cptcovprod);
                   8101:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   8102:      scanf("%d ",i);*/
                   8103: 
                   8104: 
1.230     brouard  8105: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   8106:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  8107: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   8108:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   8109:    k =           1    2   3     4       5       6      7      8        9
                   8110:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
                   8111:    Typevar[k]=   0    0   0     2       1       0      2      1        1
1.227     brouard  8112:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   8113:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   8114:          Tmodelind[combination of covar]=k;
1.225     brouard  8115: */  
                   8116: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  8117:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  8118:   /* 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  8119:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.227     brouard  8120:   printf("Model=%s\n\
                   8121: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   8122: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   8123: 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);
                   8124:   fprintf(ficlog,"Model=%s\n\
                   8125: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   8126: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   8127: 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);
                   8128: 
1.232   ! brouard  8129:   for(k=1, ncovf=0, ncovv=0, ncova=0, ncoveff=0, nqfveff=0, ntveff=0, nqtveff=0;k<=cptcovt; k++){ /* or cptocvt */
1.231     brouard  8130:     if (Tvar[k] <=ncovcol && (Typevar[k]==0 || Typevar[k]==2)){ /* Simple or product fixed dummy (<=ncovcol) covariates */
1.227     brouard  8131:       Fixed[k]= 0;
                   8132:       Dummy[k]= 0;
1.225     brouard  8133:       ncoveff++;
1.232   ! brouard  8134:       ncovf++;
1.231     brouard  8135:                        modell[k].maintype= FTYPE;
1.232   ! brouard  8136:                        TvarF[ncovf]=Tvar[k];
        !          8137:                        TvarFind[ncovf]=k;
1.230     brouard  8138:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  8139:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8140:     }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  8141:       Fixed[k]= 0;
                   8142:       Dummy[k]= 1;
1.230     brouard  8143:       nqfveff++;
1.231     brouard  8144:                        modell[k].maintype= FTYPE;
                   8145:                        modell[k].subtype= FQ;
1.232   ! brouard  8146:       ncovf++;
        !          8147:                        TvarF[ncovf]=Tvar[k];
        !          8148:                        TvarFind[ncovf]=k;
1.231     brouard  8149:       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  8150:       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.225     brouard  8151:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){
1.227     brouard  8152:       Fixed[k]= 1;
                   8153:       Dummy[k]= 0;
1.225     brouard  8154:       ntveff++; /* Only simple time varying dummy variable */
1.231     brouard  8155:                        modell[k].maintype= VTYPE;
                   8156:                        modell[k].subtype= VD;
1.232   ! brouard  8157:                        ncovv++; /* Only simple time varying variables */
        !          8158:                        TvarV[ncovv]=Tvar[k];
        !          8159:                        TvarVind[ncovv]=k;
1.231     brouard  8160:       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 */
                   8161:       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  8162:       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);
                   8163:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  8164:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
                   8165:                        Fixed[k]= 1;
                   8166:                        Dummy[k]= 1;
                   8167:                        nqtveff++;
                   8168:                        modell[k].maintype= VTYPE;
                   8169:                        modell[k].subtype= VQ;
1.232   ! brouard  8170:                        ncovv++; /* Only simple time varying variables */
        !          8171:                        TvarV[ncovv]=Tvar[k];
        !          8172:                        TvarVind[ncovv]=k;
1.231     brouard  8173:       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 */
                   8174:       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 */
                   8175:                        TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   8176:                        /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
                   8177:                        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  8178:       printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv);
1.227     brouard  8179:     }else if (Typevar[k] == 1) {  /* product with age */
1.232   ! brouard  8180:                        ncova++;
        !          8181:                        TvarA[ncova]=Tvar[k];
        !          8182:                        TvarAind[ncova]=k;
1.231     brouard  8183:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
                   8184:                                Fixed[k]= 2;
                   8185:                                Dummy[k]= 2;
                   8186:                                modell[k].maintype= ATYPE;
                   8187:                                modell[k].subtype= APFD;
                   8188:                                /* ncoveff++; */
1.227     brouard  8189:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.231     brouard  8190:                                Fixed[k]= 2;
                   8191:                                Dummy[k]= 3;
                   8192:                                modell[k].maintype= ATYPE;
                   8193:                                modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
                   8194:                                /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  8195:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.231     brouard  8196:                                Fixed[k]= 3;
                   8197:                                Dummy[k]= 2;
                   8198:                                modell[k].maintype= ATYPE;
                   8199:                                modell[k].subtype= APVD;                /*      Product age * varying dummy */
                   8200:                                /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  8201:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.231     brouard  8202:                                Fixed[k]= 3;
                   8203:                                Dummy[k]= 3;
                   8204:                                modell[k].maintype= ATYPE;
                   8205:                                modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
                   8206:                                /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  8207:       }
                   8208:     }else if (Typevar[k] == 2) {  /* product without age */
                   8209:       k1=Tposprod[k];
1.232   ! brouard  8210:                        ncovv++; /* Only time varying variables */
        !          8211:                        TvarV[ncovv]=Tvar[k];
        !          8212:                        TvarVind[ncovv]=k;
1.227     brouard  8213:       if(Tvard[k1][1] <=ncovcol){
1.231     brouard  8214:                                if(Tvard[k1][2] <=ncovcol){
                   8215:                                        Fixed[k]= 1;
                   8216:                                        Dummy[k]= 0;
                   8217:                                        modell[k].maintype= FTYPE;
                   8218:                                        modell[k].subtype= FPDD;                /*      Product fixed dummy * fixed dummy */
                   8219:                                }else if(Tvard[k1][2] <=ncovcol+nqv){
                   8220:                                        Fixed[k]= 0;  /* or 2 ?*/
                   8221:                                        Dummy[k]= 1;
                   8222:                                        modell[k].maintype= FTYPE;
                   8223:                                        modell[k].subtype= FPDQ;                /*      Product fixed dummy * fixed quantitative */
                   8224:                                }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   8225:                                        Fixed[k]= 1;
                   8226:                                        Dummy[k]= 0;
                   8227:                                        modell[k].maintype= VTYPE;
                   8228:                                        modell[k].subtype= VPDD;                /*      Product fixed dummy * varying dummy */
                   8229:                                }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   8230:                                        Fixed[k]= 1;
                   8231:                                        Dummy[k]= 1;
                   8232:                                        modell[k].maintype= VTYPE;
                   8233:                                        modell[k].subtype= VPDQ;                /*      Product fixed dummy * varying quantitative */
                   8234:                                } 
1.227     brouard  8235:       }else if(Tvard[k1][1] <=ncovcol+nqv){
1.231     brouard  8236:                                if(Tvard[k1][2] <=ncovcol){
                   8237:                                        Fixed[k]= 0;  /* or 2 ?*/
                   8238:                                        Dummy[k]= 1;
                   8239:                                        modell[k].maintype= FTYPE;
                   8240:                                        modell[k].subtype= FPDQ;                /*      Product fixed quantitative * fixed dummy */
                   8241:                                }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   8242:                                        Fixed[k]= 1;
                   8243:                                        Dummy[k]= 1;
                   8244:                                        modell[k].maintype= VTYPE;
                   8245:                                        modell[k].subtype= VPDQ;                /*      Product fixed quantitative * varying dummy */
                   8246:                                }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   8247:                                        Fixed[k]= 1;
                   8248:                                        Dummy[k]= 1;
                   8249:                                        modell[k].maintype= VTYPE;
                   8250:                                        modell[k].subtype= VPQQ;                /*      Product fixed quantitative * varying quantitative */
                   8251:                                } 
1.227     brouard  8252:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){
1.231     brouard  8253:                                if(Tvard[k1][2] <=ncovcol){
                   8254:                                        Fixed[k]= 1;
                   8255:                                        Dummy[k]= 1;
                   8256:                                        modell[k].maintype= VTYPE;
                   8257:                                        modell[k].subtype= VPDD;                /*      Product time varying dummy * fixed dummy */
                   8258:                                }else if(Tvard[k1][2] <=ncovcol+nqv){
                   8259:                                        Fixed[k]= 1;
                   8260:                                        Dummy[k]= 1;
                   8261:                                        modell[k].maintype= VTYPE;
                   8262:                                        modell[k].subtype= VPDQ;                /*      Product time varying dummy * fixed quantitative */
                   8263:                                }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   8264:                                        Fixed[k]= 1;
                   8265:                                        Dummy[k]= 0;
                   8266:                                        modell[k].maintype= VTYPE;
                   8267:                                        modell[k].subtype= VPDD;                /*      Product time varying dummy * time varying dummy */
                   8268:                                }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   8269:                                        Fixed[k]= 1;
                   8270:                                        Dummy[k]= 1;
                   8271:                                        modell[k].maintype= VTYPE;
                   8272:                                        modell[k].subtype= VPDQ;                /*      Product time varying dummy * time varying quantitative */
                   8273:                                } 
1.227     brouard  8274:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){
1.231     brouard  8275:                                if(Tvard[k1][2] <=ncovcol){
                   8276:                                        Fixed[k]= 1;
                   8277:                                        Dummy[k]= 1;
                   8278:                                        modell[k].maintype= VTYPE;
                   8279:                                        modell[k].subtype= VPDQ;                /*      Product time varying quantitative * fixed dummy */
                   8280:                                }else if(Tvard[k1][2] <=ncovcol+nqv){
                   8281:                                        Fixed[k]= 1;
                   8282:                                        Dummy[k]= 1;
                   8283:                                        modell[k].maintype= VTYPE;
                   8284:                                        modell[k].subtype= VPQQ;                /*      Product time varying quantitative * fixed quantitative */
                   8285:                                }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   8286:                                        Fixed[k]= 1;
                   8287:                                        Dummy[k]= 1;
                   8288:                                        modell[k].maintype= VTYPE;
                   8289:                                        modell[k].subtype= VPDQ;                /*      Product time varying quantitative * time varying dummy */
                   8290:                                }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   8291:                                        Fixed[k]= 1;
                   8292:                                        Dummy[k]= 1;
                   8293:                                        modell[k].maintype= VTYPE;
                   8294:                                        modell[k].subtype= VPQQ;                /*      Product time varying quantitative * time varying quantitative */
                   8295:                                } 
1.227     brouard  8296:       }else{
1.231     brouard  8297:                                printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   8298:                                fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
1.226     brouard  8299:       } /* end k1 */
1.225     brouard  8300:     }else{
1.226     brouard  8301:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   8302:       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  8303:     }
1.227     brouard  8304:     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  8305:     printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype);
1.227     brouard  8306:     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]);
                   8307:   }
                   8308:   /* Searching for doublons in the model */
                   8309:   for(k1=1; k1<= cptcovt;k1++){
                   8310:     for(k2=1; k2 <k1;k2++){
                   8311:       if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){
1.231     brouard  8312:                                if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   8313:                                        if(Tvar[k1]==Tvar[k2]){
                   8314:                                                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]]);
                   8315:                                                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);
                   8316:                                                return(1);
                   8317:                                        }
                   8318:                                }else if (Typevar[k1] ==2){
                   8319:                                        k3=Tposprod[k1];
                   8320:                                        k4=Tposprod[k2];
                   8321:                                        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])) ){
                   8322:                                                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]]);
                   8323:                                                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);
                   8324:                                                return(1);
                   8325:                                        }
                   8326:                                }
1.227     brouard  8327:       }
                   8328:     }
1.225     brouard  8329:   }
                   8330:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   8331:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.232   ! brouard  8332:   printf("ncovf=%d, ncovv=%d, ncova=%d\n",ncovf,ncovv,ncova);
        !          8333:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d\n",ncovf,ncovv,ncova);
1.137     brouard  8334:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  8335:   /*endread:*/
1.225     brouard  8336:   printf("Exiting decodemodel: ");
                   8337:   return (1);
1.136     brouard  8338: }
                   8339: 
1.169     brouard  8340: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136     brouard  8341: {
                   8342:   int i, m;
1.218     brouard  8343:   int firstone=0;
                   8344:   
1.136     brouard  8345:   for (i=1; i<=imx; i++) {
                   8346:     for(m=2; (m<= maxwav); m++) {
                   8347:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   8348:        anint[m][i]=9999;
1.216     brouard  8349:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   8350:          s[m][i]=-1;
1.136     brouard  8351:       }
                   8352:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169     brouard  8353:        *nberr = *nberr + 1;
1.218     brouard  8354:        if(firstone == 0){
                   8355:          firstone=1;
                   8356:        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);
                   8357:        }
                   8358:        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  8359:        s[m][i]=-1;
                   8360:       }
                   8361:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  8362:        (*nberr)++;
1.136     brouard  8363:        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]); 
                   8364:        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]); 
                   8365:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   8366:       }
                   8367:     }
                   8368:   }
                   8369: 
                   8370:   for (i=1; i<=imx; i++)  {
                   8371:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   8372:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  8373:       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  8374:        if (s[m][i] >= nlstate+1) {
1.169     brouard  8375:          if(agedc[i]>0){
                   8376:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  8377:              agev[m][i]=agedc[i];
1.214     brouard  8378:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  8379:            }else {
1.136     brouard  8380:              if ((int)andc[i]!=9999){
                   8381:                nbwarn++;
                   8382:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   8383:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   8384:                agev[m][i]=-1;
                   8385:              }
                   8386:            }
1.169     brouard  8387:          } /* agedc > 0 */
1.214     brouard  8388:        } /* end if */
1.136     brouard  8389:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   8390:                                 years but with the precision of a month */
                   8391:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   8392:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   8393:            agev[m][i]=1;
                   8394:          else if(agev[m][i] < *agemin){ 
                   8395:            *agemin=agev[m][i];
                   8396:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   8397:          }
                   8398:          else if(agev[m][i] >*agemax){
                   8399:            *agemax=agev[m][i];
1.156     brouard  8400:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  8401:          }
                   8402:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   8403:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  8404:        } /* en if 9*/
1.136     brouard  8405:        else { /* =9 */
1.214     brouard  8406:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  8407:          agev[m][i]=1;
                   8408:          s[m][i]=-1;
                   8409:        }
                   8410:       }
1.214     brouard  8411:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  8412:        agev[m][i]=1;
1.214     brouard  8413:       else{
                   8414:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   8415:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   8416:        agev[m][i]=0;
                   8417:       }
                   8418:     } /* End for lastpass */
                   8419:   }
1.136     brouard  8420:     
                   8421:   for (i=1; i<=imx; i++)  {
                   8422:     for(m=firstpass; (m<=lastpass); m++){
                   8423:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  8424:        (*nberr)++;
1.136     brouard  8425:        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);     
                   8426:        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);     
                   8427:        return 1;
                   8428:       }
                   8429:     }
                   8430:   }
                   8431: 
                   8432:   /*for (i=1; i<=imx; i++){
                   8433:   for (m=firstpass; (m<lastpass); m++){
                   8434:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   8435: }
                   8436: 
                   8437: }*/
                   8438: 
                   8439: 
1.139     brouard  8440:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   8441:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  8442: 
                   8443:   return (0);
1.164     brouard  8444:  /* endread:*/
1.136     brouard  8445:     printf("Exiting calandcheckages: ");
                   8446:     return (1);
                   8447: }
                   8448: 
1.172     brouard  8449: #if defined(_MSC_VER)
                   8450: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   8451: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   8452: //#include "stdafx.h"
                   8453: //#include <stdio.h>
                   8454: //#include <tchar.h>
                   8455: //#include <windows.h>
                   8456: //#include <iostream>
                   8457: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   8458: 
                   8459: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   8460: 
                   8461: BOOL IsWow64()
                   8462: {
                   8463:        BOOL bIsWow64 = FALSE;
                   8464: 
                   8465:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   8466:        //  (HANDLE, PBOOL);
                   8467: 
                   8468:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   8469: 
                   8470:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   8471:        const char funcName[] = "IsWow64Process";
                   8472:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   8473:                GetProcAddress(module, funcName);
                   8474: 
                   8475:        if (NULL != fnIsWow64Process)
                   8476:        {
                   8477:                if (!fnIsWow64Process(GetCurrentProcess(),
                   8478:                        &bIsWow64))
                   8479:                        //throw std::exception("Unknown error");
                   8480:                        printf("Unknown error\n");
                   8481:        }
                   8482:        return bIsWow64 != FALSE;
                   8483: }
                   8484: #endif
1.177     brouard  8485: 
1.191     brouard  8486: void syscompilerinfo(int logged)
1.167     brouard  8487:  {
                   8488:    /* #include "syscompilerinfo.h"*/
1.185     brouard  8489:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   8490:    /* /GS /W3 /Gy
                   8491:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   8492:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   8493:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  8494:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   8495:    */ 
                   8496:    /* 64 bits */
1.185     brouard  8497:    /*
                   8498:      /GS /W3 /Gy
                   8499:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   8500:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   8501:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   8502:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   8503:    /* Optimization are useless and O3 is slower than O2 */
                   8504:    /*
                   8505:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   8506:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   8507:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   8508:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   8509:    */
1.186     brouard  8510:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  8511:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   8512:       /PDB:"visual studio
                   8513:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   8514:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   8515:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   8516:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   8517:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   8518:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   8519:       uiAccess='false'"
                   8520:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   8521:       /NOLOGO /TLBID:1
                   8522:    */
1.177     brouard  8523: #if defined __INTEL_COMPILER
1.178     brouard  8524: #if defined(__GNUC__)
                   8525:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   8526: #endif
1.177     brouard  8527: #elif defined(__GNUC__) 
1.179     brouard  8528: #ifndef  __APPLE__
1.174     brouard  8529: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  8530: #endif
1.177     brouard  8531:    struct utsname sysInfo;
1.178     brouard  8532:    int cross = CROSS;
                   8533:    if (cross){
                   8534:           printf("Cross-");
1.191     brouard  8535:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  8536:    }
1.174     brouard  8537: #endif
                   8538: 
1.171     brouard  8539: #include <stdint.h>
1.178     brouard  8540: 
1.191     brouard  8541:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  8542: #if defined(__clang__)
1.191     brouard  8543:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  8544: #endif
                   8545: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  8546:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  8547: #endif
                   8548: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  8549:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  8550: #endif
                   8551: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  8552:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  8553: #endif
                   8554: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  8555:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  8556: #endif
                   8557: #if defined(_MSC_VER)
1.191     brouard  8558:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  8559: #endif
                   8560: #if defined(__PGI)
1.191     brouard  8561:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  8562: #endif
                   8563: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  8564:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  8565: #endif
1.191     brouard  8566:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  8567:    
1.167     brouard  8568: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   8569: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   8570:     // Windows (x64 and x86)
1.191     brouard  8571:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  8572: #elif __unix__ // all unices, not all compilers
                   8573:     // Unix
1.191     brouard  8574:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  8575: #elif __linux__
                   8576:     // linux
1.191     brouard  8577:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  8578: #elif __APPLE__
1.174     brouard  8579:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  8580:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  8581: #endif
                   8582: 
                   8583: /*  __MINGW32__          */
                   8584: /*  __CYGWIN__  */
                   8585: /* __MINGW64__  */
                   8586: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   8587: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   8588: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   8589: /* _WIN64  // Defined for applications for Win64. */
                   8590: /* _M_X64 // Defined for compilations that target x64 processors. */
                   8591: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  8592: 
1.167     brouard  8593: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  8594:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  8595: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  8596:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  8597: #else
1.191     brouard  8598:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  8599: #endif
                   8600: 
1.169     brouard  8601: #if defined(__GNUC__)
                   8602: # if defined(__GNUC_PATCHLEVEL__)
                   8603: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   8604:                             + __GNUC_MINOR__ * 100 \
                   8605:                             + __GNUC_PATCHLEVEL__)
                   8606: # else
                   8607: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   8608:                             + __GNUC_MINOR__ * 100)
                   8609: # endif
1.174     brouard  8610:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  8611:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  8612: 
                   8613:    if (uname(&sysInfo) != -1) {
                   8614:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  8615:         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  8616:    }
                   8617:    else
                   8618:       perror("uname() error");
1.179     brouard  8619:    //#ifndef __INTEL_COMPILER 
                   8620: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  8621:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  8622:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  8623: #endif
1.169     brouard  8624: #endif
1.172     brouard  8625: 
                   8626:    //   void main()
                   8627:    //   {
1.169     brouard  8628: #if defined(_MSC_VER)
1.174     brouard  8629:    if (IsWow64()){
1.191     brouard  8630:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   8631:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  8632:    }
                   8633:    else{
1.191     brouard  8634:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   8635:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  8636:    }
1.172     brouard  8637:    //     printf("\nPress Enter to continue...");
                   8638:    //     getchar();
                   8639:    //   }
                   8640: 
1.169     brouard  8641: #endif
                   8642:    
1.167     brouard  8643: 
1.219     brouard  8644: }
1.136     brouard  8645: 
1.219     brouard  8646: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.180     brouard  8647:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
                   8648:   int i, j, k, i1 ;
1.202     brouard  8649:   /* double ftolpl = 1.e-10; */
1.180     brouard  8650:   double age, agebase, agelim;
1.203     brouard  8651:   double tot;
1.180     brouard  8652: 
1.202     brouard  8653:   strcpy(filerespl,"PL_");
                   8654:   strcat(filerespl,fileresu);
                   8655:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
                   8656:     printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   8657:     fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   8658:   }
1.227     brouard  8659:   printf("\nComputing period (stable) prevalence: result on file '%s' \n", filerespl);
                   8660:   fprintf(ficlog,"\nComputing period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  8661:   pstamp(ficrespl);
1.203     brouard  8662:   fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  8663:   fprintf(ficrespl,"#Age ");
                   8664:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   8665:   fprintf(ficrespl,"\n");
1.180     brouard  8666:   
1.219     brouard  8667:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  8668: 
1.219     brouard  8669:   agebase=ageminpar;
                   8670:   agelim=agemaxpar;
1.180     brouard  8671: 
1.227     brouard  8672:   /* i1=pow(2,ncoveff); */
                   8673:   i1=pow(2,cptcoveff); /* Number of dummy covariates */
1.219     brouard  8674:   if (cptcovn < 1){i1=1;}
1.180     brouard  8675: 
1.220     brouard  8676:   for(k=1; k<=i1;k++){
                   8677:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
1.180     brouard  8678:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
1.219     brouard  8679:     //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
1.220     brouard  8680:     /* k=k+1; */
1.219     brouard  8681:     /* to clean */
                   8682:     //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   8683:     fprintf(ficrespl,"#******");
                   8684:     printf("#******");
                   8685:     fprintf(ficlog,"#******");
1.227     brouard  8686:     for(j=1;j<=cptcoveff ;j++) {/* all covariates */
                   8687:       fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); /* Here problem for varying dummy*/
1.219     brouard  8688:       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8689:       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8690:     }
                   8691:     fprintf(ficrespl,"******\n");
                   8692:     printf("******\n");
                   8693:     fprintf(ficlog,"******\n");
1.227     brouard  8694:     if(invalidvarcomb[k]){
                   8695:       printf("\nCombination (%d) ignored because no case \n",k); 
                   8696:       fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   8697:       fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
1.220     brouard  8698:                                                continue;
1.227     brouard  8699:     }
1.219     brouard  8700: 
                   8701:     fprintf(ficrespl,"#Age ");
1.227     brouard  8702:     for(j=1;j<=cptcoveff;j++) {
1.219     brouard  8703:       fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8704:     }
                   8705:     for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   8706:     fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  8707:     
1.219     brouard  8708:     for (age=agebase; age<=agelim; age++){
                   8709:       /* for (age=agebase; age<=agebase; age++){ */
                   8710:       prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k);
                   8711:       fprintf(ficrespl,"%.0f ",age );
1.227     brouard  8712:       for(j=1;j<=cptcoveff;j++)
                   8713:        fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.219     brouard  8714:       tot=0.;
                   8715:       for(i=1; i<=nlstate;i++){
1.227     brouard  8716:        tot +=  prlim[i][i];
                   8717:        fprintf(ficrespl," %.5f", prlim[i][i]);
1.219     brouard  8718:       }
                   8719:       fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   8720:     } /* Age */
                   8721:     /* was end of cptcod */
                   8722:   } /* cptcov */
                   8723:   return 0;
1.180     brouard  8724: }
                   8725: 
1.218     brouard  8726: 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){
                   8727:        /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   8728:        
                   8729:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   8730:    * at any age between ageminpar and agemaxpar
                   8731:         */
1.217     brouard  8732:   int i, j, k, i1 ;
                   8733:   /* double ftolpl = 1.e-10; */
                   8734:   double age, agebase, agelim;
                   8735:   double tot;
1.218     brouard  8736:   /* double ***mobaverage; */
                   8737:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  8738: 
                   8739:   strcpy(fileresplb,"PLB_");
                   8740:   strcat(fileresplb,fileresu);
                   8741:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
                   8742:     printf("Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
                   8743:     fprintf(ficlog,"Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
                   8744:   }
                   8745:   printf("Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
                   8746:   fprintf(ficlog,"Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
                   8747:   pstamp(ficresplb);
                   8748:   fprintf(ficresplb,"# Period (stable) back prevalence. Precision given by ftolpl=%g \n", ftolpl);
                   8749:   fprintf(ficresplb,"#Age ");
                   8750:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   8751:   fprintf(ficresplb,"\n");
                   8752:   
1.218     brouard  8753:   
                   8754:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   8755:   
                   8756:   agebase=ageminpar;
                   8757:   agelim=agemaxpar;
                   8758:   
                   8759:   
1.227     brouard  8760:   i1=pow(2,cptcoveff);
1.218     brouard  8761:   if (cptcovn < 1){i1=1;}
1.227     brouard  8762:   
                   8763:   for(k=1; k<=i1;k++){ 
1.218     brouard  8764:     //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   8765:     fprintf(ficresplb,"#******");
                   8766:     printf("#******");
                   8767:     fprintf(ficlog,"#******");
1.227     brouard  8768:     for(j=1;j<=cptcoveff ;j++) {/* all covariates */
1.218     brouard  8769:       fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8770:       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8771:       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8772:     }
                   8773:     fprintf(ficresplb,"******\n");
                   8774:     printf("******\n");
                   8775:     fprintf(ficlog,"******\n");
1.227     brouard  8776:     if(invalidvarcomb[k]){
                   8777:       printf("\nCombination (%d) ignored because no cases \n",k); 
                   8778:       fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   8779:       fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   8780:       continue;
                   8781:     }
1.218     brouard  8782:     
                   8783:     fprintf(ficresplb,"#Age ");
1.227     brouard  8784:     for(j=1;j<=cptcoveff;j++) {
1.218     brouard  8785:       fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8786:     }
                   8787:     for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   8788:     fprintf(ficresplb,"Total Years_to_converge\n");
                   8789:     
                   8790:     
                   8791:     for (age=agebase; age<=agelim; age++){
                   8792:       /* for (age=agebase; age<=agebase; age++){ */
                   8793:       if(mobilavproj > 0){
                   8794:        /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   8795:        /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.227     brouard  8796:        bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k);
1.218     brouard  8797:       }else if (mobilavproj == 0){
1.227     brouard  8798:        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);
                   8799:        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);
                   8800:        exit(1);
1.218     brouard  8801:       }else{
1.227     brouard  8802:        /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   8803:        bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k);
1.218     brouard  8804:       }
                   8805:       fprintf(ficresplb,"%.0f ",age );
1.227     brouard  8806:       for(j=1;j<=cptcoveff;j++)
                   8807:        fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.218     brouard  8808:       tot=0.;
                   8809:       for(i=1; i<=nlstate;i++){
1.227     brouard  8810:        tot +=  bprlim[i][i];
                   8811:        fprintf(ficresplb," %.5f", bprlim[i][i]);
1.218     brouard  8812:       }
                   8813:       fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   8814:     } /* Age */
                   8815:     /* was end of cptcod */
                   8816:   } /* cptcov */
                   8817:   
                   8818:   /* hBijx(p, bage, fage); */
                   8819:   /* fclose(ficrespijb); */
                   8820:   
                   8821:   return 0;
1.217     brouard  8822: }
1.218     brouard  8823:  
1.180     brouard  8824: int hPijx(double *p, int bage, int fage){
                   8825:     /*------------- h Pij x at various ages ------------*/
                   8826: 
                   8827:   int stepsize;
                   8828:   int agelim;
                   8829:   int hstepm;
                   8830:   int nhstepm;
                   8831:   int h, i, i1, j, k;
                   8832: 
                   8833:   double agedeb;
                   8834:   double ***p3mat;
                   8835: 
1.201     brouard  8836:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  8837:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   8838:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   8839:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   8840:     }
                   8841:     printf("Computing pij: result on file '%s' \n", filerespij);
                   8842:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   8843:   
                   8844:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   8845:     /*if (stepm<=24) stepsize=2;*/
                   8846: 
                   8847:     agelim=AGESUP;
                   8848:     hstepm=stepsize*YEARM; /* Every year of age */
                   8849:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
1.218     brouard  8850:                
1.180     brouard  8851:     /* hstepm=1;   aff par mois*/
                   8852:     pstamp(ficrespij);
                   8853:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
1.227     brouard  8854:     i1= pow(2,cptcoveff);
1.218     brouard  8855:                /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   8856:                /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   8857:                /*      k=k+1;  */
1.227     brouard  8858:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.183     brouard  8859:       fprintf(ficrespij,"\n#****** ");
1.227     brouard  8860:       for(j=1;j<=cptcoveff;j++) 
1.198     brouard  8861:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.183     brouard  8862:       fprintf(ficrespij,"******\n");
                   8863:       
                   8864:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   8865:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   8866:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   8867:        
                   8868:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  8869:        
1.183     brouard  8870:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8871:        oldm=oldms;savm=savms;
                   8872:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   8873:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   8874:        for(i=1; i<=nlstate;i++)
                   8875:          for(j=1; j<=nlstate+ndeath;j++)
                   8876:            fprintf(ficrespij," %1d-%1d",i,j);
                   8877:        fprintf(ficrespij,"\n");
                   8878:        for (h=0; h<=nhstepm; h++){
                   8879:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   8880:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  8881:          for(i=1; i<=nlstate;i++)
                   8882:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  8883:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  8884:          fprintf(ficrespij,"\n");
                   8885:        }
1.183     brouard  8886:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8887:        fprintf(ficrespij,"\n");
                   8888:       }
1.180     brouard  8889:       /*}*/
                   8890:     }
1.218     brouard  8891:     return 0;
1.180     brouard  8892: }
1.218     brouard  8893:  
                   8894:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  8895:     /*------------- h Bij x at various ages ------------*/
                   8896: 
                   8897:   int stepsize;
1.218     brouard  8898:   /* int agelim; */
                   8899:        int ageminl;
1.217     brouard  8900:   int hstepm;
                   8901:   int nhstepm;
                   8902:   int h, i, i1, j, k;
1.218     brouard  8903:        
1.217     brouard  8904:   double agedeb;
                   8905:   double ***p3mat;
1.218     brouard  8906:        
                   8907:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   8908:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   8909:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   8910:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   8911:   }
                   8912:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   8913:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   8914:   
                   8915:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   8916:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  8917:   
1.218     brouard  8918:   /* agelim=AGESUP; */
                   8919:   ageminl=30;
                   8920:   hstepm=stepsize*YEARM; /* Every year of age */
                   8921:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   8922:   
                   8923:   /* hstepm=1;   aff par mois*/
                   8924:   pstamp(ficrespijb);
                   8925:   fprintf(ficrespijb,"#****** h Pij x Back Probability to be in state i at age x-h being in j at x ");
1.227     brouard  8926:   i1= pow(2,cptcoveff);
1.218     brouard  8927:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   8928:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   8929:   /*   k=k+1;  */
1.227     brouard  8930:   for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.218     brouard  8931:     fprintf(ficrespijb,"\n#****** ");
1.227     brouard  8932:     for(j=1;j<=cptcoveff;j++)
1.218     brouard  8933:       fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8934:     fprintf(ficrespijb,"******\n");
1.222     brouard  8935:     if(invalidvarcomb[k]){
                   8936:       fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   8937:       continue;
                   8938:     }
1.218     brouard  8939:     
                   8940:     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   8941:     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   8942:       /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   8943:       nhstepm=(int) rint((agedeb-ageminl)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
                   8944:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 */
                   8945:       
                   8946:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   8947:       
                   8948:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8949:       /* oldm=oldms;savm=savms; */
                   8950:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   8951:       hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k);
                   8952:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
                   8953:       fprintf(ficrespijb,"# Cov Agex agex-h hpijx with i,j=");
                   8954:       for(i=1; i<=nlstate;i++)
                   8955:        for(j=1; j<=nlstate+ndeath;j++)
                   8956:          fprintf(ficrespijb," %1d-%1d",i,j);
                   8957:       fprintf(ficrespijb,"\n");
                   8958:       for (h=0; h<=nhstepm; h++){
                   8959:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   8960:        fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   8961:        /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
1.217     brouard  8962:        for(i=1; i<=nlstate;i++)
                   8963:          for(j=1; j<=nlstate+ndeath;j++)
1.218     brouard  8964:            fprintf(ficrespijb," %.5f", p3mat[i][j][h]);
1.217     brouard  8965:        fprintf(ficrespijb,"\n");
                   8966:       }
1.218     brouard  8967:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8968:       fprintf(ficrespijb,"\n");
1.217     brouard  8969:     }
1.218     brouard  8970:     /*}*/
                   8971:   }
                   8972:   return 0;
                   8973:  } /*  hBijx */
1.217     brouard  8974: 
1.180     brouard  8975: 
1.136     brouard  8976: /***********************************************/
                   8977: /**************** Main Program *****************/
                   8978: /***********************************************/
                   8979: 
                   8980: int main(int argc, char *argv[])
                   8981: {
                   8982: #ifdef GSL
                   8983:   const gsl_multimin_fminimizer_type *T;
                   8984:   size_t iteri = 0, it;
                   8985:   int rval = GSL_CONTINUE;
                   8986:   int status = GSL_SUCCESS;
                   8987:   double ssval;
                   8988: #endif
                   8989:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164     brouard  8990:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
1.209     brouard  8991:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  8992:   int jj, ll, li, lj, lk;
1.136     brouard  8993:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  8994:   int num_filled;
1.136     brouard  8995:   int itimes;
                   8996:   int NDIM=2;
                   8997:   int vpopbased=0;
                   8998: 
1.164     brouard  8999:   char ca[32], cb[32];
1.136     brouard  9000:   /*  FILE *fichtm; *//* Html File */
                   9001:   /* FILE *ficgp;*/ /*Gnuplot File */
                   9002:   struct stat info;
1.191     brouard  9003:   double agedeb=0.;
1.194     brouard  9004: 
                   9005:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  9006:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  9007: 
1.165     brouard  9008:   double fret;
1.191     brouard  9009:   double dum=0.; /* Dummy variable */
1.136     brouard  9010:   double ***p3mat;
1.218     brouard  9011:   /* double ***mobaverage; */
1.164     brouard  9012: 
                   9013:   char line[MAXLINE];
1.197     brouard  9014:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   9015: 
                   9016:   char model[MAXLINE], modeltemp[MAXLINE];
1.230     brouard  9017:   char resultline[MAXLINE];
                   9018:   
1.136     brouard  9019:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  9020:   char *tok, *val; /* pathtot */
1.136     brouard  9021:   int firstobs=1, lastobs=10;
1.195     brouard  9022:   int c,  h , cpt, c2;
1.191     brouard  9023:   int jl=0;
                   9024:   int i1, j1, jk, stepsize=0;
1.194     brouard  9025:   int count=0;
                   9026: 
1.164     brouard  9027:   int *tab; 
1.136     brouard  9028:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.217     brouard  9029:   int backcast=0;
1.136     brouard  9030:   int mobilav=0,popforecast=0;
1.191     brouard  9031:   int hstepm=0, nhstepm=0;
1.136     brouard  9032:   int agemortsup;
                   9033:   float  sumlpop=0.;
                   9034:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   9035:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   9036: 
1.191     brouard  9037:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  9038:   double ftolpl=FTOL;
                   9039:   double **prlim;
1.217     brouard  9040:   double **bprlim;
1.136     brouard  9041:   double ***param; /* Matrix of parameters */
                   9042:   double  *p;
                   9043:   double **matcov; /* Matrix of covariance */
1.203     brouard  9044:   double **hess; /* Hessian matrix */
1.136     brouard  9045:   double ***delti3; /* Scale */
                   9046:   double *delti; /* Scale */
                   9047:   double ***eij, ***vareij;
                   9048:   double **varpl; /* Variances of prevalence limits by age */
                   9049:   double *epj, vepp;
1.164     brouard  9050: 
1.136     brouard  9051:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
1.217     brouard  9052:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000;
                   9053: 
1.136     brouard  9054:   double **ximort;
1.145     brouard  9055:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  9056:   int *dcwave;
                   9057: 
1.164     brouard  9058:   char z[1]="c";
1.136     brouard  9059: 
                   9060:   /*char  *strt;*/
                   9061:   char strtend[80];
1.126     brouard  9062: 
1.164     brouard  9063: 
1.126     brouard  9064: /*   setlocale (LC_ALL, ""); */
                   9065: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   9066: /*   textdomain (PACKAGE); */
                   9067: /*   setlocale (LC_CTYPE, ""); */
                   9068: /*   setlocale (LC_MESSAGES, ""); */
                   9069: 
                   9070:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  9071:   rstart_time = time(NULL);  
                   9072:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   9073:   start_time = *localtime(&rstart_time);
1.126     brouard  9074:   curr_time=start_time;
1.157     brouard  9075:   /*tml = *localtime(&start_time.tm_sec);*/
                   9076:   /* strcpy(strstart,asctime(&tml)); */
                   9077:   strcpy(strstart,asctime(&start_time));
1.126     brouard  9078: 
                   9079: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  9080: /*  tp.tm_sec = tp.tm_sec +86400; */
                   9081: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  9082: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   9083: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   9084: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  9085: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  9086: /*   strt=asctime(&tmg); */
                   9087: /*   printf("Time(after) =%s",strstart);  */
                   9088: /*  (void) time (&time_value);
                   9089: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   9090: *  tm = *localtime(&time_value);
                   9091: *  strstart=asctime(&tm);
                   9092: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   9093: */
                   9094: 
                   9095:   nberr=0; /* Number of errors and warnings */
                   9096:   nbwarn=0;
1.184     brouard  9097: #ifdef WIN32
                   9098:   _getcwd(pathcd, size);
                   9099: #else
1.126     brouard  9100:   getcwd(pathcd, size);
1.184     brouard  9101: #endif
1.191     brouard  9102:   syscompilerinfo(0);
1.196     brouard  9103:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  9104:   if(argc <=1){
                   9105:     printf("\nEnter the parameter file name: ");
1.205     brouard  9106:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   9107:       printf("ERROR Empty parameter file name\n");
                   9108:       goto end;
                   9109:     }
1.126     brouard  9110:     i=strlen(pathr);
                   9111:     if(pathr[i-1]=='\n')
                   9112:       pathr[i-1]='\0';
1.156     brouard  9113:     i=strlen(pathr);
1.205     brouard  9114:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  9115:       pathr[i-1]='\0';
1.205     brouard  9116:     }
                   9117:     i=strlen(pathr);
                   9118:     if( i==0 ){
                   9119:       printf("ERROR Empty parameter file name\n");
                   9120:       goto end;
                   9121:     }
                   9122:     for (tok = pathr; tok != NULL; ){
1.126     brouard  9123:       printf("Pathr |%s|\n",pathr);
                   9124:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   9125:       printf("val= |%s| pathr=%s\n",val,pathr);
                   9126:       strcpy (pathtot, val);
                   9127:       if(pathr[0] == '\0') break; /* Dirty */
                   9128:     }
                   9129:   }
                   9130:   else{
                   9131:     strcpy(pathtot,argv[1]);
                   9132:   }
                   9133:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   9134:   /*cygwin_split_path(pathtot,path,optionfile);
                   9135:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   9136:   /* cutv(path,optionfile,pathtot,'\\');*/
                   9137: 
                   9138:   /* Split argv[0], imach program to get pathimach */
                   9139:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   9140:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   9141:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   9142:  /*   strcpy(pathimach,argv[0]); */
                   9143:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   9144:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   9145:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  9146: #ifdef WIN32
                   9147:   _chdir(path); /* Can be a relative path */
                   9148:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   9149: #else
1.126     brouard  9150:   chdir(path); /* Can be a relative path */
1.184     brouard  9151:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   9152: #endif
                   9153:   printf("Current directory %s!\n",pathcd);
1.126     brouard  9154:   strcpy(command,"mkdir ");
                   9155:   strcat(command,optionfilefiname);
                   9156:   if((outcmd=system(command)) != 0){
1.169     brouard  9157:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  9158:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   9159:     /* fclose(ficlog); */
                   9160: /*     exit(1); */
                   9161:   }
                   9162: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   9163: /*     perror("mkdir"); */
                   9164: /*   } */
                   9165: 
                   9166:   /*-------- arguments in the command line --------*/
                   9167: 
1.186     brouard  9168:   /* Main Log file */
1.126     brouard  9169:   strcat(filelog, optionfilefiname);
                   9170:   strcat(filelog,".log");    /* */
                   9171:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   9172:     printf("Problem with logfile %s\n",filelog);
                   9173:     goto end;
                   9174:   }
                   9175:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  9176:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  9177:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   9178:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   9179:  path=%s \n\
                   9180:  optionfile=%s\n\
                   9181:  optionfilext=%s\n\
1.156     brouard  9182:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  9183: 
1.197     brouard  9184:   syscompilerinfo(1);
1.167     brouard  9185: 
1.126     brouard  9186:   printf("Local time (at start):%s",strstart);
                   9187:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   9188:   fflush(ficlog);
                   9189: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  9190: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  9191: 
                   9192:   /* */
                   9193:   strcpy(fileres,"r");
                   9194:   strcat(fileres, optionfilefiname);
1.201     brouard  9195:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  9196:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  9197:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  9198: 
1.186     brouard  9199:   /* Main ---------arguments file --------*/
1.126     brouard  9200: 
                   9201:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  9202:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   9203:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  9204:     fflush(ficlog);
1.149     brouard  9205:     /* goto end; */
                   9206:     exit(70); 
1.126     brouard  9207:   }
                   9208: 
                   9209: 
                   9210: 
                   9211:   strcpy(filereso,"o");
1.201     brouard  9212:   strcat(filereso,fileresu);
1.126     brouard  9213:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   9214:     printf("Problem with Output resultfile: %s\n", filereso);
                   9215:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   9216:     fflush(ficlog);
                   9217:     goto end;
                   9218:   }
                   9219: 
                   9220:   /* Reads comments: lines beginning with '#' */
                   9221:   numlinepar=0;
1.197     brouard  9222: 
                   9223:     /* First parameter line */
                   9224:   while(fgets(line, MAXLINE, ficpar)) {
                   9225:     /* If line starts with a # it is a comment */
                   9226:     if (line[0] == '#') {
                   9227:       numlinepar++;
                   9228:       fputs(line,stdout);
                   9229:       fputs(line,ficparo);
                   9230:       fputs(line,ficlog);
                   9231:       continue;
                   9232:     }else
                   9233:       break;
                   9234:   }
                   9235:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   9236:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   9237:     if (num_filled != 5) {
                   9238:       printf("Should be 5 parameters\n");
                   9239:     }
1.126     brouard  9240:     numlinepar++;
1.197     brouard  9241:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   9242:   }
                   9243:   /* Second parameter line */
                   9244:   while(fgets(line, MAXLINE, ficpar)) {
                   9245:     /* If line starts with a # it is a comment */
                   9246:     if (line[0] == '#') {
                   9247:       numlinepar++;
                   9248:       fputs(line,stdout);
                   9249:       fputs(line,ficparo);
                   9250:       fputs(line,ficlog);
                   9251:       continue;
                   9252:     }else
                   9253:       break;
                   9254:   }
1.223     brouard  9255:   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", \
                   9256:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   9257:     if (num_filled != 11) {
                   9258:       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  9259:       printf("but line=%s\n",line);
1.197     brouard  9260:     }
1.223     brouard  9261:     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  9262:   }
1.203     brouard  9263:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  9264:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  9265:   /* Third parameter line */
                   9266:   while(fgets(line, MAXLINE, ficpar)) {
                   9267:     /* If line starts with a # it is a comment */
                   9268:     if (line[0] == '#') {
                   9269:       numlinepar++;
                   9270:       fputs(line,stdout);
                   9271:       fputs(line,ficparo);
                   9272:       fputs(line,ficlog);
                   9273:       continue;
                   9274:     }else
                   9275:       break;
                   9276:   }
1.201     brouard  9277:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
                   9278:     if (num_filled == 0)
                   9279:             model[0]='\0';
                   9280:     else if (num_filled != 1){
1.197     brouard  9281:       printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   9282:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   9283:       model[0]='\0';
                   9284:       goto end;
                   9285:     }
                   9286:     else{
                   9287:       if (model[0]=='+'){
                   9288:        for(i=1; i<=strlen(model);i++)
                   9289:          modeltemp[i-1]=model[i];
1.201     brouard  9290:        strcpy(model,modeltemp); 
1.197     brouard  9291:       }
                   9292:     }
1.199     brouard  9293:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  9294:     printf("model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  9295:   }
                   9296:   /* 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); */
                   9297:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   9298:   /* 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  9299:   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);
                   9300:   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  9301:   fflush(ficlog);
1.190     brouard  9302:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   9303:   if(model[0]=='#'){
1.187     brouard  9304:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
                   9305:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
                   9306:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");         \
                   9307:     if(mle != -1){
                   9308:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
                   9309:       exit(1);
                   9310:     }
                   9311:   }
1.126     brouard  9312:   while((c=getc(ficpar))=='#' && c!= EOF){
                   9313:     ungetc(c,ficpar);
                   9314:     fgets(line, MAXLINE, ficpar);
                   9315:     numlinepar++;
1.195     brouard  9316:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   9317:       z[0]=line[1];
                   9318:     }
                   9319:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  9320:     fputs(line, stdout);
                   9321:     //puts(line);
1.126     brouard  9322:     fputs(line,ficparo);
                   9323:     fputs(line,ficlog);
                   9324:   }
                   9325:   ungetc(c,ficpar);
                   9326: 
                   9327:    
1.145     brouard  9328:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
1.225     brouard  9329:   coqvar=matrix(1,nqv,1,n);  /**< Fixed quantitative covariate */
                   9330:   cotvar=ma3x(1,maxwav,1,ntv,1,n);  /**< Time varying covariate */
                   9331:   cotqvar=ma3x(1,maxwav,1,nqtv,1,n);  /**< Time varying quantitative covariate */
1.136     brouard  9332:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   9333:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   9334:      v1+v2*age+v2*v3 makes cptcovn = 3
                   9335:   */
                   9336:   if (strlen(model)>1) 
1.187     brouard  9337:     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  9338:   else
1.187     brouard  9339:     ncovmodel=2; /* Constant and age */
1.133     brouard  9340:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   9341:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  9342:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   9343:     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);
                   9344:     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);
                   9345:     fflush(stdout);
                   9346:     fclose (ficlog);
                   9347:     goto end;
                   9348:   }
1.126     brouard  9349:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   9350:   delti=delti3[1][1];
                   9351:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   9352:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   9353:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  9354:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   9355:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  9356:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   9357:     fclose (ficparo);
                   9358:     fclose (ficlog);
                   9359:     goto end;
                   9360:     exit(0);
1.220     brouard  9361:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  9362:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  9363:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   9364:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  9365:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   9366:     matcov=matrix(1,npar,1,npar);
1.203     brouard  9367:     hess=matrix(1,npar,1,npar);
1.220     brouard  9368:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  9369:     /* Read guessed parameters */
1.126     brouard  9370:     /* Reads comments: lines beginning with '#' */
                   9371:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9372:       ungetc(c,ficpar);
                   9373:       fgets(line, MAXLINE, ficpar);
                   9374:       numlinepar++;
1.141     brouard  9375:       fputs(line,stdout);
1.126     brouard  9376:       fputs(line,ficparo);
                   9377:       fputs(line,ficlog);
                   9378:     }
                   9379:     ungetc(c,ficpar);
                   9380:     
                   9381:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   9382:     for(i=1; i <=nlstate; i++){
1.220     brouard  9383:                        j=0;
1.126     brouard  9384:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.220     brouard  9385:                                if(jj==i) continue;
                   9386:                                j++;
                   9387:                                fscanf(ficpar,"%1d%1d",&i1,&j1);
                   9388:                                if ((i1 != i) || (j1 != jj)){
                   9389:                                        printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  9390: It might be a problem of design; if ncovcol and the model are correct\n \
                   9391: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.220     brouard  9392:                                        exit(1);
                   9393:                                }
                   9394:                                fprintf(ficparo,"%1d%1d",i1,j1);
                   9395:                                if(mle==1)
                   9396:                                        printf("%1d%1d",i,jj);
                   9397:                                fprintf(ficlog,"%1d%1d",i,jj);
                   9398:                                for(k=1; k<=ncovmodel;k++){
                   9399:                                        fscanf(ficpar," %lf",&param[i][j][k]);
                   9400:                                        if(mle==1){
                   9401:                                                printf(" %lf",param[i][j][k]);
                   9402:                                                fprintf(ficlog," %lf",param[i][j][k]);
                   9403:                                        }
                   9404:                                        else
                   9405:                                                fprintf(ficlog," %lf",param[i][j][k]);
                   9406:                                        fprintf(ficparo," %lf",param[i][j][k]);
                   9407:                                }
                   9408:                                fscanf(ficpar,"\n");
                   9409:                                numlinepar++;
                   9410:                                if(mle==1)
                   9411:                                        printf("\n");
                   9412:                                fprintf(ficlog,"\n");
                   9413:                                fprintf(ficparo,"\n");
1.126     brouard  9414:       }
                   9415:     }  
                   9416:     fflush(ficlog);
                   9417: 
1.145     brouard  9418:     /* Reads scales values */
1.126     brouard  9419:     p=param[1][1];
                   9420:     
                   9421:     /* Reads comments: lines beginning with '#' */
                   9422:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9423:       ungetc(c,ficpar);
                   9424:       fgets(line, MAXLINE, ficpar);
                   9425:       numlinepar++;
1.141     brouard  9426:       fputs(line,stdout);
1.126     brouard  9427:       fputs(line,ficparo);
                   9428:       fputs(line,ficlog);
                   9429:     }
                   9430:     ungetc(c,ficpar);
                   9431: 
                   9432:     for(i=1; i <=nlstate; i++){
                   9433:       for(j=1; j <=nlstate+ndeath-1; j++){
1.220     brouard  9434:                                fscanf(ficpar,"%1d%1d",&i1,&j1);
                   9435:                                if ( (i1-i) * (j1-j) != 0){
                   9436:                                        printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   9437:                                        exit(1);
                   9438:                                }
                   9439:                                printf("%1d%1d",i,j);
                   9440:                                fprintf(ficparo,"%1d%1d",i1,j1);
                   9441:                                fprintf(ficlog,"%1d%1d",i1,j1);
                   9442:                                for(k=1; k<=ncovmodel;k++){
                   9443:                                        fscanf(ficpar,"%le",&delti3[i][j][k]);
                   9444:                                        printf(" %le",delti3[i][j][k]);
                   9445:                                        fprintf(ficparo," %le",delti3[i][j][k]);
                   9446:                                        fprintf(ficlog," %le",delti3[i][j][k]);
                   9447:                                }
                   9448:                                fscanf(ficpar,"\n");
                   9449:                                numlinepar++;
                   9450:                                printf("\n");
                   9451:                                fprintf(ficparo,"\n");
                   9452:                                fprintf(ficlog,"\n");
1.126     brouard  9453:       }
                   9454:     }
                   9455:     fflush(ficlog);
1.220     brouard  9456:                
1.145     brouard  9457:     /* Reads covariance matrix */
1.126     brouard  9458:     delti=delti3[1][1];
1.220     brouard  9459:                
                   9460:                
1.126     brouard  9461:     /* 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  9462:                
1.126     brouard  9463:     /* Reads comments: lines beginning with '#' */
                   9464:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9465:       ungetc(c,ficpar);
                   9466:       fgets(line, MAXLINE, ficpar);
                   9467:       numlinepar++;
1.141     brouard  9468:       fputs(line,stdout);
1.126     brouard  9469:       fputs(line,ficparo);
                   9470:       fputs(line,ficlog);
                   9471:     }
                   9472:     ungetc(c,ficpar);
1.220     brouard  9473:                
1.126     brouard  9474:     matcov=matrix(1,npar,1,npar);
1.203     brouard  9475:     hess=matrix(1,npar,1,npar);
1.131     brouard  9476:     for(i=1; i <=npar; i++)
                   9477:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  9478:                
1.194     brouard  9479:     /* Scans npar lines */
1.126     brouard  9480:     for(i=1; i <=npar; i++){
1.226     brouard  9481:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  9482:       if(count != 3){
1.226     brouard  9483:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  9484: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   9485: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  9486:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  9487: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   9488: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  9489:        exit(1);
1.220     brouard  9490:       }else{
1.226     brouard  9491:        if(mle==1)
                   9492:          printf("%1d%1d%d",i1,j1,jk);
                   9493:       }
                   9494:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   9495:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  9496:       for(j=1; j <=i; j++){
1.226     brouard  9497:        fscanf(ficpar," %le",&matcov[i][j]);
                   9498:        if(mle==1){
                   9499:          printf(" %.5le",matcov[i][j]);
                   9500:        }
                   9501:        fprintf(ficlog," %.5le",matcov[i][j]);
                   9502:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  9503:       }
                   9504:       fscanf(ficpar,"\n");
                   9505:       numlinepar++;
                   9506:       if(mle==1)
1.220     brouard  9507:                                printf("\n");
1.126     brouard  9508:       fprintf(ficlog,"\n");
                   9509:       fprintf(ficparo,"\n");
                   9510:     }
1.194     brouard  9511:     /* End of read covariance matrix npar lines */
1.126     brouard  9512:     for(i=1; i <=npar; i++)
                   9513:       for(j=i+1;j<=npar;j++)
1.226     brouard  9514:        matcov[i][j]=matcov[j][i];
1.126     brouard  9515:     
                   9516:     if(mle==1)
                   9517:       printf("\n");
                   9518:     fprintf(ficlog,"\n");
                   9519:     
                   9520:     fflush(ficlog);
                   9521:     
                   9522:     /*-------- Rewriting parameter file ----------*/
                   9523:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   9524:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   9525:     strcat(rfileres,".");    /* */
                   9526:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   9527:     if((ficres =fopen(rfileres,"w"))==NULL) {
1.201     brouard  9528:       printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   9529:       fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
1.126     brouard  9530:     }
                   9531:     fprintf(ficres,"#%s\n",version);
                   9532:   }    /* End of mle != -3 */
1.218     brouard  9533:   
1.186     brouard  9534:   /*  Main data
                   9535:    */
1.126     brouard  9536:   n= lastobs;
                   9537:   num=lvector(1,n);
                   9538:   moisnais=vector(1,n);
                   9539:   annais=vector(1,n);
                   9540:   moisdc=vector(1,n);
                   9541:   andc=vector(1,n);
1.220     brouard  9542:   weight=vector(1,n);
1.126     brouard  9543:   agedc=vector(1,n);
                   9544:   cod=ivector(1,n);
1.220     brouard  9545:   for(i=1;i<=n;i++){
                   9546:                num[i]=0;
                   9547:                moisnais[i]=0;
                   9548:                annais[i]=0;
                   9549:                moisdc[i]=0;
                   9550:                andc[i]=0;
                   9551:                agedc[i]=0;
                   9552:                cod[i]=0;
                   9553:                weight[i]=1.0; /* Equal weights, 1 by default */
                   9554:        }
1.126     brouard  9555:   mint=matrix(1,maxwav,1,n);
                   9556:   anint=matrix(1,maxwav,1,n);
1.131     brouard  9557:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  9558:   tab=ivector(1,NCOVMAX);
1.144     brouard  9559:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  9560:   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  9561: 
1.136     brouard  9562:   /* Reads data from file datafile */
                   9563:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   9564:     goto end;
                   9565: 
                   9566:   /* Calculation of the number of parameters from char model */
1.137     brouard  9567:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
                   9568:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   9569:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   9570:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   9571:        k=1 Tvar[1]=2 (from V2)
                   9572:     */
1.231     brouard  9573: 
                   9574:        Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
1.232   ! brouard  9575:   TvarF=ivector(1,NCOVMAX); /*  */
        !          9576:   TvarFind=ivector(1,NCOVMAX); /*  */
        !          9577:   TvarV=ivector(1,NCOVMAX); /*  */
        !          9578:   TvarVind=ivector(1,NCOVMAX); /*  */
        !          9579:   TvarA=ivector(1,NCOVMAX); /*  */
        !          9580:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  9581:   TvarFD=ivector(1,NCOVMAX); /*  */
                   9582:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   9583:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   9584:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   9585:   TvarVD=ivector(1,NCOVMAX); /*  */
                   9586:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   9587:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   9588:   TvarVQind=ivector(1,NCOVMAX); /*  */
                   9589: 
1.230     brouard  9590:   Tvalsel=vector(1,NCOVMAX); /*  */
1.226     brouard  9591:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   9592:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   9593:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.137     brouard  9594:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   9595:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   9596:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   9597:   */
                   9598:   /* For model-covariate k tells which data-covariate to use but
                   9599:     because this model-covariate is a construction we invent a new column
                   9600:     ncovcol + k1
                   9601:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   9602:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  9603:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   9604:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  9605:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   9606:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  9607:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  9608:   */
1.145     brouard  9609:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   9610:   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  9611:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   9612:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  9613:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  9614:                         4 covariates (3 plus signs)
                   9615:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   9616:                      */  
1.230     brouard  9617:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  9618:                                * individual dummy, fixed or varying:
                   9619:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   9620:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  9621:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   9622:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   9623:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   9624:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   9625:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  9626:                                * individual quantitative, fixed or varying:
                   9627:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   9628:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   9629:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.186     brouard  9630: /* Main decodemodel */
                   9631: 
1.187     brouard  9632: 
1.223     brouard  9633:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  9634:     goto end;
                   9635: 
1.137     brouard  9636:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   9637:     nbwarn++;
                   9638:     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); 
                   9639:     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); 
                   9640:   }
1.136     brouard  9641:     /*  if(mle==1){*/
1.137     brouard  9642:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   9643:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  9644:   }
                   9645: 
                   9646:     /*-calculation of age at interview from date of interview and age at death -*/
                   9647:   agev=matrix(1,maxwav,1,imx);
                   9648: 
                   9649:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   9650:     goto end;
                   9651: 
1.126     brouard  9652: 
1.136     brouard  9653:   agegomp=(int)agemin;
                   9654:   free_vector(moisnais,1,n);
                   9655:   free_vector(annais,1,n);
1.126     brouard  9656:   /* free_matrix(mint,1,maxwav,1,n);
                   9657:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  9658:   /* free_vector(moisdc,1,n); */
                   9659:   /* free_vector(andc,1,n); */
1.145     brouard  9660:   /* */
                   9661:   
1.126     brouard  9662:   wav=ivector(1,imx);
1.214     brouard  9663:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   9664:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   9665:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   9666:   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.*/
                   9667:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   9668:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  9669:    
                   9670:   /* Concatenates waves */
1.214     brouard  9671:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   9672:      Death is a valid wave (if date is known).
                   9673:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   9674:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   9675:      and mw[mi+1][i]. dh depends on stepm.
                   9676:   */
                   9677: 
1.126     brouard  9678:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.145     brouard  9679:   /* */
                   9680:  
1.215     brouard  9681:   free_vector(moisdc,1,n);
                   9682:   free_vector(andc,1,n);
                   9683: 
1.126     brouard  9684:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   9685:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   9686:   ncodemax[1]=1;
1.145     brouard  9687:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  9688:   cptcoveff=0;
1.220     brouard  9689:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
                   9690:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.227     brouard  9691:   }
                   9692:   
                   9693:   ncovcombmax=pow(2,cptcoveff);
                   9694:   invalidvarcomb=ivector(1, ncovcombmax); 
                   9695:   for(i=1;i<ncovcombmax;i++)
                   9696:     invalidvarcomb[i]=0;
                   9697:   
1.211     brouard  9698:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  9699:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  9700:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  9701:   
1.200     brouard  9702:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  9703:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  9704:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  9705:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   9706:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   9707:    * (currently 0 or 1) in the data.
                   9708:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   9709:    * corresponding modality (h,j).
                   9710:    */
                   9711: 
1.145     brouard  9712:   h=0;
                   9713:   /*if (cptcovn > 0) */
1.126     brouard  9714:   m=pow(2,cptcoveff);
                   9715:  
1.144     brouard  9716:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  9717:           * For k=4 covariates, h goes from 1 to m=2**k
                   9718:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   9719:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.186     brouard  9720:           *     h\k   1     2     3     4
1.143     brouard  9721:           *______________________________  
                   9722:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   9723:           *     2     2     1     1     1
                   9724:           *     3 i=2 1     2     1     1
                   9725:           *     4     2     2     1     1
                   9726:           *     5 i=3 1 i=2 1     2     1
                   9727:           *     6     2     1     2     1
                   9728:           *     7 i=4 1     2     2     1
                   9729:           *     8     2     2     2     1
1.197     brouard  9730:           *     9 i=5 1 i=3 1 i=2 1     2
                   9731:           *    10     2     1     1     2
                   9732:           *    11 i=6 1     2     1     2
                   9733:           *    12     2     2     1     2
                   9734:           *    13 i=7 1 i=4 1     2     2    
                   9735:           *    14     2     1     2     2
                   9736:           *    15 i=8 1     2     2     2
                   9737:           *    16     2     2     2     2
1.143     brouard  9738:           */
1.212     brouard  9739:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  9740:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   9741:      * and the value of each covariate?
                   9742:      * V1=1, V2=1, V3=2, V4=1 ?
                   9743:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   9744:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   9745:      * In order to get the real value in the data, we use nbcode
                   9746:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   9747:      * We are keeping this crazy system in order to be able (in the future?) 
                   9748:      * to have more than 2 values (0 or 1) for a covariate.
                   9749:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   9750:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   9751:      *              bbbbbbbb
                   9752:      *              76543210     
                   9753:      *   h-1        00000101 (6-1=5)
1.219     brouard  9754:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  9755:      *           &
                   9756:      *     1        00000001 (1)
1.219     brouard  9757:      *              00000000        = 1 & ((h-1) >> (k-1))
                   9758:      *          +1= 00000001 =1 
1.211     brouard  9759:      *
                   9760:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   9761:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   9762:      *    >>k'            11
                   9763:      *          &   00000001
                   9764:      *            = 00000001
                   9765:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   9766:      * Reverse h=6 and m=16?
                   9767:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   9768:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   9769:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   9770:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   9771:      * V3=decodtabm(14,3,2**4)=2
                   9772:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   9773:      *(h-1) >> (j-1)    0011 =13 >> 2
                   9774:      *          &1 000000001
                   9775:      *           = 000000001
                   9776:      *         +1= 000000010 =2
                   9777:      *                  2211
                   9778:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   9779:      *                  V3=2
1.220     brouard  9780:                 * codtabm and decodtabm are identical
1.211     brouard  9781:      */
                   9782: 
1.145     brouard  9783: 
                   9784:  free_ivector(Ndum,-1,NCOVMAX);
                   9785: 
                   9786: 
1.126     brouard  9787:     
1.186     brouard  9788:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  9789:   strcpy(optionfilegnuplot,optionfilefiname);
                   9790:   if(mle==-3)
1.201     brouard  9791:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  9792:   strcat(optionfilegnuplot,".gp");
                   9793: 
                   9794:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   9795:     printf("Problem with file %s",optionfilegnuplot);
                   9796:   }
                   9797:   else{
1.204     brouard  9798:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  9799:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  9800:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   9801:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  9802:   }
                   9803:   /*  fclose(ficgp);*/
1.186     brouard  9804: 
                   9805: 
                   9806:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  9807: 
                   9808:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   9809:   if(mle==-3)
1.201     brouard  9810:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  9811:   strcat(optionfilehtm,".htm");
                   9812:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  9813:     printf("Problem with %s \n",optionfilehtm);
                   9814:     exit(0);
1.126     brouard  9815:   }
                   9816: 
                   9817:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   9818:   strcat(optionfilehtmcov,"-cov.htm");
                   9819:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   9820:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   9821:   }
                   9822:   else{
                   9823:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   9824: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  9825: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  9826:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   9827:   }
                   9828: 
1.213     brouard  9829:   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  9830: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   9831: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  9832: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  9833: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  9834: \n\
                   9835: <hr  size=\"2\" color=\"#EC5E5E\">\
                   9836:  <ul><li><h4>Parameter files</h4>\n\
                   9837:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   9838:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   9839:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   9840:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   9841:  - Date and time at start: %s</ul>\n",\
                   9842:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   9843:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   9844:          fileres,fileres,\
                   9845:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   9846:   fflush(fichtm);
                   9847: 
                   9848:   strcpy(pathr,path);
                   9849:   strcat(pathr,optionfilefiname);
1.184     brouard  9850: #ifdef WIN32
                   9851:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   9852: #else
1.126     brouard  9853:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  9854: #endif
                   9855:          
1.126     brouard  9856:   
1.220     brouard  9857:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   9858:                 and for any valid combination of covariates
1.126     brouard  9859:      and prints on file fileres'p'. */
1.227     brouard  9860:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
                   9861:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  9862: 
                   9863:   fprintf(fichtm,"\n");
                   9864:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   9865: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   9866: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   9867:          imx,agemin,agemax,jmin,jmax,jmean);
                   9868:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.220     brouard  9869:        oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   9870:        newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   9871:        savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   9872:        oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  9873: 
1.126     brouard  9874:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   9875:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   9876:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   9877: 
                   9878:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  9879:   /* For mortality only */
1.126     brouard  9880:   if (mle==-3){
1.136     brouard  9881:     ximort=matrix(1,NDIM,1,NDIM); 
1.220     brouard  9882:                for(i=1;i<=NDIM;i++)
                   9883:                        for(j=1;j<=NDIM;j++)
                   9884:                                ximort[i][j]=0.;
1.186     brouard  9885:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  9886:     cens=ivector(1,n);
                   9887:     ageexmed=vector(1,n);
                   9888:     agecens=vector(1,n);
                   9889:     dcwave=ivector(1,n);
1.223     brouard  9890:                
1.126     brouard  9891:     for (i=1; i<=imx; i++){
                   9892:       dcwave[i]=-1;
                   9893:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  9894:        if (s[m][i]>nlstate) {
                   9895:          dcwave[i]=m;
                   9896:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   9897:          break;
                   9898:        }
1.126     brouard  9899:     }
1.226     brouard  9900:     
1.126     brouard  9901:     for (i=1; i<=imx; i++) {
                   9902:       if (wav[i]>0){
1.226     brouard  9903:        ageexmed[i]=agev[mw[1][i]][i];
                   9904:        j=wav[i];
                   9905:        agecens[i]=1.; 
                   9906:        
                   9907:        if (ageexmed[i]> 1 && wav[i] > 0){
                   9908:          agecens[i]=agev[mw[j][i]][i];
                   9909:          cens[i]= 1;
                   9910:        }else if (ageexmed[i]< 1) 
                   9911:          cens[i]= -1;
                   9912:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   9913:          cens[i]=0 ;
1.126     brouard  9914:       }
                   9915:       else cens[i]=-1;
                   9916:     }
                   9917:     
                   9918:     for (i=1;i<=NDIM;i++) {
                   9919:       for (j=1;j<=NDIM;j++)
1.226     brouard  9920:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  9921:     }
                   9922:     
1.145     brouard  9923:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  9924:     /*printf("%lf %lf", p[1], p[2]);*/
                   9925:     
                   9926:     
1.136     brouard  9927: #ifdef GSL
                   9928:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  9929: #else
1.126     brouard  9930:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  9931: #endif
1.201     brouard  9932:     strcpy(filerespow,"POW-MORT_"); 
                   9933:     strcat(filerespow,fileresu);
1.126     brouard  9934:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   9935:       printf("Problem with resultfile: %s\n", filerespow);
                   9936:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   9937:     }
1.136     brouard  9938: #ifdef GSL
                   9939:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  9940: #else
1.126     brouard  9941:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  9942: #endif
1.126     brouard  9943:     /*  for (i=1;i<=nlstate;i++)
                   9944:        for(j=1;j<=nlstate+ndeath;j++)
                   9945:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   9946:     */
                   9947:     fprintf(ficrespow,"\n");
1.136     brouard  9948: #ifdef GSL
                   9949:     /* gsl starts here */ 
                   9950:     T = gsl_multimin_fminimizer_nmsimplex;
                   9951:     gsl_multimin_fminimizer *sfm = NULL;
                   9952:     gsl_vector *ss, *x;
                   9953:     gsl_multimin_function minex_func;
                   9954: 
                   9955:     /* Initial vertex size vector */
                   9956:     ss = gsl_vector_alloc (NDIM);
                   9957:     
                   9958:     if (ss == NULL){
                   9959:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   9960:     }
                   9961:     /* Set all step sizes to 1 */
                   9962:     gsl_vector_set_all (ss, 0.001);
                   9963: 
                   9964:     /* Starting point */
1.126     brouard  9965:     
1.136     brouard  9966:     x = gsl_vector_alloc (NDIM);
                   9967:     
                   9968:     if (x == NULL){
                   9969:       gsl_vector_free(ss);
                   9970:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   9971:     }
                   9972:   
                   9973:     /* Initialize method and iterate */
                   9974:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  9975:     /*     gsl_vector_set(x, 0, 0.0268); */
                   9976:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  9977:     gsl_vector_set(x, 0, p[1]);
                   9978:     gsl_vector_set(x, 1, p[2]);
                   9979: 
                   9980:     minex_func.f = &gompertz_f;
                   9981:     minex_func.n = NDIM;
                   9982:     minex_func.params = (void *)&p; /* ??? */
                   9983:     
                   9984:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   9985:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   9986:     
                   9987:     printf("Iterations beginning .....\n\n");
                   9988:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   9989: 
                   9990:     iteri=0;
                   9991:     while (rval == GSL_CONTINUE){
                   9992:       iteri++;
                   9993:       status = gsl_multimin_fminimizer_iterate(sfm);
                   9994:       
                   9995:       if (status) printf("error: %s\n", gsl_strerror (status));
                   9996:       fflush(0);
                   9997:       
                   9998:       if (status) 
                   9999:         break;
                   10000:       
                   10001:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   10002:       ssval = gsl_multimin_fminimizer_size (sfm);
                   10003:       
                   10004:       if (rval == GSL_SUCCESS)
                   10005:         printf ("converged to a local maximum at\n");
                   10006:       
                   10007:       printf("%5d ", iteri);
                   10008:       for (it = 0; it < NDIM; it++){
                   10009:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   10010:       }
                   10011:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   10012:     }
                   10013:     
                   10014:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   10015:     
                   10016:     gsl_vector_free(x); /* initial values */
                   10017:     gsl_vector_free(ss); /* inital step size */
                   10018:     for (it=0; it<NDIM; it++){
                   10019:       p[it+1]=gsl_vector_get(sfm->x,it);
                   10020:       fprintf(ficrespow," %.12lf", p[it]);
                   10021:     }
                   10022:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   10023: #endif
                   10024: #ifdef POWELL
                   10025:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   10026: #endif  
1.126     brouard  10027:     fclose(ficrespow);
                   10028:     
1.203     brouard  10029:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  10030: 
                   10031:     for(i=1; i <=NDIM; i++)
                   10032:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  10033:                                matcov[i][j]=matcov[j][i];
1.126     brouard  10034:     
                   10035:     printf("\nCovariance matrix\n ");
1.203     brouard  10036:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  10037:     for(i=1; i <=NDIM; i++) {
                   10038:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  10039:                                printf("%f ",matcov[i][j]);
                   10040:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  10041:       }
1.203     brouard  10042:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  10043:     }
                   10044:     
                   10045:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  10046:     for (i=1;i<=NDIM;i++) {
1.126     brouard  10047:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  10048:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   10049:     }
1.126     brouard  10050:     lsurv=vector(1,AGESUP);
                   10051:     lpop=vector(1,AGESUP);
                   10052:     tpop=vector(1,AGESUP);
                   10053:     lsurv[agegomp]=100000;
                   10054:     
                   10055:     for (k=agegomp;k<=AGESUP;k++) {
                   10056:       agemortsup=k;
                   10057:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   10058:     }
                   10059:     
                   10060:     for (k=agegomp;k<agemortsup;k++)
                   10061:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   10062:     
                   10063:     for (k=agegomp;k<agemortsup;k++){
                   10064:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   10065:       sumlpop=sumlpop+lpop[k];
                   10066:     }
                   10067:     
                   10068:     tpop[agegomp]=sumlpop;
                   10069:     for (k=agegomp;k<(agemortsup-3);k++){
                   10070:       /*  tpop[k+1]=2;*/
                   10071:       tpop[k+1]=tpop[k]-lpop[k];
                   10072:     }
                   10073:     
                   10074:     
                   10075:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   10076:     for (k=agegomp;k<(agemortsup-2);k++) 
                   10077:       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]);
                   10078:     
                   10079:     
                   10080:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  10081:                ageminpar=50;
                   10082:                agemaxpar=100;
1.194     brouard  10083:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   10084:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   10085: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   10086: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   10087:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   10088: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   10089: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  10090:     }else{
                   10091:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   10092:                        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  10093:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  10094:                }
1.201     brouard  10095:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  10096:                     stepm, weightopt,\
                   10097:                     model,imx,p,matcov,agemortsup);
                   10098:     
                   10099:     free_vector(lsurv,1,AGESUP);
                   10100:     free_vector(lpop,1,AGESUP);
                   10101:     free_vector(tpop,1,AGESUP);
1.220     brouard  10102:     free_matrix(ximort,1,NDIM,1,NDIM);
1.136     brouard  10103:     free_ivector(cens,1,n);
                   10104:     free_vector(agecens,1,n);
                   10105:     free_ivector(dcwave,1,n);
1.220     brouard  10106: #ifdef GSL
1.136     brouard  10107: #endif
1.186     brouard  10108:   } /* Endof if mle==-3 mortality only */
1.205     brouard  10109:   /* Standard  */
                   10110:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   10111:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   10112:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  10113:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  10114:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   10115:     for (k=1; k<=npar;k++)
                   10116:       printf(" %d %8.5f",k,p[k]);
                   10117:     printf("\n");
1.205     brouard  10118:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   10119:       /* mlikeli uses func not funcone */
                   10120:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   10121:     }
                   10122:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   10123:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   10124:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   10125:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   10126:     }
                   10127:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  10128:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   10129:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   10130:     for (k=1; k<=npar;k++)
                   10131:       printf(" %d %8.5f",k,p[k]);
                   10132:     printf("\n");
                   10133:     
                   10134:     /*--------- results files --------------*/
1.224     brouard  10135:     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  10136:     
                   10137:     
                   10138:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10139:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10140:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10141:     for(i=1,jk=1; i <=nlstate; i++){
                   10142:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  10143:        if (k != i) {
                   10144:          printf("%d%d ",i,k);
                   10145:          fprintf(ficlog,"%d%d ",i,k);
                   10146:          fprintf(ficres,"%1d%1d ",i,k);
                   10147:          for(j=1; j <=ncovmodel; j++){
                   10148:            printf("%12.7f ",p[jk]);
                   10149:            fprintf(ficlog,"%12.7f ",p[jk]);
                   10150:            fprintf(ficres,"%12.7f ",p[jk]);
                   10151:            jk++; 
                   10152:          }
                   10153:          printf("\n");
                   10154:          fprintf(ficlog,"\n");
                   10155:          fprintf(ficres,"\n");
                   10156:        }
1.126     brouard  10157:       }
                   10158:     }
1.203     brouard  10159:     if(mle != 0){
                   10160:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  10161:       ftolhess=ftol; /* Usually correct */
1.203     brouard  10162:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   10163:       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");
                   10164:       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");
                   10165:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  10166:        for(k=1; k <=(nlstate+ndeath); k++){
                   10167:          if (k != i) {
                   10168:            printf("%d%d ",i,k);
                   10169:            fprintf(ficlog,"%d%d ",i,k);
                   10170:            for(j=1; j <=ncovmodel; j++){
                   10171:              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]));
                   10172:              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]));
                   10173:              jk++; 
                   10174:            }
                   10175:            printf("\n");
                   10176:            fprintf(ficlog,"\n");
                   10177:          }
                   10178:        }
1.193     brouard  10179:       }
1.203     brouard  10180:     } /* end of hesscov and Wald tests */
1.225     brouard  10181:     
1.203     brouard  10182:     /*  */
1.126     brouard  10183:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   10184:     printf("# Scales (for hessian or gradient estimation)\n");
                   10185:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   10186:     for(i=1,jk=1; i <=nlstate; i++){
                   10187:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  10188:        if (j!=i) {
                   10189:          fprintf(ficres,"%1d%1d",i,j);
                   10190:          printf("%1d%1d",i,j);
                   10191:          fprintf(ficlog,"%1d%1d",i,j);
                   10192:          for(k=1; k<=ncovmodel;k++){
                   10193:            printf(" %.5e",delti[jk]);
                   10194:            fprintf(ficlog," %.5e",delti[jk]);
                   10195:            fprintf(ficres," %.5e",delti[jk]);
                   10196:            jk++;
                   10197:          }
                   10198:          printf("\n");
                   10199:          fprintf(ficlog,"\n");
                   10200:          fprintf(ficres,"\n");
                   10201:        }
1.126     brouard  10202:       }
                   10203:     }
                   10204:     
                   10205:     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  10206:     if(mle >= 1) /* To big for the screen */
1.126     brouard  10207:       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");
                   10208:     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");
                   10209:     /* # 121 Var(a12)\n\ */
                   10210:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10211:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   10212:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   10213:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   10214:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   10215:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   10216:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   10217:     
                   10218:     
                   10219:     /* Just to have a covariance matrix which will be more understandable
                   10220:        even is we still don't want to manage dictionary of variables
                   10221:     */
                   10222:     for(itimes=1;itimes<=2;itimes++){
                   10223:       jj=0;
                   10224:       for(i=1; i <=nlstate; i++){
1.225     brouard  10225:        for(j=1; j <=nlstate+ndeath; j++){
                   10226:          if(j==i) continue;
                   10227:          for(k=1; k<=ncovmodel;k++){
                   10228:            jj++;
                   10229:            ca[0]= k+'a'-1;ca[1]='\0';
                   10230:            if(itimes==1){
                   10231:              if(mle>=1)
                   10232:                printf("#%1d%1d%d",i,j,k);
                   10233:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   10234:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   10235:            }else{
                   10236:              if(mle>=1)
                   10237:                printf("%1d%1d%d",i,j,k);
                   10238:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   10239:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   10240:            }
                   10241:            ll=0;
                   10242:            for(li=1;li <=nlstate; li++){
                   10243:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   10244:                if(lj==li) continue;
                   10245:                for(lk=1;lk<=ncovmodel;lk++){
                   10246:                  ll++;
                   10247:                  if(ll<=jj){
                   10248:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   10249:                    if(ll<jj){
                   10250:                      if(itimes==1){
                   10251:                        if(mle>=1)
                   10252:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10253:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10254:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10255:                      }else{
                   10256:                        if(mle>=1)
                   10257:                          printf(" %.5e",matcov[jj][ll]); 
                   10258:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   10259:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   10260:                      }
                   10261:                    }else{
                   10262:                      if(itimes==1){
                   10263:                        if(mle>=1)
                   10264:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   10265:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   10266:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   10267:                      }else{
                   10268:                        if(mle>=1)
                   10269:                          printf(" %.7e",matcov[jj][ll]); 
                   10270:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   10271:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   10272:                      }
                   10273:                    }
                   10274:                  }
                   10275:                } /* end lk */
                   10276:              } /* end lj */
                   10277:            } /* end li */
                   10278:            if(mle>=1)
                   10279:              printf("\n");
                   10280:            fprintf(ficlog,"\n");
                   10281:            fprintf(ficres,"\n");
                   10282:            numlinepar++;
                   10283:          } /* end k*/
                   10284:        } /*end j */
1.126     brouard  10285:       } /* end i */
                   10286:     } /* end itimes */
                   10287:     
                   10288:     fflush(ficlog);
                   10289:     fflush(ficres);
1.225     brouard  10290:     while(fgets(line, MAXLINE, ficpar)) {
                   10291:       /* If line starts with a # it is a comment */
                   10292:       if (line[0] == '#') {
                   10293:        numlinepar++;
                   10294:        fputs(line,stdout);
                   10295:        fputs(line,ficparo);
                   10296:        fputs(line,ficlog);
                   10297:        continue;
                   10298:       }else
                   10299:        break;
                   10300:     }
                   10301:     
1.209     brouard  10302:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   10303:     /*   ungetc(c,ficpar); */
                   10304:     /*   fgets(line, MAXLINE, ficpar); */
                   10305:     /*   fputs(line,stdout); */
                   10306:     /*   fputs(line,ficparo); */
                   10307:     /* } */
                   10308:     /* ungetc(c,ficpar); */
1.126     brouard  10309:     
                   10310:     estepm=0;
1.209     brouard  10311:     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  10312:       
                   10313:       if (num_filled != 6) {
                   10314:        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);
                   10315:        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);
                   10316:        goto end;
                   10317:       }
                   10318:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   10319:     }
                   10320:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   10321:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   10322:     
1.209     brouard  10323:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  10324:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   10325:     if (fage <= 2) {
                   10326:       bage = ageminpar;
                   10327:       fage = agemaxpar;
                   10328:     }
                   10329:     
                   10330:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  10331:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   10332:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  10333:                
1.186     brouard  10334:     /* Other stuffs, more or less useful */    
1.126     brouard  10335:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10336:       ungetc(c,ficpar);
                   10337:       fgets(line, MAXLINE, ficpar);
1.141     brouard  10338:       fputs(line,stdout);
1.126     brouard  10339:       fputs(line,ficparo);
                   10340:     }
                   10341:     ungetc(c,ficpar);
                   10342:     
                   10343:     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);
                   10344:     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);
                   10345:     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);
                   10346:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   10347:     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);
                   10348:     
                   10349:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10350:       ungetc(c,ficpar);
                   10351:       fgets(line, MAXLINE, ficpar);
1.141     brouard  10352:       fputs(line,stdout);
1.126     brouard  10353:       fputs(line,ficparo);
                   10354:     }
                   10355:     ungetc(c,ficpar);
                   10356:     
                   10357:     
                   10358:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   10359:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   10360:     
                   10361:     fscanf(ficpar,"pop_based=%d\n",&popbased);
1.193     brouard  10362:     fprintf(ficlog,"pop_based=%d\n",popbased);
1.126     brouard  10363:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   10364:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   10365:     
                   10366:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10367:       ungetc(c,ficpar);
                   10368:       fgets(line, MAXLINE, ficpar);
1.141     brouard  10369:       fputs(line,stdout);
1.126     brouard  10370:       fputs(line,ficparo);
                   10371:     }
                   10372:     ungetc(c,ficpar);
                   10373:     
                   10374:     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);
                   10375:     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);
                   10376:     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);
                   10377:     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);
                   10378:     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);
                   10379:     /* day and month of proj2 are not used but only year anproj2.*/
                   10380:     
1.217     brouard  10381:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10382:       ungetc(c,ficpar);
                   10383:       fgets(line, MAXLINE, ficpar);
                   10384:       fputs(line,stdout);
                   10385:       fputs(line,ficparo);
                   10386:     }
                   10387:     ungetc(c,ficpar);
                   10388:     
                   10389:     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  10390:     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);
                   10391:     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);
                   10392:     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  10393:     /* day and month of proj2 are not used but only year anproj2.*/
1.126     brouard  10394:     
1.230     brouard  10395:     /* Results */
                   10396:     while(fgets(line, MAXLINE, ficpar)) {
                   10397:       /* If line starts with a # it is a comment */
                   10398:       if (line[0] == '#') {
                   10399:        numlinepar++;
                   10400:        fputs(line,stdout);
                   10401:        fputs(line,ficparo);
                   10402:        fputs(line,ficlog);
                   10403:        continue;
                   10404:       }else
                   10405:        break;
                   10406:     }
                   10407:     while((num_filled=sscanf(line,"result:%[^\n]\n",resultline)) !=EOF){
                   10408:       if (num_filled == 0)
                   10409:        resultline[0]='\0';
                   10410:       else if (num_filled != 1){
                   10411:        printf("ERROR %d: result line should be at minimum 'result=' %s\n",num_filled, line);
                   10412:       }
                   10413:       printf("Result %d: result line should be at minimum 'line=' %s, result=%s\n",num_filled, line, resultline);
                   10414:       decoderesult(resultline);
                   10415:       while(fgets(line, MAXLINE, ficpar)) {
                   10416:        /* If line starts with a # it is a comment */
                   10417:        if (line[0] == '#') {
                   10418:          numlinepar++;
                   10419:          fputs(line,stdout);
                   10420:          fputs(line,ficparo);
                   10421:          fputs(line,ficlog);
                   10422:          continue;
                   10423:        }else
                   10424:          break;
                   10425:       }
                   10426:       if (feof(ficpar))
                   10427:        break;
                   10428:       else{ /* Processess output results for this combination of covariate values */
                   10429:       }                                   
                   10430:     }
                   10431: 
                   10432: 
1.126     brouard  10433:     
1.230     brouard  10434:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  10435:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  10436:     
                   10437:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  10438:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  10439:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  10440: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   10441: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  10442:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  10443: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   10444: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  10445:     }else{
1.218     brouard  10446:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p);
1.220     brouard  10447:     }
                   10448:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.225     brouard  10449:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,prevfcast,backcast, estepm, \
                   10450:                 jprev1,mprev1,anprev1,dateprev1,jprev2,mprev2,anprev2,dateprev2);
1.220     brouard  10451:                
1.225     brouard  10452:     /*------------ free_vector  -------------*/
                   10453:     /*  chdir(path); */
1.220     brouard  10454:                
1.215     brouard  10455:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   10456:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   10457:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   10458:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.126     brouard  10459:     free_lvector(num,1,n);
                   10460:     free_vector(agedc,1,n);
                   10461:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   10462:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   10463:     fclose(ficparo);
                   10464:     fclose(ficres);
1.220     brouard  10465:                
                   10466:                
1.186     brouard  10467:     /* Other results (useful)*/
1.220     brouard  10468:                
                   10469:                
1.126     brouard  10470:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  10471:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   10472:     prlim=matrix(1,nlstate,1,nlstate);
1.209     brouard  10473:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  10474:     fclose(ficrespl);
                   10475: 
                   10476:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  10477:     /*#include "hpijx.h"*/
                   10478:     hPijx(p, bage, fage);
1.145     brouard  10479:     fclose(ficrespij);
1.227     brouard  10480:     
1.220     brouard  10481:     /* ncovcombmax=  pow(2,cptcoveff); */
1.219     brouard  10482:     /*-------------- Variance of one-step probabilities---*/
1.145     brouard  10483:     k=1;
1.126     brouard  10484:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  10485:     
1.219     brouard  10486:     /* Prevalence for each covariates in probs[age][status][cov] */
1.218     brouard  10487:     probs= ma3x(1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.126     brouard  10488:     for(i=1;i<=AGESUP;i++)
1.219     brouard  10489:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  10490:        for(k=1;k<=ncovcombmax;k++)
                   10491:          probs[i][j][k]=0.;
1.219     brouard  10492:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   10493:     if (mobilav!=0 ||mobilavproj !=0 ) {
                   10494:       mobaverages= ma3x(1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.227     brouard  10495:       for(i=1;i<=AGESUP;i++)
                   10496:        for(j=1;j<=nlstate;j++)
                   10497:          for(k=1;k<=ncovcombmax;k++)
                   10498:            mobaverages[i][j][k]=0.;
1.219     brouard  10499:       mobaverage=mobaverages;
                   10500:       if (mobilav!=0) {
1.227     brouard  10501:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   10502:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   10503:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   10504:        }
1.219     brouard  10505:       }
                   10506:       /* /\* Prevalence for each covariates in probs[age][status][cov] *\/ */
                   10507:       /* prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   10508:       else if (mobilavproj !=0) {
1.227     brouard  10509:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   10510:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   10511:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   10512:        }
1.219     brouard  10513:       }
                   10514:     }/* end if moving average */
1.227     brouard  10515:     
1.126     brouard  10516:     /*---------- Forecasting ------------------*/
                   10517:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   10518:     if(prevfcast==1){
                   10519:       /*    if(stepm ==1){*/
1.225     brouard  10520:       prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
1.126     brouard  10521:     }
1.217     brouard  10522:     if(backcast==1){
1.219     brouard  10523:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   10524:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   10525:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   10526: 
                   10527:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   10528: 
                   10529:       bprlim=matrix(1,nlstate,1,nlstate);
                   10530:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   10531:       fclose(ficresplb);
                   10532: 
1.222     brouard  10533:       hBijx(p, bage, fage, mobaverage);
                   10534:       fclose(ficrespijb);
1.219     brouard  10535:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   10536: 
                   10537:       /* prevbackforecast(fileresu, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, mobilavproj,
1.225     brouard  10538:         bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
1.219     brouard  10539:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   10540:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   10541:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   10542:     }
1.217     brouard  10543:     
1.186     brouard  10544:  
                   10545:     /* ------ Other prevalence ratios------------ */
1.126     brouard  10546: 
1.215     brouard  10547:     free_ivector(wav,1,imx);
                   10548:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   10549:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   10550:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  10551:                
                   10552:                
1.127     brouard  10553:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  10554:                
1.201     brouard  10555:     strcpy(filerese,"E_");
                   10556:     strcat(filerese,fileresu);
1.126     brouard  10557:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   10558:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   10559:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   10560:     }
1.208     brouard  10561:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   10562:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.219     brouard  10563:                
1.227     brouard  10564:     for (k=1; k <= (int) pow(2,cptcoveff); k++){ /* For any combination of dummy covariates, fixed and varying */
1.219     brouard  10565:       fprintf(ficreseij,"\n#****** ");
1.225     brouard  10566:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  10567:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.219     brouard  10568:       }
                   10569:       fprintf(ficreseij,"******\n");
                   10570:       
                   10571:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   10572:       oldm=oldms;savm=savms;
                   10573:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
1.127     brouard  10574:       
1.219     brouard  10575:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  10576:     }
                   10577:     fclose(ficreseij);
1.208     brouard  10578:     printf("done evsij\n");fflush(stdout);
                   10579:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.218     brouard  10580:                
1.227     brouard  10581:     /*---------- State-specific expectancies and variances ------------*/
1.218     brouard  10582:                
                   10583:                
1.201     brouard  10584:     strcpy(filerest,"T_");
                   10585:     strcat(filerest,fileresu);
1.127     brouard  10586:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   10587:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   10588:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   10589:     }
1.208     brouard  10590:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   10591:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.218     brouard  10592:                
1.126     brouard  10593: 
1.201     brouard  10594:     strcpy(fileresstde,"STDE_");
                   10595:     strcat(fileresstde,fileresu);
1.126     brouard  10596:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  10597:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   10598:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  10599:     }
1.227     brouard  10600:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   10601:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  10602: 
1.201     brouard  10603:     strcpy(filerescve,"CVE_");
                   10604:     strcat(filerescve,fileresu);
1.126     brouard  10605:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  10606:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   10607:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  10608:     }
1.227     brouard  10609:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   10610:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  10611: 
1.201     brouard  10612:     strcpy(fileresv,"V_");
                   10613:     strcat(fileresv,fileresu);
1.126     brouard  10614:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   10615:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   10616:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   10617:     }
1.227     brouard  10618:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   10619:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  10620: 
1.145     brouard  10621:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   10622:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   10623:           
1.225     brouard  10624:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.227     brouard  10625:       printf("\n#****** ");
1.208     brouard  10626:       fprintf(ficrest,"\n#****** ");
1.227     brouard  10627:       fprintf(ficlog,"\n#****** ");
                   10628:       for(j=1;j<=cptcoveff;j++){ 
                   10629:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10630:        fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10631:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10632:       }
1.208     brouard  10633:       fprintf(ficrest,"******\n");
1.227     brouard  10634:       fprintf(ficlog,"******\n");
                   10635:       printf("******\n");
1.208     brouard  10636:       
                   10637:       fprintf(ficresstdeij,"\n#****** ");
                   10638:       fprintf(ficrescveij,"\n#****** ");
1.225     brouard  10639:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  10640:        fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10641:        fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.208     brouard  10642:       }
                   10643:       fprintf(ficresstdeij,"******\n");
                   10644:       fprintf(ficrescveij,"******\n");
                   10645:       
                   10646:       fprintf(ficresvij,"\n#****** ");
1.225     brouard  10647:       for(j=1;j<=cptcoveff;j++) 
1.227     brouard  10648:        fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.208     brouard  10649:       fprintf(ficresvij,"******\n");
                   10650:       
                   10651:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   10652:       oldm=oldms;savm=savms;
1.227     brouard  10653:       printf(" cvevsij combination#=%d, ",k);
                   10654:       fprintf(ficlog, " cvevsij combination#=%d, ",k);
1.208     brouard  10655:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
                   10656:       printf(" end cvevsij \n ");
                   10657:       fprintf(ficlog, " end cvevsij \n ");
                   10658:       
                   10659:       /*
                   10660:        */
                   10661:       /* goto endfree; */
                   10662:       
                   10663:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   10664:       pstamp(ficrest);
                   10665:       
                   10666:       
                   10667:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  10668:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   10669:        cptcod= 0; /* To be deleted */
                   10670:        printf("varevsij vpopbased=%d \n",vpopbased);
                   10671:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
                   10672:        varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart); /* cptcod not initialized Intel */
                   10673:        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 ");
                   10674:        if(vpopbased==1)
                   10675:          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);
                   10676:        else
                   10677:          fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
                   10678:        fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
                   10679:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   10680:        fprintf(ficrest,"\n");
                   10681:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
                   10682:        epj=vector(1,nlstate+1);
                   10683:        printf("Computing age specific period (stable) prevalences in each health state \n");
                   10684:        fprintf(ficlog,"Computing age specific period (stable) prevalences in each health state \n");
                   10685:        for(age=bage; age <=fage ;age++){
                   10686:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k); /*ZZ Is it the correct prevalim */
                   10687:          if (vpopbased==1) {
                   10688:            if(mobilav ==0){
                   10689:              for(i=1; i<=nlstate;i++)
                   10690:                prlim[i][i]=probs[(int)age][i][k];
                   10691:            }else{ /* mobilav */ 
                   10692:              for(i=1; i<=nlstate;i++)
                   10693:                prlim[i][i]=mobaverage[(int)age][i][k];
                   10694:            }
                   10695:          }
1.219     brouard  10696:          
1.227     brouard  10697:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   10698:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   10699:          /* printf(" age %4.0f ",age); */
                   10700:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   10701:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   10702:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   10703:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   10704:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   10705:            }
                   10706:            epj[nlstate+1] +=epj[j];
                   10707:          }
                   10708:          /* printf(" age %4.0f \n",age); */
1.219     brouard  10709:          
1.227     brouard  10710:          for(i=1, vepp=0.;i <=nlstate;i++)
                   10711:            for(j=1;j <=nlstate;j++)
                   10712:              vepp += vareij[i][j][(int)age];
                   10713:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   10714:          for(j=1;j <=nlstate;j++){
                   10715:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   10716:          }
                   10717:          fprintf(ficrest,"\n");
                   10718:        }
1.208     brouard  10719:       } /* End vpopbased */
                   10720:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   10721:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   10722:       free_vector(epj,1,nlstate+1);
                   10723:       printf("done \n");fflush(stdout);
                   10724:       fprintf(ficlog,"done\n");fflush(ficlog);
                   10725:       
1.145     brouard  10726:       /*}*/
1.208     brouard  10727:     } /* End k */
1.227     brouard  10728: 
                   10729:     printf("done State-specific expectancies\n");fflush(stdout);
                   10730:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   10731: 
1.126     brouard  10732:     /*------- Variance of period (stable) prevalence------*/   
1.227     brouard  10733:     
1.201     brouard  10734:     strcpy(fileresvpl,"VPL_");
                   10735:     strcat(fileresvpl,fileresu);
1.126     brouard  10736:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   10737:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   10738:       exit(0);
                   10739:     }
1.208     brouard  10740:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   10741:     fprintf(ficlog, "Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.227     brouard  10742:     
1.145     brouard  10743:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   10744:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
1.227     brouard  10745:     
1.225     brouard  10746:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.227     brouard  10747:       fprintf(ficresvpl,"\n#****** ");
                   10748:       printf("\n#****** ");
                   10749:       fprintf(ficlog,"\n#****** ");
                   10750:       for(j=1;j<=cptcoveff;j++) {
                   10751:        fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10752:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10753:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10754:       }
                   10755:       fprintf(ficresvpl,"******\n");
                   10756:       printf("******\n");
                   10757:       fprintf(ficlog,"******\n");
                   10758:       
                   10759:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   10760:       oldm=oldms;savm=savms;
                   10761:       varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, strstart);
                   10762:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145     brouard  10763:       /*}*/
1.126     brouard  10764:     }
1.227     brouard  10765:     
1.126     brouard  10766:     fclose(ficresvpl);
1.208     brouard  10767:     printf("done variance-covariance of period prevalence\n");fflush(stdout);
                   10768:     fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
1.227     brouard  10769:     
                   10770:     free_vector(weight,1,n);
                   10771:     free_imatrix(Tvard,1,NCOVMAX,1,2);
                   10772:     free_imatrix(s,1,maxwav+1,1,n);
                   10773:     free_matrix(anint,1,maxwav,1,n); 
                   10774:     free_matrix(mint,1,maxwav,1,n);
                   10775:     free_ivector(cod,1,n);
                   10776:     free_ivector(tab,1,NCOVMAX);
                   10777:     fclose(ficresstdeij);
                   10778:     fclose(ficrescveij);
                   10779:     fclose(ficresvij);
                   10780:     fclose(ficrest);
                   10781:     fclose(ficpar);
                   10782:     
                   10783:     
1.126     brouard  10784:     /*---------- End : free ----------------*/
1.219     brouard  10785:     if (mobilav!=0 ||mobilavproj !=0)
                   10786:       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  10787:     free_ma3x(probs,1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  10788:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   10789:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  10790:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  10791:   /* endfree:*/
                   10792:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   10793:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   10794:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   10795:   free_ma3x(cotqvar,1,maxwav,1,nqtv,1,n);
                   10796:   free_ma3x(cotvar,1,maxwav,1,ntv,1,n);
                   10797:   free_matrix(coqvar,1,maxwav,1,n);
                   10798:   free_matrix(covar,0,NCOVMAX,1,n);
                   10799:   free_matrix(matcov,1,npar,1,npar);
                   10800:   free_matrix(hess,1,npar,1,npar);
                   10801:   /*free_vector(delti,1,npar);*/
                   10802:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   10803:   free_matrix(agev,1,maxwav,1,imx);
                   10804:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   10805:   
                   10806:   free_ivector(ncodemax,1,NCOVMAX);
                   10807:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   10808:   free_ivector(Dummy,-1,NCOVMAX);
                   10809:   free_ivector(Fixed,-1,NCOVMAX);
                   10810:   free_ivector(Typevar,-1,NCOVMAX);
                   10811:   free_ivector(Tvar,1,NCOVMAX);
1.231     brouard  10812:   free_ivector(TvarFD,1,NCOVMAX);
                   10813:   free_ivector(TvarFDind,1,NCOVMAX);
1.232   ! brouard  10814:   free_ivector(TvarF,1,NCOVMAX);
        !          10815:   free_ivector(TvarFind,1,NCOVMAX);
        !          10816:   free_ivector(TvarV,1,NCOVMAX);
        !          10817:   free_ivector(TvarVind,1,NCOVMAX);
        !          10818:   free_ivector(TvarA,1,NCOVMAX);
        !          10819:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  10820:   free_ivector(TvarFQ,1,NCOVMAX);
                   10821:   free_ivector(TvarFQind,1,NCOVMAX);
                   10822:   free_ivector(TvarVD,1,NCOVMAX);
                   10823:   free_ivector(TvarVDind,1,NCOVMAX);
                   10824:   free_ivector(TvarVQ,1,NCOVMAX);
                   10825:   free_ivector(TvarVQind,1,NCOVMAX);
1.230     brouard  10826:   free_ivector(Tvarsel,1,NCOVMAX);
                   10827:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  10828:   free_ivector(Tposprod,1,NCOVMAX);
                   10829:   free_ivector(Tprod,1,NCOVMAX);
                   10830:   free_ivector(Tvaraff,1,NCOVMAX);
                   10831:   free_ivector(invalidvarcomb,1,ncovcombmax);
                   10832:   free_ivector(Tage,1,NCOVMAX);
                   10833:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  10834:   free_ivector(TmodelInvind,1,NCOVMAX);
                   10835:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.227     brouard  10836:   
                   10837:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   10838:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  10839:   fflush(fichtm);
                   10840:   fflush(ficgp);
                   10841:   
1.227     brouard  10842:   
1.126     brouard  10843:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  10844:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   10845:     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  10846:   }else{
                   10847:     printf("End of Imach\n");
                   10848:     fprintf(ficlog,"End of Imach\n");
                   10849:   }
                   10850:   printf("See log file on %s\n",filelog);
                   10851:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  10852:   /*(void) gettimeofday(&end_time,&tzp);*/
                   10853:   rend_time = time(NULL);  
                   10854:   end_time = *localtime(&rend_time);
                   10855:   /* tml = *localtime(&end_time.tm_sec); */
                   10856:   strcpy(strtend,asctime(&end_time));
1.126     brouard  10857:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   10858:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  10859:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  10860:   
1.157     brouard  10861:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   10862:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   10863:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  10864:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   10865: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   10866:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   10867:   fclose(fichtm);
                   10868:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   10869:   fclose(fichtmcov);
                   10870:   fclose(ficgp);
                   10871:   fclose(ficlog);
                   10872:   /*------ End -----------*/
1.227     brouard  10873:   
                   10874:   
                   10875:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  10876: #ifdef WIN32
1.227     brouard  10877:   if (_chdir(pathcd) != 0)
                   10878:     printf("Can't move to directory %s!\n",path);
                   10879:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  10880: #else
1.227     brouard  10881:     if(chdir(pathcd) != 0)
                   10882:       printf("Can't move to directory %s!\n", path);
                   10883:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  10884: #endif 
1.126     brouard  10885:     printf("Current directory %s!\n",pathcd);
                   10886:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   10887:   sprintf(plotcmd,"gnuplot");
1.157     brouard  10888: #ifdef _WIN32
1.126     brouard  10889:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   10890: #endif
                   10891:   if(!stat(plotcmd,&info)){
1.158     brouard  10892:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  10893:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  10894:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  10895:     }else
                   10896:       strcpy(pplotcmd,plotcmd);
1.157     brouard  10897: #ifdef __unix
1.126     brouard  10898:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   10899:     if(!stat(plotcmd,&info)){
1.158     brouard  10900:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  10901:     }else
                   10902:       strcpy(pplotcmd,plotcmd);
                   10903: #endif
                   10904:   }else
                   10905:     strcpy(pplotcmd,plotcmd);
                   10906:   
                   10907:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  10908:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.227     brouard  10909:   
1.126     brouard  10910:   if((outcmd=system(plotcmd)) != 0){
1.158     brouard  10911:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  10912:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  10913:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150     brouard  10914:     if((outcmd=system(plotcmd)) != 0)
1.153     brouard  10915:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126     brouard  10916:   }
1.158     brouard  10917:   printf(" Successful, please wait...");
1.126     brouard  10918:   while (z[0] != 'q') {
                   10919:     /* chdir(path); */
1.154     brouard  10920:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  10921:     scanf("%s",z);
                   10922: /*     if (z[0] == 'c') system("./imach"); */
                   10923:     if (z[0] == 'e') {
1.158     brouard  10924: #ifdef __APPLE__
1.152     brouard  10925:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  10926: #elif __linux
                   10927:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  10928: #else
1.152     brouard  10929:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  10930: #endif
                   10931:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   10932:       system(pplotcmd);
1.126     brouard  10933:     }
                   10934:     else if (z[0] == 'g') system(plotcmd);
                   10935:     else if (z[0] == 'q') exit(0);
                   10936:   }
1.227     brouard  10937: end:
1.126     brouard  10938:   while (z[0] != 'q') {
1.195     brouard  10939:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  10940:     scanf("%s",z);
                   10941:   }
                   10942: }

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