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

1.224   ! brouard     1: /* $Id: imach.c,v 1.223 2016/02/19 09:23:35 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.224   ! brouard     4:   Revision 1.223  2016/02/19 09:23:35  brouard
        !             5:   Summary: temporary
        !             6: 
1.223     brouard     7:   Revision 1.222  2016/02/17 08:14:50  brouard
                      8:   Summary: Probably last 0.98 stable version 0.98r6
                      9: 
1.222     brouard    10:   Revision 1.221  2016/02/15 23:35:36  brouard
                     11:   Summary: minor bug
                     12: 
1.220     brouard    13:   Revision 1.219  2016/02/15 00:48:12  brouard
                     14:   *** empty log message ***
                     15: 
1.219     brouard    16:   Revision 1.218  2016/02/12 11:29:23  brouard
                     17:   Summary: 0.99 Back projections
                     18: 
1.218     brouard    19:   Revision 1.217  2015/12/23 17:18:31  brouard
                     20:   Summary: Experimental backcast
                     21: 
1.217     brouard    22:   Revision 1.216  2015/12/18 17:32:11  brouard
                     23:   Summary: 0.98r4 Warning and status=-2
                     24: 
                     25:   Version 0.98r4 is now:
                     26:    - displaying an error when status is -1, date of interview unknown and date of death known;
                     27:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                     28:   Older changes concerning s=-2, dating from 2005 have been supersed.
                     29: 
1.216     brouard    30:   Revision 1.215  2015/12/16 08:52:24  brouard
                     31:   Summary: 0.98r4 working
                     32: 
1.215     brouard    33:   Revision 1.214  2015/12/16 06:57:54  brouard
                     34:   Summary: temporary not working
                     35: 
1.214     brouard    36:   Revision 1.213  2015/12/11 18:22:17  brouard
                     37:   Summary: 0.98r4
                     38: 
1.213     brouard    39:   Revision 1.212  2015/11/21 12:47:24  brouard
                     40:   Summary: minor typo
                     41: 
1.212     brouard    42:   Revision 1.211  2015/11/21 12:41:11  brouard
                     43:   Summary: 0.98r3 with some graph of projected cross-sectional
                     44: 
                     45:   Author: Nicolas Brouard
                     46: 
1.211     brouard    47:   Revision 1.210  2015/11/18 17:41:20  brouard
                     48:   Summary: Start working on projected prevalences
                     49: 
1.210     brouard    50:   Revision 1.209  2015/11/17 22:12:03  brouard
                     51:   Summary: Adding ftolpl parameter
                     52:   Author: N Brouard
                     53: 
                     54:   We had difficulties to get smoothed confidence intervals. It was due
                     55:   to the period prevalence which wasn't computed accurately. The inner
                     56:   parameter ftolpl is now an outer parameter of the .imach parameter
                     57:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                     58:   computation are long.
                     59: 
1.209     brouard    60:   Revision 1.208  2015/11/17 14:31:57  brouard
                     61:   Summary: temporary
                     62: 
1.208     brouard    63:   Revision 1.207  2015/10/27 17:36:57  brouard
                     64:   *** empty log message ***
                     65: 
1.207     brouard    66:   Revision 1.206  2015/10/24 07:14:11  brouard
                     67:   *** empty log message ***
                     68: 
1.206     brouard    69:   Revision 1.205  2015/10/23 15:50:53  brouard
                     70:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                     71: 
1.205     brouard    72:   Revision 1.204  2015/10/01 16:20:26  brouard
                     73:   Summary: Some new graphs of contribution to likelihood
                     74: 
1.204     brouard    75:   Revision 1.203  2015/09/30 17:45:14  brouard
                     76:   Summary: looking at better estimation of the hessian
                     77: 
                     78:   Also a better criteria for convergence to the period prevalence And
                     79:   therefore adding the number of years needed to converge. (The
                     80:   prevalence in any alive state shold sum to one
                     81: 
1.203     brouard    82:   Revision 1.202  2015/09/22 19:45:16  brouard
                     83:   Summary: Adding some overall graph on contribution to likelihood. Might change
                     84: 
1.202     brouard    85:   Revision 1.201  2015/09/15 17:34:58  brouard
                     86:   Summary: 0.98r0
                     87: 
                     88:   - Some new graphs like suvival functions
                     89:   - Some bugs fixed like model=1+age+V2.
                     90: 
1.201     brouard    91:   Revision 1.200  2015/09/09 16:53:55  brouard
                     92:   Summary: Big bug thanks to Flavia
                     93: 
                     94:   Even model=1+age+V2. did not work anymore
                     95: 
1.200     brouard    96:   Revision 1.199  2015/09/07 14:09:23  brouard
                     97:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                     98: 
1.199     brouard    99:   Revision 1.198  2015/09/03 07:14:39  brouard
                    100:   Summary: 0.98q5 Flavia
                    101: 
1.198     brouard   102:   Revision 1.197  2015/09/01 18:24:39  brouard
                    103:   *** empty log message ***
                    104: 
1.197     brouard   105:   Revision 1.196  2015/08/18 23:17:52  brouard
                    106:   Summary: 0.98q5
                    107: 
1.196     brouard   108:   Revision 1.195  2015/08/18 16:28:39  brouard
                    109:   Summary: Adding a hack for testing purpose
                    110: 
                    111:   After reading the title, ftol and model lines, if the comment line has
                    112:   a q, starting with #q, the answer at the end of the run is quit. It
                    113:   permits to run test files in batch with ctest. The former workaround was
                    114:   $ echo q | imach foo.imach
                    115: 
1.195     brouard   116:   Revision 1.194  2015/08/18 13:32:00  brouard
                    117:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    118: 
1.194     brouard   119:   Revision 1.193  2015/08/04 07:17:42  brouard
                    120:   Summary: 0.98q4
                    121: 
1.193     brouard   122:   Revision 1.192  2015/07/16 16:49:02  brouard
                    123:   Summary: Fixing some outputs
                    124: 
1.192     brouard   125:   Revision 1.191  2015/07/14 10:00:33  brouard
                    126:   Summary: Some fixes
                    127: 
1.191     brouard   128:   Revision 1.190  2015/05/05 08:51:13  brouard
                    129:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    130: 
                    131:   Fix 1+age+.
                    132: 
1.190     brouard   133:   Revision 1.189  2015/04/30 14:45:16  brouard
                    134:   Summary: 0.98q2
                    135: 
1.189     brouard   136:   Revision 1.188  2015/04/30 08:27:53  brouard
                    137:   *** empty log message ***
                    138: 
1.188     brouard   139:   Revision 1.187  2015/04/29 09:11:15  brouard
                    140:   *** empty log message ***
                    141: 
1.187     brouard   142:   Revision 1.186  2015/04/23 12:01:52  brouard
                    143:   Summary: V1*age is working now, version 0.98q1
                    144: 
                    145:   Some codes had been disabled in order to simplify and Vn*age was
                    146:   working in the optimization phase, ie, giving correct MLE parameters,
                    147:   but, as usual, outputs were not correct and program core dumped.
                    148: 
1.186     brouard   149:   Revision 1.185  2015/03/11 13:26:42  brouard
                    150:   Summary: Inclusion of compile and links command line for Intel Compiler
                    151: 
1.185     brouard   152:   Revision 1.184  2015/03/11 11:52:39  brouard
                    153:   Summary: Back from Windows 8. Intel Compiler
                    154: 
1.184     brouard   155:   Revision 1.183  2015/03/10 20:34:32  brouard
                    156:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    157: 
                    158:   We use directest instead of original Powell test; probably no
                    159:   incidence on the results, but better justifications;
                    160:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    161:   wrong results.
                    162: 
1.183     brouard   163:   Revision 1.182  2015/02/12 08:19:57  brouard
                    164:   Summary: Trying to keep directest which seems simpler and more general
                    165:   Author: Nicolas Brouard
                    166: 
1.182     brouard   167:   Revision 1.181  2015/02/11 23:22:24  brouard
                    168:   Summary: Comments on Powell added
                    169: 
                    170:   Author:
                    171: 
1.181     brouard   172:   Revision 1.180  2015/02/11 17:33:45  brouard
                    173:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    174: 
1.180     brouard   175:   Revision 1.179  2015/01/04 09:57:06  brouard
                    176:   Summary: back to OS/X
                    177: 
1.179     brouard   178:   Revision 1.178  2015/01/04 09:35:48  brouard
                    179:   *** empty log message ***
                    180: 
1.178     brouard   181:   Revision 1.177  2015/01/03 18:40:56  brouard
                    182:   Summary: Still testing ilc32 on OSX
                    183: 
1.177     brouard   184:   Revision 1.176  2015/01/03 16:45:04  brouard
                    185:   *** empty log message ***
                    186: 
1.176     brouard   187:   Revision 1.175  2015/01/03 16:33:42  brouard
                    188:   *** empty log message ***
                    189: 
1.175     brouard   190:   Revision 1.174  2015/01/03 16:15:49  brouard
                    191:   Summary: Still in cross-compilation
                    192: 
1.174     brouard   193:   Revision 1.173  2015/01/03 12:06:26  brouard
                    194:   Summary: trying to detect cross-compilation
                    195: 
1.173     brouard   196:   Revision 1.172  2014/12/27 12:07:47  brouard
                    197:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    198: 
1.172     brouard   199:   Revision 1.171  2014/12/23 13:26:59  brouard
                    200:   Summary: Back from Visual C
                    201: 
                    202:   Still problem with utsname.h on Windows
                    203: 
1.171     brouard   204:   Revision 1.170  2014/12/23 11:17:12  brouard
                    205:   Summary: Cleaning some \%% back to %%
                    206: 
                    207:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    208: 
1.170     brouard   209:   Revision 1.169  2014/12/22 23:08:31  brouard
                    210:   Summary: 0.98p
                    211: 
                    212:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    213: 
1.169     brouard   214:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   215:   Summary: update
1.169     brouard   216: 
1.168     brouard   217:   Revision 1.167  2014/12/22 13:50:56  brouard
                    218:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    219: 
                    220:   Testing on Linux 64
                    221: 
1.167     brouard   222:   Revision 1.166  2014/12/22 11:40:47  brouard
                    223:   *** empty log message ***
                    224: 
1.166     brouard   225:   Revision 1.165  2014/12/16 11:20:36  brouard
                    226:   Summary: After compiling on Visual C
                    227: 
                    228:   * imach.c (Module): Merging 1.61 to 1.162
                    229: 
1.165     brouard   230:   Revision 1.164  2014/12/16 10:52:11  brouard
                    231:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    232: 
                    233:   * imach.c (Module): Merging 1.61 to 1.162
                    234: 
1.164     brouard   235:   Revision 1.163  2014/12/16 10:30:11  brouard
                    236:   * imach.c (Module): Merging 1.61 to 1.162
                    237: 
1.163     brouard   238:   Revision 1.162  2014/09/25 11:43:39  brouard
                    239:   Summary: temporary backup 0.99!
                    240: 
1.162     brouard   241:   Revision 1.1  2014/09/16 11:06:58  brouard
                    242:   Summary: With some code (wrong) for nlopt
                    243: 
                    244:   Author:
                    245: 
                    246:   Revision 1.161  2014/09/15 20:41:41  brouard
                    247:   Summary: Problem with macro SQR on Intel compiler
                    248: 
1.161     brouard   249:   Revision 1.160  2014/09/02 09:24:05  brouard
                    250:   *** empty log message ***
                    251: 
1.160     brouard   252:   Revision 1.159  2014/09/01 10:34:10  brouard
                    253:   Summary: WIN32
                    254:   Author: Brouard
                    255: 
1.159     brouard   256:   Revision 1.158  2014/08/27 17:11:51  brouard
                    257:   *** empty log message ***
                    258: 
1.158     brouard   259:   Revision 1.157  2014/08/27 16:26:55  brouard
                    260:   Summary: Preparing windows Visual studio version
                    261:   Author: Brouard
                    262: 
                    263:   In order to compile on Visual studio, time.h is now correct and time_t
                    264:   and tm struct should be used. difftime should be used but sometimes I
                    265:   just make the differences in raw time format (time(&now).
                    266:   Trying to suppress #ifdef LINUX
                    267:   Add xdg-open for __linux in order to open default browser.
                    268: 
1.157     brouard   269:   Revision 1.156  2014/08/25 20:10:10  brouard
                    270:   *** empty log message ***
                    271: 
1.156     brouard   272:   Revision 1.155  2014/08/25 18:32:34  brouard
                    273:   Summary: New compile, minor changes
                    274:   Author: Brouard
                    275: 
1.155     brouard   276:   Revision 1.154  2014/06/20 17:32:08  brouard
                    277:   Summary: Outputs now all graphs of convergence to period prevalence
                    278: 
1.154     brouard   279:   Revision 1.153  2014/06/20 16:45:46  brouard
                    280:   Summary: If 3 live state, convergence to period prevalence on same graph
                    281:   Author: Brouard
                    282: 
1.153     brouard   283:   Revision 1.152  2014/06/18 17:54:09  brouard
                    284:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    285: 
1.152     brouard   286:   Revision 1.151  2014/06/18 16:43:30  brouard
                    287:   *** empty log message ***
                    288: 
1.151     brouard   289:   Revision 1.150  2014/06/18 16:42:35  brouard
                    290:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    291:   Author: brouard
                    292: 
1.150     brouard   293:   Revision 1.149  2014/06/18 15:51:14  brouard
                    294:   Summary: Some fixes in parameter files errors
                    295:   Author: Nicolas Brouard
                    296: 
1.149     brouard   297:   Revision 1.148  2014/06/17 17:38:48  brouard
                    298:   Summary: Nothing new
                    299:   Author: Brouard
                    300: 
                    301:   Just a new packaging for OS/X version 0.98nS
                    302: 
1.148     brouard   303:   Revision 1.147  2014/06/16 10:33:11  brouard
                    304:   *** empty log message ***
                    305: 
1.147     brouard   306:   Revision 1.146  2014/06/16 10:20:28  brouard
                    307:   Summary: Merge
                    308:   Author: Brouard
                    309: 
                    310:   Merge, before building revised version.
                    311: 
1.146     brouard   312:   Revision 1.145  2014/06/10 21:23:15  brouard
                    313:   Summary: Debugging with valgrind
                    314:   Author: Nicolas Brouard
                    315: 
                    316:   Lot of changes in order to output the results with some covariates
                    317:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    318:   improve the code.
                    319:   No more memory valgrind error but a lot has to be done in order to
                    320:   continue the work of splitting the code into subroutines.
                    321:   Also, decodemodel has been improved. Tricode is still not
                    322:   optimal. nbcode should be improved. Documentation has been added in
                    323:   the source code.
                    324: 
1.144     brouard   325:   Revision 1.143  2014/01/26 09:45:38  brouard
                    326:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    327: 
                    328:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    329:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    330: 
1.143     brouard   331:   Revision 1.142  2014/01/26 03:57:36  brouard
                    332:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    333: 
                    334:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    335: 
1.142     brouard   336:   Revision 1.141  2014/01/26 02:42:01  brouard
                    337:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    338: 
1.141     brouard   339:   Revision 1.140  2011/09/02 10:37:54  brouard
                    340:   Summary: times.h is ok with mingw32 now.
                    341: 
1.140     brouard   342:   Revision 1.139  2010/06/14 07:50:17  brouard
                    343:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    344:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    345: 
1.139     brouard   346:   Revision 1.138  2010/04/30 18:19:40  brouard
                    347:   *** empty log message ***
                    348: 
1.138     brouard   349:   Revision 1.137  2010/04/29 18:11:38  brouard
                    350:   (Module): Checking covariates for more complex models
                    351:   than V1+V2. A lot of change to be done. Unstable.
                    352: 
1.137     brouard   353:   Revision 1.136  2010/04/26 20:30:53  brouard
                    354:   (Module): merging some libgsl code. Fixing computation
                    355:   of likelione (using inter/intrapolation if mle = 0) in order to
                    356:   get same likelihood as if mle=1.
                    357:   Some cleaning of code and comments added.
                    358: 
1.136     brouard   359:   Revision 1.135  2009/10/29 15:33:14  brouard
                    360:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    361: 
1.135     brouard   362:   Revision 1.134  2009/10/29 13:18:53  brouard
                    363:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    364: 
1.134     brouard   365:   Revision 1.133  2009/07/06 10:21:25  brouard
                    366:   just nforces
                    367: 
1.133     brouard   368:   Revision 1.132  2009/07/06 08:22:05  brouard
                    369:   Many tings
                    370: 
1.132     brouard   371:   Revision 1.131  2009/06/20 16:22:47  brouard
                    372:   Some dimensions resccaled
                    373: 
1.131     brouard   374:   Revision 1.130  2009/05/26 06:44:34  brouard
                    375:   (Module): Max Covariate is now set to 20 instead of 8. A
                    376:   lot of cleaning with variables initialized to 0. Trying to make
                    377:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    378: 
1.130     brouard   379:   Revision 1.129  2007/08/31 13:49:27  lievre
                    380:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    381: 
1.129     lievre    382:   Revision 1.128  2006/06/30 13:02:05  brouard
                    383:   (Module): Clarifications on computing e.j
                    384: 
1.128     brouard   385:   Revision 1.127  2006/04/28 18:11:50  brouard
                    386:   (Module): Yes the sum of survivors was wrong since
                    387:   imach-114 because nhstepm was no more computed in the age
                    388:   loop. Now we define nhstepma in the age loop.
                    389:   (Module): In order to speed up (in case of numerous covariates) we
                    390:   compute health expectancies (without variances) in a first step
                    391:   and then all the health expectancies with variances or standard
                    392:   deviation (needs data from the Hessian matrices) which slows the
                    393:   computation.
                    394:   In the future we should be able to stop the program is only health
                    395:   expectancies and graph are needed without standard deviations.
                    396: 
1.127     brouard   397:   Revision 1.126  2006/04/28 17:23:28  brouard
                    398:   (Module): Yes the sum of survivors was wrong since
                    399:   imach-114 because nhstepm was no more computed in the age
                    400:   loop. Now we define nhstepma in the age loop.
                    401:   Version 0.98h
                    402: 
1.126     brouard   403:   Revision 1.125  2006/04/04 15:20:31  lievre
                    404:   Errors in calculation of health expectancies. Age was not initialized.
                    405:   Forecasting file added.
                    406: 
                    407:   Revision 1.124  2006/03/22 17:13:53  lievre
                    408:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    409:   The log-likelihood is printed in the log file
                    410: 
                    411:   Revision 1.123  2006/03/20 10:52:43  brouard
                    412:   * imach.c (Module): <title> changed, corresponds to .htm file
                    413:   name. <head> headers where missing.
                    414: 
                    415:   * imach.c (Module): Weights can have a decimal point as for
                    416:   English (a comma might work with a correct LC_NUMERIC environment,
                    417:   otherwise the weight is truncated).
                    418:   Modification of warning when the covariates values are not 0 or
                    419:   1.
                    420:   Version 0.98g
                    421: 
                    422:   Revision 1.122  2006/03/20 09:45:41  brouard
                    423:   (Module): Weights can have a decimal point as for
                    424:   English (a comma might work with a correct LC_NUMERIC environment,
                    425:   otherwise the weight is truncated).
                    426:   Modification of warning when the covariates values are not 0 or
                    427:   1.
                    428:   Version 0.98g
                    429: 
                    430:   Revision 1.121  2006/03/16 17:45:01  lievre
                    431:   * imach.c (Module): Comments concerning covariates added
                    432: 
                    433:   * imach.c (Module): refinements in the computation of lli if
                    434:   status=-2 in order to have more reliable computation if stepm is
                    435:   not 1 month. Version 0.98f
                    436: 
                    437:   Revision 1.120  2006/03/16 15:10:38  lievre
                    438:   (Module): refinements in the computation of lli if
                    439:   status=-2 in order to have more reliable computation if stepm is
                    440:   not 1 month. Version 0.98f
                    441: 
                    442:   Revision 1.119  2006/03/15 17:42:26  brouard
                    443:   (Module): Bug if status = -2, the loglikelihood was
                    444:   computed as likelihood omitting the logarithm. Version O.98e
                    445: 
                    446:   Revision 1.118  2006/03/14 18:20:07  brouard
                    447:   (Module): varevsij Comments added explaining the second
                    448:   table of variances if popbased=1 .
                    449:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    450:   (Module): Function pstamp added
                    451:   (Module): Version 0.98d
                    452: 
                    453:   Revision 1.117  2006/03/14 17:16:22  brouard
                    454:   (Module): varevsij Comments added explaining the second
                    455:   table of variances if popbased=1 .
                    456:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    457:   (Module): Function pstamp added
                    458:   (Module): Version 0.98d
                    459: 
                    460:   Revision 1.116  2006/03/06 10:29:27  brouard
                    461:   (Module): Variance-covariance wrong links and
                    462:   varian-covariance of ej. is needed (Saito).
                    463: 
                    464:   Revision 1.115  2006/02/27 12:17:45  brouard
                    465:   (Module): One freematrix added in mlikeli! 0.98c
                    466: 
                    467:   Revision 1.114  2006/02/26 12:57:58  brouard
                    468:   (Module): Some improvements in processing parameter
                    469:   filename with strsep.
                    470: 
                    471:   Revision 1.113  2006/02/24 14:20:24  brouard
                    472:   (Module): Memory leaks checks with valgrind and:
                    473:   datafile was not closed, some imatrix were not freed and on matrix
                    474:   allocation too.
                    475: 
                    476:   Revision 1.112  2006/01/30 09:55:26  brouard
                    477:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    478: 
                    479:   Revision 1.111  2006/01/25 20:38:18  brouard
                    480:   (Module): Lots of cleaning and bugs added (Gompertz)
                    481:   (Module): Comments can be added in data file. Missing date values
                    482:   can be a simple dot '.'.
                    483: 
                    484:   Revision 1.110  2006/01/25 00:51:50  brouard
                    485:   (Module): Lots of cleaning and bugs added (Gompertz)
                    486: 
                    487:   Revision 1.109  2006/01/24 19:37:15  brouard
                    488:   (Module): Comments (lines starting with a #) are allowed in data.
                    489: 
                    490:   Revision 1.108  2006/01/19 18:05:42  lievre
                    491:   Gnuplot problem appeared...
                    492:   To be fixed
                    493: 
                    494:   Revision 1.107  2006/01/19 16:20:37  brouard
                    495:   Test existence of gnuplot in imach path
                    496: 
                    497:   Revision 1.106  2006/01/19 13:24:36  brouard
                    498:   Some cleaning and links added in html output
                    499: 
                    500:   Revision 1.105  2006/01/05 20:23:19  lievre
                    501:   *** empty log message ***
                    502: 
                    503:   Revision 1.104  2005/09/30 16:11:43  lievre
                    504:   (Module): sump fixed, loop imx fixed, and simplifications.
                    505:   (Module): If the status is missing at the last wave but we know
                    506:   that the person is alive, then we can code his/her status as -2
                    507:   (instead of missing=-1 in earlier versions) and his/her
                    508:   contributions to the likelihood is 1 - Prob of dying from last
                    509:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    510:   the healthy state at last known wave). Version is 0.98
                    511: 
                    512:   Revision 1.103  2005/09/30 15:54:49  lievre
                    513:   (Module): sump fixed, loop imx fixed, and simplifications.
                    514: 
                    515:   Revision 1.102  2004/09/15 17:31:30  brouard
                    516:   Add the possibility to read data file including tab characters.
                    517: 
                    518:   Revision 1.101  2004/09/15 10:38:38  brouard
                    519:   Fix on curr_time
                    520: 
                    521:   Revision 1.100  2004/07/12 18:29:06  brouard
                    522:   Add version for Mac OS X. Just define UNIX in Makefile
                    523: 
                    524:   Revision 1.99  2004/06/05 08:57:40  brouard
                    525:   *** empty log message ***
                    526: 
                    527:   Revision 1.98  2004/05/16 15:05:56  brouard
                    528:   New version 0.97 . First attempt to estimate force of mortality
                    529:   directly from the data i.e. without the need of knowing the health
                    530:   state at each age, but using a Gompertz model: log u =a + b*age .
                    531:   This is the basic analysis of mortality and should be done before any
                    532:   other analysis, in order to test if the mortality estimated from the
                    533:   cross-longitudinal survey is different from the mortality estimated
                    534:   from other sources like vital statistic data.
                    535: 
                    536:   The same imach parameter file can be used but the option for mle should be -3.
                    537: 
1.133     brouard   538:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   539:   former routines in order to include the new code within the former code.
                    540: 
                    541:   The output is very simple: only an estimate of the intercept and of
                    542:   the slope with 95% confident intervals.
                    543: 
                    544:   Current limitations:
                    545:   A) Even if you enter covariates, i.e. with the
                    546:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    547:   B) There is no computation of Life Expectancy nor Life Table.
                    548: 
                    549:   Revision 1.97  2004/02/20 13:25:42  lievre
                    550:   Version 0.96d. Population forecasting command line is (temporarily)
                    551:   suppressed.
                    552: 
                    553:   Revision 1.96  2003/07/15 15:38:55  brouard
                    554:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    555:   rewritten within the same printf. Workaround: many printfs.
                    556: 
                    557:   Revision 1.95  2003/07/08 07:54:34  brouard
                    558:   * imach.c (Repository):
                    559:   (Repository): Using imachwizard code to output a more meaningful covariance
                    560:   matrix (cov(a12,c31) instead of numbers.
                    561: 
                    562:   Revision 1.94  2003/06/27 13:00:02  brouard
                    563:   Just cleaning
                    564: 
                    565:   Revision 1.93  2003/06/25 16:33:55  brouard
                    566:   (Module): On windows (cygwin) function asctime_r doesn't
                    567:   exist so I changed back to asctime which exists.
                    568:   (Module): Version 0.96b
                    569: 
                    570:   Revision 1.92  2003/06/25 16:30:45  brouard
                    571:   (Module): On windows (cygwin) function asctime_r doesn't
                    572:   exist so I changed back to asctime which exists.
                    573: 
                    574:   Revision 1.91  2003/06/25 15:30:29  brouard
                    575:   * imach.c (Repository): Duplicated warning errors corrected.
                    576:   (Repository): Elapsed time after each iteration is now output. It
                    577:   helps to forecast when convergence will be reached. Elapsed time
                    578:   is stamped in powell.  We created a new html file for the graphs
                    579:   concerning matrix of covariance. It has extension -cov.htm.
                    580: 
                    581:   Revision 1.90  2003/06/24 12:34:15  brouard
                    582:   (Module): Some bugs corrected for windows. Also, when
                    583:   mle=-1 a template is output in file "or"mypar.txt with the design
                    584:   of the covariance matrix to be input.
                    585: 
                    586:   Revision 1.89  2003/06/24 12:30:52  brouard
                    587:   (Module): Some bugs corrected for windows. Also, when
                    588:   mle=-1 a template is output in file "or"mypar.txt with the design
                    589:   of the covariance matrix to be input.
                    590: 
                    591:   Revision 1.88  2003/06/23 17:54:56  brouard
                    592:   * 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.
                    593: 
                    594:   Revision 1.87  2003/06/18 12:26:01  brouard
                    595:   Version 0.96
                    596: 
                    597:   Revision 1.86  2003/06/17 20:04:08  brouard
                    598:   (Module): Change position of html and gnuplot routines and added
                    599:   routine fileappend.
                    600: 
                    601:   Revision 1.85  2003/06/17 13:12:43  brouard
                    602:   * imach.c (Repository): Check when date of death was earlier that
                    603:   current date of interview. It may happen when the death was just
                    604:   prior to the death. In this case, dh was negative and likelihood
                    605:   was wrong (infinity). We still send an "Error" but patch by
                    606:   assuming that the date of death was just one stepm after the
                    607:   interview.
                    608:   (Repository): Because some people have very long ID (first column)
                    609:   we changed int to long in num[] and we added a new lvector for
                    610:   memory allocation. But we also truncated to 8 characters (left
                    611:   truncation)
                    612:   (Repository): No more line truncation errors.
                    613: 
                    614:   Revision 1.84  2003/06/13 21:44:43  brouard
                    615:   * imach.c (Repository): Replace "freqsummary" at a correct
                    616:   place. It differs from routine "prevalence" which may be called
                    617:   many times. Probs is memory consuming and must be used with
                    618:   parcimony.
                    619:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    620: 
                    621:   Revision 1.83  2003/06/10 13:39:11  lievre
                    622:   *** empty log message ***
                    623: 
                    624:   Revision 1.82  2003/06/05 15:57:20  brouard
                    625:   Add log in  imach.c and  fullversion number is now printed.
                    626: 
                    627: */
                    628: /*
                    629:    Interpolated Markov Chain
                    630: 
                    631:   Short summary of the programme:
                    632:   
                    633:   This program computes Healthy Life Expectancies from
                    634:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
                    635:   first survey ("cross") where individuals from different ages are
                    636:   interviewed on their health status or degree of disability (in the
                    637:   case of a health survey which is our main interest) -2- at least a
                    638:   second wave of interviews ("longitudinal") which measure each change
                    639:   (if any) in individual health status.  Health expectancies are
                    640:   computed from the time spent in each health state according to a
                    641:   model. More health states you consider, more time is necessary to reach the
                    642:   Maximum Likelihood of the parameters involved in the model.  The
                    643:   simplest model is the multinomial logistic model where pij is the
                    644:   probability to be observed in state j at the second wave
                    645:   conditional to be observed in state i at the first wave. Therefore
                    646:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
                    647:   'age' is age and 'sex' is a covariate. If you want to have a more
                    648:   complex model than "constant and age", you should modify the program
                    649:   where the markup *Covariates have to be included here again* invites
                    650:   you to do it.  More covariates you add, slower the
                    651:   convergence.
                    652: 
                    653:   The advantage of this computer programme, compared to a simple
                    654:   multinomial logistic model, is clear when the delay between waves is not
                    655:   identical for each individual. Also, if a individual missed an
                    656:   intermediate interview, the information is lost, but taken into
                    657:   account using an interpolation or extrapolation.  
                    658: 
                    659:   hPijx is the probability to be observed in state i at age x+h
                    660:   conditional to the observed state i at age x. The delay 'h' can be
                    661:   split into an exact number (nh*stepm) of unobserved intermediate
                    662:   states. This elementary transition (by month, quarter,
                    663:   semester or year) is modelled as a multinomial logistic.  The hPx
                    664:   matrix is simply the matrix product of nh*stepm elementary matrices
                    665:   and the contribution of each individual to the likelihood is simply
                    666:   hPijx.
                    667: 
                    668:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard   669:   of the life expectancies. It also computes the period (stable) prevalence.
                    670: 
                    671: Back prevalence and projections:
                    672:  - 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)
                    673:     Computes the back prevalence limit  for any combination    of covariate values k
                    674:     at any age between ageminpar and agemaxpar and returns it in **bprlim. In the loops,
                    675:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm, **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                    676:  - hBijx Back Probability to be in state i at age x-h being in j at x
                    677:    Computes for any combination of covariates k and any age between bage and fage 
                    678:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                    679:                        oldm=oldms;savm=savms;
                    680:         - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
                    681:      Computes the transition matrix starting at age 'age' over
                    682:      'nhstepm*hstepm*stepm' months (i.e. until
                    683:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                    684:      nhstepm*hstepm matrices. Returns p3mat[i][j][h] after calling 
                    685:      p3mat[i][j][h]=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\
                    686:                                                                         1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
                    687: 
1.133     brouard   688:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    689:            Institut national d'études démographiques, Paris.
1.126     brouard   690:   This software have been partly granted by Euro-REVES, a concerted action
                    691:   from the European Union.
                    692:   It is copyrighted identically to a GNU software product, ie programme and
                    693:   software can be distributed freely for non commercial use. Latest version
                    694:   can be accessed at http://euroreves.ined.fr/imach .
                    695: 
                    696:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    697:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    698:   
                    699:   **********************************************************************/
                    700: /*
                    701:   main
                    702:   read parameterfile
                    703:   read datafile
                    704:   concatwav
                    705:   freqsummary
                    706:   if (mle >= 1)
                    707:     mlikeli
                    708:   print results files
                    709:   if mle==1 
                    710:      computes hessian
                    711:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    712:       begin-prev-date,...
                    713:   open gnuplot file
                    714:   open html file
1.145     brouard   715:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    716:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    717:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    718:     freexexit2 possible for memory heap.
                    719: 
                    720:   h Pij x                         | pij_nom  ficrestpij
                    721:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    722:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    723:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    724: 
                    725:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    726:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    727:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    728:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    729:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    730: 
1.126     brouard   731:   forecasting if prevfcast==1 prevforecast call prevalence()
                    732:   health expectancies
                    733:   Variance-covariance of DFLE
                    734:   prevalence()
                    735:    movingaverage()
                    736:   varevsij() 
                    737:   if popbased==1 varevsij(,popbased)
                    738:   total life expectancies
                    739:   Variance of period (stable) prevalence
                    740:  end
                    741: */
                    742: 
1.187     brouard   743: /* #define DEBUG */
                    744: /* #define DEBUGBRENT */
1.203     brouard   745: /* #define DEBUGLINMIN */
                    746: /* #define DEBUGHESS */
                    747: #define DEBUGHESSIJ
1.224   ! brouard   748: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard   749: #define POWELL /* Instead of NLOPT */
1.224   ! brouard   750: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard   751: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                    752: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard   753: 
                    754: #include <math.h>
                    755: #include <stdio.h>
                    756: #include <stdlib.h>
                    757: #include <string.h>
1.159     brouard   758: 
                    759: #ifdef _WIN32
                    760: #include <io.h>
1.172     brouard   761: #include <windows.h>
                    762: #include <tchar.h>
1.159     brouard   763: #else
1.126     brouard   764: #include <unistd.h>
1.159     brouard   765: #endif
1.126     brouard   766: 
                    767: #include <limits.h>
                    768: #include <sys/types.h>
1.171     brouard   769: 
                    770: #if defined(__GNUC__)
                    771: #include <sys/utsname.h> /* Doesn't work on Windows */
                    772: #endif
                    773: 
1.126     brouard   774: #include <sys/stat.h>
                    775: #include <errno.h>
1.159     brouard   776: /* extern int errno; */
1.126     brouard   777: 
1.157     brouard   778: /* #ifdef LINUX */
                    779: /* #include <time.h> */
                    780: /* #include "timeval.h" */
                    781: /* #else */
                    782: /* #include <sys/time.h> */
                    783: /* #endif */
                    784: 
1.126     brouard   785: #include <time.h>
                    786: 
1.136     brouard   787: #ifdef GSL
                    788: #include <gsl/gsl_errno.h>
                    789: #include <gsl/gsl_multimin.h>
                    790: #endif
                    791: 
1.167     brouard   792: 
1.162     brouard   793: #ifdef NLOPT
                    794: #include <nlopt.h>
                    795: typedef struct {
                    796:   double (* function)(double [] );
                    797: } myfunc_data ;
                    798: #endif
                    799: 
1.126     brouard   800: /* #include <libintl.h> */
                    801: /* #define _(String) gettext (String) */
                    802: 
1.141     brouard   803: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   804: 
                    805: #define GNUPLOTPROGRAM "gnuplot"
                    806: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    807: #define FILENAMELENGTH 132
                    808: 
                    809: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    810: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    811: 
1.144     brouard   812: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    813: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   814: 
                    815: #define NINTERVMAX 8
1.144     brouard   816: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    817: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    818: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197     brouard   819: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard   820: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                    821: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.126     brouard   822: #define MAXN 20000
1.144     brouard   823: #define YEARM 12. /**< Number of months per year */
1.218     brouard   824: /* #define AGESUP 130 */
                    825: #define AGESUP 150
                    826: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard   827: #define AGEBASE 40
1.194     brouard   828: #define AGEOVERFLOW 1.e20
1.164     brouard   829: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard   830: #ifdef _WIN32
                    831: #define DIRSEPARATOR '\\'
                    832: #define CHARSEPARATOR "\\"
                    833: #define ODIRSEPARATOR '/'
                    834: #else
1.126     brouard   835: #define DIRSEPARATOR '/'
                    836: #define CHARSEPARATOR "/"
                    837: #define ODIRSEPARATOR '\\'
                    838: #endif
                    839: 
1.224   ! brouard   840: /* $Id: imach.c,v 1.223 2016/02/19 09:23:35 brouard Exp $ */
1.126     brouard   841: /* $State: Exp $ */
1.196     brouard   842: #include "version.h"
                    843: char version[]=__IMACH_VERSION__;
1.224   ! brouard   844: 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";
        !           845: char fullversion[]="$Revision: 1.223 $ $Date: 2016/02/19 09:23:35 $"; 
1.126     brouard   846: char strstart[80];
                    847: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   848: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard   849: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard   850: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    851: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    852: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
                    853: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
                    854: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    855: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    856: int cptcoveff=0; /* Total number of covariates to vary for printing results */
1.224   ! brouard   857: int ncoveff=0; /* Total number of effective covariates in the model */
        !           858: int nqveff=0; /**< nqveff number of effective quantitative variables */
        !           859: int ntveff=0; /**< ntveff number of effective time varying variables */
        !           860: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard   861: int cptcov=0; /* Working variable */
1.218     brouard   862: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.126     brouard   863: int npar=NPARMAX;
                    864: int nlstate=2; /* Number of live states */
                    865: int ndeath=1; /* Number of dead states */
1.130     brouard   866: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.223     brouard   867: int  nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable */ 
1.126     brouard   868: int popbased=0;
                    869: 
                    870: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard   871: int maxwav=0; /* Maxim number of waves */
                    872: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    873: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    874: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard   875:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard   876: int mle=1, weightopt=0;
1.126     brouard   877: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    878: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    879: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    880:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard   881: int countcallfunc=0;  /* Count the number of calls to func */
1.130     brouard   882: double jmean=1; /* Mean space between 2 waves */
1.145     brouard   883: double **matprod2(); /* test */
1.126     brouard   884: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    885: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard   886: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                    887: 
1.136     brouard   888: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard   889: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard   890: FILE *ficlog, *ficrespow;
1.130     brouard   891: int globpr=0; /* Global variable for printing or not */
1.126     brouard   892: double fretone; /* Only one call to likelihood */
1.130     brouard   893: long ipmx=0; /* Number of contributions */
1.126     brouard   894: double sw; /* Sum of weights */
                    895: char filerespow[FILENAMELENGTH];
                    896: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                    897: FILE *ficresilk;
                    898: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                    899: FILE *ficresprobmorprev;
                    900: FILE *fichtm, *fichtmcov; /* Html File */
                    901: FILE *ficreseij;
                    902: char filerese[FILENAMELENGTH];
                    903: FILE *ficresstdeij;
                    904: char fileresstde[FILENAMELENGTH];
                    905: FILE *ficrescveij;
                    906: char filerescve[FILENAMELENGTH];
                    907: FILE  *ficresvij;
                    908: char fileresv[FILENAMELENGTH];
                    909: FILE  *ficresvpl;
                    910: char fileresvpl[FILENAMELENGTH];
                    911: char title[MAXLINE];
1.217     brouard   912: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard   913: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                    914: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                    915: char command[FILENAMELENGTH];
                    916: int  outcmd=0;
                    917: 
1.217     brouard   918: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard   919: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard   920: char filelog[FILENAMELENGTH]; /* Log file */
                    921: char filerest[FILENAMELENGTH];
                    922: char fileregp[FILENAMELENGTH];
                    923: char popfile[FILENAMELENGTH];
                    924: 
                    925: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                    926: 
1.157     brouard   927: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                    928: /* struct timezone tzp; */
                    929: /* extern int gettimeofday(); */
                    930: struct tm tml, *gmtime(), *localtime();
                    931: 
                    932: extern time_t time();
                    933: 
                    934: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                    935: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                    936: struct tm tm;
                    937: 
1.126     brouard   938: char strcurr[80], strfor[80];
                    939: 
                    940: char *endptr;
                    941: long lval;
                    942: double dval;
                    943: 
                    944: #define NR_END 1
                    945: #define FREE_ARG char*
                    946: #define FTOL 1.0e-10
                    947: 
                    948: #define NRANSI 
                    949: #define ITMAX 200 
                    950: 
                    951: #define TOL 2.0e-4 
                    952: 
                    953: #define CGOLD 0.3819660 
                    954: #define ZEPS 1.0e-10 
                    955: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                    956: 
                    957: #define GOLD 1.618034 
                    958: #define GLIMIT 100.0 
                    959: #define TINY 1.0e-20 
                    960: 
                    961: static double maxarg1,maxarg2;
                    962: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                    963: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                    964:   
                    965: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                    966: #define rint(a) floor(a+0.5)
1.166     brouard   967: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard   968: #define mytinydouble 1.0e-16
1.166     brouard   969: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                    970: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                    971: /* static double dsqrarg; */
                    972: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard   973: static double sqrarg;
                    974: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                    975: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                    976: int agegomp= AGEGOMP;
                    977: 
                    978: int imx; 
                    979: int stepm=1;
                    980: /* Stepm, step in month: minimum step interpolation*/
                    981: 
                    982: int estepm;
                    983: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                    984: 
                    985: int m,nb;
                    986: long *num;
1.197     brouard   987: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard   988: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                    989:                   covariate for which somebody answered excluding 
                    990:                   undefined. Usually 2: 0 and 1. */
                    991: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                    992:                             covariate for which somebody answered including 
                    993:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard   994: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard   995: double **pmmij, ***probs; /* Global pointer */
1.219     brouard   996: double ***mobaverage, ***mobaverages; /* New global variable */
1.126     brouard   997: double *ageexmed,*agecens;
                    998: double dateintmean=0;
                    999: 
                   1000: double *weight;
                   1001: int **s; /* Status */
1.141     brouard  1002: double *agedc;
1.145     brouard  1003: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1004:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1005:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.224   ! brouard  1006: double **coqvar; /* Fixed quantitative covariate */
1.223     brouard  1007: double ***cotvar; /* Time varying covariate */
                   1008: double ***cotqvar; /* Time varying quantitative covariate */
1.141     brouard  1009: double  idx; 
                   1010: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.197     brouard  1011: int *Tage;
1.145     brouard  1012: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1013: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.220     brouard  1014: int **Tvard, *Tprod, cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1015: double *lsurv, *lpop, *tpop;
                   1016: 
1.143     brouard  1017: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1018: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1019: 
                   1020: /**************** split *************************/
                   1021: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1022: {
                   1023:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1024:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1025:   */ 
                   1026:   char *ss;                            /* pointer */
1.186     brouard  1027:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1028: 
                   1029:   l1 = strlen(path );                  /* length of path */
                   1030:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1031:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1032:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1033:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1034:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1035:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1036:     /* get current working directory */
                   1037:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1038: #ifdef WIN32
                   1039:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1040: #else
                   1041:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1042: #endif
1.126     brouard  1043:       return( GLOCK_ERROR_GETCWD );
                   1044:     }
                   1045:     /* got dirc from getcwd*/
                   1046:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1047:   } else {                             /* strip directory from path */
1.126     brouard  1048:     ss++;                              /* after this, the filename */
                   1049:     l2 = strlen( ss );                 /* length of filename */
                   1050:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1051:     strcpy( name, ss );                /* save file name */
                   1052:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1053:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1054:     printf(" DIRC2 = %s \n",dirc);
                   1055:   }
                   1056:   /* We add a separator at the end of dirc if not exists */
                   1057:   l1 = strlen( dirc );                 /* length of directory */
                   1058:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1059:     dirc[l1] =  DIRSEPARATOR;
                   1060:     dirc[l1+1] = 0; 
                   1061:     printf(" DIRC3 = %s \n",dirc);
                   1062:   }
                   1063:   ss = strrchr( name, '.' );           /* find last / */
                   1064:   if (ss >0){
                   1065:     ss++;
                   1066:     strcpy(ext,ss);                    /* save extension */
                   1067:     l1= strlen( name);
                   1068:     l2= strlen(ss)+1;
                   1069:     strncpy( finame, name, l1-l2);
                   1070:     finame[l1-l2]= 0;
                   1071:   }
                   1072: 
                   1073:   return( 0 );                         /* we're done */
                   1074: }
                   1075: 
                   1076: 
                   1077: /******************************************/
                   1078: 
                   1079: void replace_back_to_slash(char *s, char*t)
                   1080: {
                   1081:   int i;
                   1082:   int lg=0;
                   1083:   i=0;
                   1084:   lg=strlen(t);
                   1085:   for(i=0; i<= lg; i++) {
                   1086:     (s[i] = t[i]);
                   1087:     if (t[i]== '\\') s[i]='/';
                   1088:   }
                   1089: }
                   1090: 
1.132     brouard  1091: char *trimbb(char *out, char *in)
1.137     brouard  1092: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1093:   char *s;
                   1094:   s=out;
                   1095:   while (*in != '\0'){
1.137     brouard  1096:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1097:       in++;
                   1098:     }
                   1099:     *out++ = *in++;
                   1100:   }
                   1101:   *out='\0';
                   1102:   return s;
                   1103: }
                   1104: 
1.187     brouard  1105: /* char *substrchaine(char *out, char *in, char *chain) */
                   1106: /* { */
                   1107: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1108: /*   char *s, *t; */
                   1109: /*   t=in;s=out; */
                   1110: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1111: /*     *out++ = *in++; */
                   1112: /*   } */
                   1113: 
                   1114: /*   /\* *in matches *chain *\/ */
                   1115: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1116: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1117: /*   } */
                   1118: /*   in--; chain--; */
                   1119: /*   while ( (*in != '\0')){ */
                   1120: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1121: /*     *out++ = *in++; */
                   1122: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1123: /*   } */
                   1124: /*   *out='\0'; */
                   1125: /*   out=s; */
                   1126: /*   return out; */
                   1127: /* } */
                   1128: char *substrchaine(char *out, char *in, char *chain)
                   1129: {
                   1130:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1131:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1132: 
                   1133:   char *strloc;
                   1134: 
                   1135:   strcpy (out, in); 
                   1136:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1137:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1138:   if(strloc != NULL){ 
                   1139:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1140:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1141:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1142:   }
                   1143:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1144:   return out;
                   1145: }
                   1146: 
                   1147: 
1.145     brouard  1148: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1149: {
1.187     brouard  1150:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1151:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187     brouard  1152:      gives blocc="abcdef" and alocc="ghi2j".
1.145     brouard  1153:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1154:   */
1.160     brouard  1155:   char *s, *t;
1.145     brouard  1156:   t=in;s=in;
                   1157:   while ((*in != occ) && (*in != '\0')){
                   1158:     *alocc++ = *in++;
                   1159:   }
                   1160:   if( *in == occ){
                   1161:     *(alocc)='\0';
                   1162:     s=++in;
                   1163:   }
                   1164:  
                   1165:   if (s == t) {/* occ not found */
                   1166:     *(alocc-(in-s))='\0';
                   1167:     in=s;
                   1168:   }
                   1169:   while ( *in != '\0'){
                   1170:     *blocc++ = *in++;
                   1171:   }
                   1172: 
                   1173:   *blocc='\0';
                   1174:   return t;
                   1175: }
1.137     brouard  1176: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1177: {
1.187     brouard  1178:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1179:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1180:      gives blocc="abcdef2ghi" and alocc="j".
                   1181:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1182:   */
                   1183:   char *s, *t;
                   1184:   t=in;s=in;
                   1185:   while (*in != '\0'){
                   1186:     while( *in == occ){
                   1187:       *blocc++ = *in++;
                   1188:       s=in;
                   1189:     }
                   1190:     *blocc++ = *in++;
                   1191:   }
                   1192:   if (s == t) /* occ not found */
                   1193:     *(blocc-(in-s))='\0';
                   1194:   else
                   1195:     *(blocc-(in-s)-1)='\0';
                   1196:   in=s;
                   1197:   while ( *in != '\0'){
                   1198:     *alocc++ = *in++;
                   1199:   }
                   1200: 
                   1201:   *alocc='\0';
                   1202:   return s;
                   1203: }
                   1204: 
1.126     brouard  1205: int nbocc(char *s, char occ)
                   1206: {
                   1207:   int i,j=0;
                   1208:   int lg=20;
                   1209:   i=0;
                   1210:   lg=strlen(s);
                   1211:   for(i=0; i<= lg; i++) {
                   1212:   if  (s[i] == occ ) j++;
                   1213:   }
                   1214:   return j;
                   1215: }
                   1216: 
1.137     brouard  1217: /* void cutv(char *u,char *v, char*t, char occ) */
                   1218: /* { */
                   1219: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1220: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1221: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1222: /*   int i,lg,j,p=0; */
                   1223: /*   i=0; */
                   1224: /*   lg=strlen(t); */
                   1225: /*   for(j=0; j<=lg-1; j++) { */
                   1226: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1227: /*   } */
1.126     brouard  1228: 
1.137     brouard  1229: /*   for(j=0; j<p; j++) { */
                   1230: /*     (u[j] = t[j]); */
                   1231: /*   } */
                   1232: /*      u[p]='\0'; */
1.126     brouard  1233: 
1.137     brouard  1234: /*    for(j=0; j<= lg; j++) { */
                   1235: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1236: /*   } */
                   1237: /* } */
1.126     brouard  1238: 
1.160     brouard  1239: #ifdef _WIN32
                   1240: char * strsep(char **pp, const char *delim)
                   1241: {
                   1242:   char *p, *q;
                   1243:          
                   1244:   if ((p = *pp) == NULL)
                   1245:     return 0;
                   1246:   if ((q = strpbrk (p, delim)) != NULL)
                   1247:   {
                   1248:     *pp = q + 1;
                   1249:     *q = '\0';
                   1250:   }
                   1251:   else
                   1252:     *pp = 0;
                   1253:   return p;
                   1254: }
                   1255: #endif
                   1256: 
1.126     brouard  1257: /********************** nrerror ********************/
                   1258: 
                   1259: void nrerror(char error_text[])
                   1260: {
                   1261:   fprintf(stderr,"ERREUR ...\n");
                   1262:   fprintf(stderr,"%s\n",error_text);
                   1263:   exit(EXIT_FAILURE);
                   1264: }
                   1265: /*********************** vector *******************/
                   1266: double *vector(int nl, int nh)
                   1267: {
                   1268:   double *v;
                   1269:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1270:   if (!v) nrerror("allocation failure in vector");
                   1271:   return v-nl+NR_END;
                   1272: }
                   1273: 
                   1274: /************************ free vector ******************/
                   1275: void free_vector(double*v, int nl, int nh)
                   1276: {
                   1277:   free((FREE_ARG)(v+nl-NR_END));
                   1278: }
                   1279: 
                   1280: /************************ivector *******************************/
                   1281: int *ivector(long nl,long nh)
                   1282: {
                   1283:   int *v;
                   1284:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1285:   if (!v) nrerror("allocation failure in ivector");
                   1286:   return v-nl+NR_END;
                   1287: }
                   1288: 
                   1289: /******************free ivector **************************/
                   1290: void free_ivector(int *v, long nl, long nh)
                   1291: {
                   1292:   free((FREE_ARG)(v+nl-NR_END));
                   1293: }
                   1294: 
                   1295: /************************lvector *******************************/
                   1296: long *lvector(long nl,long nh)
                   1297: {
                   1298:   long *v;
                   1299:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1300:   if (!v) nrerror("allocation failure in ivector");
                   1301:   return v-nl+NR_END;
                   1302: }
                   1303: 
                   1304: /******************free lvector **************************/
                   1305: void free_lvector(long *v, long nl, long nh)
                   1306: {
                   1307:   free((FREE_ARG)(v+nl-NR_END));
                   1308: }
                   1309: 
                   1310: /******************* imatrix *******************************/
                   1311: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1312:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1313: { 
                   1314:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1315:   int **m; 
                   1316:   
                   1317:   /* allocate pointers to rows */ 
                   1318:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1319:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1320:   m += NR_END; 
                   1321:   m -= nrl; 
                   1322:   
                   1323:   
                   1324:   /* allocate rows and set pointers to them */ 
                   1325:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1326:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1327:   m[nrl] += NR_END; 
                   1328:   m[nrl] -= ncl; 
                   1329:   
                   1330:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1331:   
                   1332:   /* return pointer to array of pointers to rows */ 
                   1333:   return m; 
                   1334: } 
                   1335: 
                   1336: /****************** free_imatrix *************************/
                   1337: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1338:       int **m;
                   1339:       long nch,ncl,nrh,nrl; 
                   1340:      /* free an int matrix allocated by imatrix() */ 
                   1341: { 
                   1342:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1343:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1344: } 
                   1345: 
                   1346: /******************* matrix *******************************/
                   1347: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1348: {
                   1349:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1350:   double **m;
                   1351: 
                   1352:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1353:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1354:   m += NR_END;
                   1355:   m -= nrl;
                   1356: 
                   1357:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1358:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1359:   m[nrl] += NR_END;
                   1360:   m[nrl] -= ncl;
                   1361: 
                   1362:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1363:   return m;
1.145     brouard  1364:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1365: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1366: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1367:    */
                   1368: }
                   1369: 
                   1370: /*************************free matrix ************************/
                   1371: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1372: {
                   1373:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1374:   free((FREE_ARG)(m+nrl-NR_END));
                   1375: }
                   1376: 
                   1377: /******************* ma3x *******************************/
                   1378: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1379: {
                   1380:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1381:   double ***m;
                   1382: 
                   1383:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1384:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1385:   m += NR_END;
                   1386:   m -= nrl;
                   1387: 
                   1388:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1389:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1390:   m[nrl] += NR_END;
                   1391:   m[nrl] -= ncl;
                   1392: 
                   1393:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1394: 
                   1395:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1396:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1397:   m[nrl][ncl] += NR_END;
                   1398:   m[nrl][ncl] -= nll;
                   1399:   for (j=ncl+1; j<=nch; j++) 
                   1400:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1401:   
                   1402:   for (i=nrl+1; i<=nrh; i++) {
                   1403:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1404:     for (j=ncl+1; j<=nch; j++) 
                   1405:       m[i][j]=m[i][j-1]+nlay;
                   1406:   }
                   1407:   return m; 
                   1408:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1409:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1410:   */
                   1411: }
                   1412: 
                   1413: /*************************free ma3x ************************/
                   1414: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1415: {
                   1416:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1417:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1418:   free((FREE_ARG)(m+nrl-NR_END));
                   1419: }
                   1420: 
                   1421: /*************** function subdirf ***********/
                   1422: char *subdirf(char fileres[])
                   1423: {
                   1424:   /* Caution optionfilefiname is hidden */
                   1425:   strcpy(tmpout,optionfilefiname);
                   1426:   strcat(tmpout,"/"); /* Add to the right */
                   1427:   strcat(tmpout,fileres);
                   1428:   return tmpout;
                   1429: }
                   1430: 
                   1431: /*************** function subdirf2 ***********/
                   1432: char *subdirf2(char fileres[], char *preop)
                   1433: {
                   1434:   
                   1435:   /* Caution optionfilefiname is hidden */
                   1436:   strcpy(tmpout,optionfilefiname);
                   1437:   strcat(tmpout,"/");
                   1438:   strcat(tmpout,preop);
                   1439:   strcat(tmpout,fileres);
                   1440:   return tmpout;
                   1441: }
                   1442: 
                   1443: /*************** function subdirf3 ***********/
                   1444: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1445: {
                   1446:   
                   1447:   /* Caution optionfilefiname is hidden */
                   1448:   strcpy(tmpout,optionfilefiname);
                   1449:   strcat(tmpout,"/");
                   1450:   strcat(tmpout,preop);
                   1451:   strcat(tmpout,preop2);
                   1452:   strcat(tmpout,fileres);
                   1453:   return tmpout;
                   1454: }
1.213     brouard  1455:  
                   1456: /*************** function subdirfext ***********/
                   1457: char *subdirfext(char fileres[], char *preop, char *postop)
                   1458: {
                   1459:   
                   1460:   strcpy(tmpout,preop);
                   1461:   strcat(tmpout,fileres);
                   1462:   strcat(tmpout,postop);
                   1463:   return tmpout;
                   1464: }
1.126     brouard  1465: 
1.213     brouard  1466: /*************** function subdirfext3 ***********/
                   1467: char *subdirfext3(char fileres[], char *preop, char *postop)
                   1468: {
                   1469:   
                   1470:   /* Caution optionfilefiname is hidden */
                   1471:   strcpy(tmpout,optionfilefiname);
                   1472:   strcat(tmpout,"/");
                   1473:   strcat(tmpout,preop);
                   1474:   strcat(tmpout,fileres);
                   1475:   strcat(tmpout,postop);
                   1476:   return tmpout;
                   1477: }
                   1478:  
1.162     brouard  1479: char *asc_diff_time(long time_sec, char ascdiff[])
                   1480: {
                   1481:   long sec_left, days, hours, minutes;
                   1482:   days = (time_sec) / (60*60*24);
                   1483:   sec_left = (time_sec) % (60*60*24);
                   1484:   hours = (sec_left) / (60*60) ;
                   1485:   sec_left = (sec_left) %(60*60);
                   1486:   minutes = (sec_left) /60;
                   1487:   sec_left = (sec_left) % (60);
                   1488:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1489:   return ascdiff;
                   1490: }
                   1491: 
1.126     brouard  1492: /***************** f1dim *************************/
                   1493: extern int ncom; 
                   1494: extern double *pcom,*xicom;
                   1495: extern double (*nrfunc)(double []); 
                   1496:  
                   1497: double f1dim(double x) 
                   1498: { 
                   1499:   int j; 
                   1500:   double f;
                   1501:   double *xt; 
                   1502:  
                   1503:   xt=vector(1,ncom); 
                   1504:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1505:   f=(*nrfunc)(xt); 
                   1506:   free_vector(xt,1,ncom); 
                   1507:   return f; 
                   1508: } 
                   1509: 
                   1510: /*****************brent *************************/
                   1511: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1512: {
                   1513:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1514:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1515:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1516:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1517:    * returned function value. 
                   1518:   */
1.126     brouard  1519:   int iter; 
                   1520:   double a,b,d,etemp;
1.159     brouard  1521:   double fu=0,fv,fw,fx;
1.164     brouard  1522:   double ftemp=0.;
1.126     brouard  1523:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1524:   double e=0.0; 
                   1525:  
                   1526:   a=(ax < cx ? ax : cx); 
                   1527:   b=(ax > cx ? ax : cx); 
                   1528:   x=w=v=bx; 
                   1529:   fw=fv=fx=(*f)(x); 
                   1530:   for (iter=1;iter<=ITMAX;iter++) { 
                   1531:     xm=0.5*(a+b); 
                   1532:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1533:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1534:     printf(".");fflush(stdout);
                   1535:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1536: #ifdef DEBUGBRENT
1.126     brouard  1537:     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);
                   1538:     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);
                   1539:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1540: #endif
                   1541:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1542:       *xmin=x; 
                   1543:       return fx; 
                   1544:     } 
                   1545:     ftemp=fu;
                   1546:     if (fabs(e) > tol1) { 
                   1547:       r=(x-w)*(fx-fv); 
                   1548:       q=(x-v)*(fx-fw); 
                   1549:       p=(x-v)*q-(x-w)*r; 
                   1550:       q=2.0*(q-r); 
                   1551:       if (q > 0.0) p = -p; 
                   1552:       q=fabs(q); 
                   1553:       etemp=e; 
                   1554:       e=d; 
                   1555:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224   ! brouard  1556:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  1557:       else { 
1.224   ! brouard  1558:                                d=p/q; 
        !          1559:                                u=x+d; 
        !          1560:                                if (u-a < tol2 || b-u < tol2) 
        !          1561:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  1562:       } 
                   1563:     } else { 
                   1564:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1565:     } 
                   1566:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1567:     fu=(*f)(u); 
                   1568:     if (fu <= fx) { 
                   1569:       if (u >= x) a=x; else b=x; 
                   1570:       SHFT(v,w,x,u) 
1.183     brouard  1571:       SHFT(fv,fw,fx,fu) 
                   1572:     } else { 
                   1573:       if (u < x) a=u; else b=u; 
                   1574:       if (fu <= fw || w == x) { 
1.224   ! brouard  1575:                                v=w; 
        !          1576:                                w=u; 
        !          1577:                                fv=fw; 
        !          1578:                                fw=fu; 
1.183     brouard  1579:       } else if (fu <= fv || v == x || v == w) { 
1.224   ! brouard  1580:                                v=u; 
        !          1581:                                fv=fu; 
1.183     brouard  1582:       } 
                   1583:     } 
1.126     brouard  1584:   } 
                   1585:   nrerror("Too many iterations in brent"); 
                   1586:   *xmin=x; 
                   1587:   return fx; 
                   1588: } 
                   1589: 
                   1590: /****************** mnbrak ***********************/
                   1591: 
                   1592: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1593:            double (*func)(double)) 
1.183     brouard  1594: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1595: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1596: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1597: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1598:    */
1.126     brouard  1599:   double ulim,u,r,q, dum;
                   1600:   double fu; 
1.187     brouard  1601: 
                   1602:   double scale=10.;
                   1603:   int iterscale=0;
                   1604: 
                   1605:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   1606:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   1607: 
                   1608: 
                   1609:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   1610:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   1611:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   1612:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   1613:   /* } */
                   1614: 
1.126     brouard  1615:   if (*fb > *fa) { 
                   1616:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  1617:     SHFT(dum,*fb,*fa,dum) 
                   1618:   } 
1.126     brouard  1619:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1620:   *fc=(*func)(*cx); 
1.183     brouard  1621: #ifdef DEBUG
1.224   ! brouard  1622:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
        !          1623:   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  1624: #endif
1.224   ! brouard  1625:   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  1626:     r=(*bx-*ax)*(*fb-*fc); 
1.224   ! brouard  1627:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  1628:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  1629:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1630:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   1631:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  1632:       fu=(*func)(u); 
1.163     brouard  1633: #ifdef DEBUG
                   1634:       /* f(x)=A(x-u)**2+f(u) */
                   1635:       double A, fparabu; 
                   1636:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1637:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224   ! brouard  1638:       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);
        !          1639:       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  1640:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   1641:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   1642:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   1643:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  1644: #endif 
1.184     brouard  1645: #ifdef MNBRAKORIGINAL
1.183     brouard  1646: #else
1.191     brouard  1647: /*       if (fu > *fc) { */
                   1648: /* #ifdef DEBUG */
                   1649: /*       printf("mnbrak4  fu > fc \n"); */
                   1650: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   1651: /* #endif */
                   1652: /*     /\* 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 *\\/  *\/ */
                   1653: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   1654: /*     dum=u; /\* Shifting c and u *\/ */
                   1655: /*     u = *cx; */
                   1656: /*     *cx = dum; */
                   1657: /*     dum = fu; */
                   1658: /*     fu = *fc; */
                   1659: /*     *fc =dum; */
                   1660: /*       } else { /\* end *\/ */
                   1661: /* #ifdef DEBUG */
                   1662: /*       printf("mnbrak3  fu < fc \n"); */
                   1663: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   1664: /* #endif */
                   1665: /*     dum=u; /\* Shifting c and u *\/ */
                   1666: /*     u = *cx; */
                   1667: /*     *cx = dum; */
                   1668: /*     dum = fu; */
                   1669: /*     fu = *fc; */
                   1670: /*     *fc =dum; */
                   1671: /*       } */
1.224   ! brouard  1672: #ifdef DEBUGMNBRAK
        !          1673:                 double A, fparabu; 
        !          1674:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
        !          1675:      fparabu= *fa - A*(*ax-u)*(*ax-u);
        !          1676:      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);
        !          1677:      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  1678: #endif
1.191     brouard  1679:       dum=u; /* Shifting c and u */
                   1680:       u = *cx;
                   1681:       *cx = dum;
                   1682:       dum = fu;
                   1683:       fu = *fc;
                   1684:       *fc =dum;
1.183     brouard  1685: #endif
1.162     brouard  1686:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  1687: #ifdef DEBUG
1.224   ! brouard  1688:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
        !          1689:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  1690: #endif
1.126     brouard  1691:       fu=(*func)(u); 
                   1692:       if (fu < *fc) { 
1.183     brouard  1693: #ifdef DEBUG
1.224   ! brouard  1694:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
        !          1695:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
        !          1696: #endif
        !          1697:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
        !          1698:                                SHFT(*fb,*fc,fu,(*func)(u)) 
        !          1699: #ifdef DEBUG
        !          1700:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  1701: #endif
                   1702:       } 
1.162     brouard  1703:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  1704: #ifdef DEBUG
1.224   ! brouard  1705:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
        !          1706:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  1707: #endif
1.126     brouard  1708:       u=ulim; 
                   1709:       fu=(*func)(u); 
1.183     brouard  1710:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   1711: #ifdef DEBUG
1.224   ! brouard  1712:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
        !          1713:       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  1714: #endif
1.126     brouard  1715:       u=(*cx)+GOLD*(*cx-*bx); 
                   1716:       fu=(*func)(u); 
1.224   ! brouard  1717: #ifdef DEBUG
        !          1718:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
        !          1719:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
        !          1720: #endif
1.183     brouard  1721:     } /* end tests */
1.126     brouard  1722:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  1723:     SHFT(*fa,*fb,*fc,fu) 
                   1724: #ifdef DEBUG
1.224   ! brouard  1725:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
        !          1726:       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  1727: #endif
                   1728:   } /* 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  1729: } 
                   1730: 
                   1731: /*************** linmin ************************/
1.162     brouard  1732: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   1733: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   1734: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   1735: the value of func at the returned location p . This is actually all accomplished by calling the
                   1736: routines mnbrak and brent .*/
1.126     brouard  1737: int ncom; 
                   1738: double *pcom,*xicom;
                   1739: double (*nrfunc)(double []); 
                   1740:  
1.224   ! brouard  1741: #ifdef LINMINORIGINAL
1.126     brouard  1742: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224   ! brouard  1743: #else
        !          1744: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
        !          1745: #endif
1.126     brouard  1746: { 
                   1747:   double brent(double ax, double bx, double cx, 
                   1748:               double (*f)(double), double tol, double *xmin); 
                   1749:   double f1dim(double x); 
                   1750:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1751:              double *fc, double (*func)(double)); 
                   1752:   int j; 
                   1753:   double xx,xmin,bx,ax; 
                   1754:   double fx,fb,fa;
1.187     brouard  1755: 
1.203     brouard  1756: #ifdef LINMINORIGINAL
                   1757: #else
                   1758:   double scale=10., axs, xxs; /* Scale added for infinity */
                   1759: #endif
                   1760:   
1.126     brouard  1761:   ncom=n; 
                   1762:   pcom=vector(1,n); 
                   1763:   xicom=vector(1,n); 
                   1764:   nrfunc=func; 
                   1765:   for (j=1;j<=n;j++) { 
                   1766:     pcom[j]=p[j]; 
1.202     brouard  1767:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  1768:   } 
1.187     brouard  1769: 
1.203     brouard  1770: #ifdef LINMINORIGINAL
                   1771:   xx=1.;
                   1772: #else
                   1773:   axs=0.0;
                   1774:   xxs=1.;
                   1775:   do{
                   1776:     xx= xxs;
                   1777: #endif
1.187     brouard  1778:     ax=0.;
                   1779:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   1780:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   1781:     /* 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))   */
                   1782:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   1783:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   1784:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   1785:     /* 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  1786: #ifdef LINMINORIGINAL
                   1787: #else
                   1788:     if (fx != fx){
1.224   ! brouard  1789:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
        !          1790:                        printf("|");
        !          1791:                        fprintf(ficlog,"|");
1.203     brouard  1792: #ifdef DEBUGLINMIN
1.224   ! brouard  1793:                        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  1794: #endif
                   1795:     }
1.224   ! brouard  1796:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  1797: #endif
                   1798:   
1.191     brouard  1799: #ifdef DEBUGLINMIN
                   1800:   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  1801:   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  1802: #endif
1.224   ! brouard  1803: #ifdef LINMINORIGINAL
        !          1804: #else
        !          1805:        if(fb == fx){ /* Flat function in the direction */
        !          1806:                xmin=xx;
        !          1807:     *flat=1;
        !          1808:        }else{
        !          1809:     *flat=0;
        !          1810: #endif
        !          1811:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  1812:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   1813:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   1814:   /* fmin = f(p[j] + xmin * xi[j]) */
                   1815:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   1816:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  1817: #ifdef DEBUG
1.224   ! brouard  1818:   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);
        !          1819:   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);
        !          1820: #endif
        !          1821: #ifdef LINMINORIGINAL
        !          1822: #else
        !          1823:                        }
1.126     brouard  1824: #endif
1.191     brouard  1825: #ifdef DEBUGLINMIN
                   1826:   printf("linmin end ");
1.202     brouard  1827:   fprintf(ficlog,"linmin end ");
1.191     brouard  1828: #endif
1.126     brouard  1829:   for (j=1;j<=n;j++) { 
1.203     brouard  1830: #ifdef LINMINORIGINAL
                   1831:     xi[j] *= xmin; 
                   1832: #else
                   1833: #ifdef DEBUGLINMIN
                   1834:     if(xxs <1.0)
                   1835:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   1836: #endif
                   1837:     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) */
                   1838: #ifdef DEBUGLINMIN
                   1839:     if(xxs <1.0)
                   1840:       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 );
                   1841: #endif
                   1842: #endif
1.187     brouard  1843:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  1844:   } 
1.191     brouard  1845: #ifdef DEBUGLINMIN
1.203     brouard  1846:   printf("\n");
1.191     brouard  1847:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  1848:   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  1849:   for (j=1;j<=n;j++) { 
1.202     brouard  1850:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   1851:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   1852:     if(j % ncovmodel == 0){
1.191     brouard  1853:       printf("\n");
1.202     brouard  1854:       fprintf(ficlog,"\n");
                   1855:     }
1.191     brouard  1856:   }
1.203     brouard  1857: #else
1.191     brouard  1858: #endif
1.126     brouard  1859:   free_vector(xicom,1,n); 
                   1860:   free_vector(pcom,1,n); 
                   1861: } 
                   1862: 
                   1863: 
                   1864: /*************** powell ************************/
1.162     brouard  1865: /*
                   1866: Minimization of a function func of n variables. Input consists of an initial starting point
                   1867: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   1868: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   1869: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   1870: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   1871: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   1872:  */
1.224   ! brouard  1873: #ifdef LINMINORIGINAL
        !          1874: #else
        !          1875:        int *flatdir; /* Function is vanishing in that direction */
        !          1876:        int flat=0; /* Function is vanishing in that direction */
        !          1877: #endif
1.126     brouard  1878: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   1879:            double (*func)(double [])) 
                   1880: { 
1.224   ! brouard  1881: #ifdef LINMINORIGINAL
        !          1882:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  1883:              double (*func)(double [])); 
1.224   ! brouard  1884: #else 
        !          1885:  void linmin(double p[], double xi[], int n, double *fret, 
        !          1886:                                                 double (*func)(double []),int *flat); 
        !          1887: #endif
1.126     brouard  1888:   int i,ibig,j; 
                   1889:   double del,t,*pt,*ptt,*xit;
1.181     brouard  1890:   double directest;
1.126     brouard  1891:   double fp,fptt;
                   1892:   double *xits;
                   1893:   int niterf, itmp;
1.224   ! brouard  1894: #ifdef LINMINORIGINAL
        !          1895: #else
        !          1896: 
        !          1897:   flatdir=ivector(1,n); 
        !          1898:   for (j=1;j<=n;j++) flatdir[j]=0; 
        !          1899: #endif
1.126     brouard  1900: 
                   1901:   pt=vector(1,n); 
                   1902:   ptt=vector(1,n); 
                   1903:   xit=vector(1,n); 
                   1904:   xits=vector(1,n); 
                   1905:   *fret=(*func)(p); 
                   1906:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  1907:   rcurr_time = time(NULL);  
1.126     brouard  1908:   for (*iter=1;;++(*iter)) { 
1.187     brouard  1909:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  1910:     ibig=0; 
                   1911:     del=0.0; 
1.157     brouard  1912:     rlast_time=rcurr_time;
                   1913:     /* (void) gettimeofday(&curr_time,&tzp); */
                   1914:     rcurr_time = time(NULL);  
                   1915:     curr_time = *localtime(&rcurr_time);
                   1916:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   1917:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   1918: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  1919:     for (i=1;i<=n;i++) {
1.126     brouard  1920:       printf(" %d %.12f",i, p[i]);
                   1921:       fprintf(ficlog," %d %.12lf",i, p[i]);
                   1922:       fprintf(ficrespow," %.12lf", p[i]);
                   1923:     }
                   1924:     printf("\n");
                   1925:     fprintf(ficlog,"\n");
                   1926:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   1927:     if(*iter <=3){
1.157     brouard  1928:       tml = *localtime(&rcurr_time);
                   1929:       strcpy(strcurr,asctime(&tml));
                   1930:       rforecast_time=rcurr_time; 
1.126     brouard  1931:       itmp = strlen(strcurr);
                   1932:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.224   ! brouard  1933:                                strcurr[itmp-1]='\0';
1.162     brouard  1934:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  1935:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  1936:       for(niterf=10;niterf<=30;niterf+=10){
1.224   ! brouard  1937:                                rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
        !          1938:                                forecast_time = *localtime(&rforecast_time);
        !          1939:                                strcpy(strfor,asctime(&forecast_time));
        !          1940:                                itmp = strlen(strfor);
        !          1941:                                if(strfor[itmp-1]=='\n')
        !          1942:                                        strfor[itmp-1]='\0';
        !          1943:                                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);
        !          1944:                                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  1945:       }
                   1946:     }
1.187     brouard  1947:     for (i=1;i<=n;i++) { /* For each direction i */
                   1948:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  1949:       fptt=(*fret); 
                   1950: #ifdef DEBUG
1.203     brouard  1951:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   1952:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  1953: #endif
1.203     brouard  1954:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  1955:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224   ! brouard  1956: #ifdef LINMINORIGINAL
1.188     brouard  1957:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224   ! brouard  1958: #else
        !          1959:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
        !          1960:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
        !          1961: #endif
        !          1962:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  1963:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224   ! brouard  1964:                                /* because that direction will be replaced unless the gain del is small */
        !          1965:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
        !          1966:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
        !          1967:                                /* with the new direction. */
        !          1968:                                del=fabs(fptt-(*fret)); 
        !          1969:                                ibig=i; 
1.126     brouard  1970:       } 
                   1971: #ifdef DEBUG
                   1972:       printf("%d %.12e",i,(*fret));
                   1973:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   1974:       for (j=1;j<=n;j++) {
1.224   ! brouard  1975:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
        !          1976:                                printf(" x(%d)=%.12e",j,xit[j]);
        !          1977:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  1978:       }
                   1979:       for(j=1;j<=n;j++) {
1.224   ! brouard  1980:                        printf(" p(%d)=%lf ",j,p[j]);
        !          1981:                        fprintf(ficlog," p(%d)=%lf ",j,p[j]);
1.126     brouard  1982:       }
                   1983:       printf("\n");
                   1984:       fprintf(ficlog,"\n");
                   1985: #endif
1.187     brouard  1986:     } /* end loop on each direction i */
                   1987:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  1988:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  1989:     /* New value of last point Pn is not computed, P(n-1) */
1.224   ! brouard  1990:       for(j=1;j<=n;j++) {
        !          1991:                          printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
        !          1992:                          fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
        !          1993:       }
        !          1994:       printf("\n");
        !          1995:       fprintf(ficlog,"\n");
        !          1996: 
1.182     brouard  1997:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1.188     brouard  1998:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   1999:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2000:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2001:       /* decreased of more than 3.84  */
                   2002:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2003:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2004:       /* By adding 10 parameters more the gain should be 18.31 */
1.224   ! brouard  2005:                        
1.188     brouard  2006:       /* Starting the program with initial values given by a former maximization will simply change */
                   2007:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2008:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2009:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2010: #ifdef DEBUG
                   2011:       int k[2],l;
                   2012:       k[0]=1;
                   2013:       k[1]=-1;
                   2014:       printf("Max: %.12e",(*func)(p));
                   2015:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2016:       for (j=1;j<=n;j++) {
                   2017:        printf(" %.12e",p[j]);
                   2018:        fprintf(ficlog," %.12e",p[j]);
                   2019:       }
                   2020:       printf("\n");
                   2021:       fprintf(ficlog,"\n");
                   2022:       for(l=0;l<=1;l++) {
                   2023:        for (j=1;j<=n;j++) {
                   2024:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2025:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2026:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2027:        }
                   2028:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2029:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2030:       }
                   2031: #endif
                   2032: 
1.224   ! brouard  2033: #ifdef LINMINORIGINAL
        !          2034: #else
        !          2035:       free_ivector(flatdir,1,n); 
        !          2036: #endif
1.126     brouard  2037:       free_vector(xit,1,n); 
                   2038:       free_vector(xits,1,n); 
                   2039:       free_vector(ptt,1,n); 
                   2040:       free_vector(pt,1,n); 
                   2041:       return; 
1.192     brouard  2042:     } /* enough precision */ 
1.126     brouard  2043:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2044:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2045:       ptt[j]=2.0*p[j]-pt[j]; 
                   2046:       xit[j]=p[j]-pt[j]; 
                   2047:       pt[j]=p[j]; 
                   2048:     } 
1.181     brouard  2049:     fptt=(*func)(ptt); /* f_3 */
1.224   ! brouard  2050: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
        !          2051:                if (*iter <=4) {
        !          2052: #else                  
        !          2053: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2054: #else
1.161     brouard  2055:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2056: #endif
1.162     brouard  2057:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2058:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2059:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2060:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2061:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224   ! brouard  2062:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
        !          2063:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
        !          2064:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2065:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224   ! brouard  2066:       /*  Even if f3 <f1, directest can be negative and t >0 */
        !          2067:       /* mu² and del² are equal when f3=f1 */
        !          2068:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
        !          2069:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
        !          2070:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
        !          2071:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2072: #ifdef NRCORIGINAL
                   2073:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2074: #else
                   2075:       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  2076:       t= t- del*SQR(fp-fptt);
1.183     brouard  2077: #endif
1.202     brouard  2078:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2079: #ifdef DEBUG
1.181     brouard  2080:       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);
                   2081:       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  2082:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2083:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2084:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2085:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2086:       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);
                   2087:       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);
                   2088: #endif
1.183     brouard  2089: #ifdef POWELLORIGINAL
                   2090:       if (t < 0.0) { /* Then we use it for new direction */
                   2091: #else
1.182     brouard  2092:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224   ! brouard  2093:                                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  2094:         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  2095:         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  2096:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2097:       } 
1.181     brouard  2098:       if (directest < 0.0) { /* Then we use it for new direction */
                   2099: #endif
1.191     brouard  2100: #ifdef DEBUGLINMIN
1.224   ! brouard  2101:                                printf("Before linmin in direction P%d-P0\n",n);
        !          2102:                                for (j=1;j<=n;j++) {
        !          2103:                                        printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
        !          2104:                                        fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
        !          2105:                                        if(j % ncovmodel == 0){
        !          2106:                                                printf("\n");
        !          2107:                                                fprintf(ficlog,"\n");
        !          2108:                                        }
        !          2109:                                }
        !          2110: #endif
        !          2111: #ifdef LINMINORIGINAL
        !          2112:                                linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
        !          2113: #else
        !          2114:                                linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
        !          2115:                                flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2116: #endif
1.224   ! brouard  2117: 
1.191     brouard  2118: #ifdef DEBUGLINMIN
1.224   ! brouard  2119:                                for (j=1;j<=n;j++) { 
        !          2120:                                        printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
        !          2121:                                        fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
        !          2122:                                        if(j % ncovmodel == 0){
        !          2123:                                                printf("\n");
        !          2124:                                                fprintf(ficlog,"\n");
        !          2125:                                        }
        !          2126:                                }
        !          2127: #endif
        !          2128:                                for (j=1;j<=n;j++) { 
        !          2129:                                        xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
        !          2130:                                        xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
        !          2131:                                }
        !          2132: #ifdef LINMINORIGINAL
        !          2133: #else
        !          2134:                                printf("Flat directions\n");
        !          2135:                                fprintf(ficlog,"Flat directions\n");
        !          2136:                                for (j=1;j<=n;j++) { 
        !          2137:                                        printf("flatdir[%d]=%d ",j,flatdir[j]);
        !          2138:                                        fprintf(ficlog,"flatdir[%d]=%d ",j,flatdir[j]);
        !          2139:         }
        !          2140:                                printf("\n");
        !          2141:                                fprintf(ficlog,"\n");
1.191     brouard  2142: #endif
1.224   ! brouard  2143:                                printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
        !          2144:                                fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
        !          2145:                                
1.126     brouard  2146: #ifdef DEBUG
1.224   ! brouard  2147:                                printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
        !          2148:                                fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
        !          2149:                                for(j=1;j<=n;j++){
        !          2150:                                        printf(" %lf",xit[j]);
        !          2151:                                        fprintf(ficlog," %lf",xit[j]);
        !          2152:                                }
        !          2153:                                printf("\n");
        !          2154:                                fprintf(ficlog,"\n");
1.126     brouard  2155: #endif
1.192     brouard  2156:       } /* end of t or directest negative */
1.224   ! brouard  2157: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2158: #else
1.162     brouard  2159:     } /* end if (fptt < fp)  */
1.192     brouard  2160: #endif
1.224   ! brouard  2161:                } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
        !          2162: #endif
1.192     brouard  2163:   } /* loop iteration */ 
1.126     brouard  2164: } 
                   2165: 
                   2166: /**** Prevalence limit (stable or period prevalence)  ****************/
                   2167: 
1.203     brouard  2168: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij)
1.126     brouard  2169: {
1.218     brouard  2170:   /* Computes the prevalence limit in each live state at age x and for covariate ij by left multiplying the unit
1.203     brouard  2171:      matrix by transitions matrix until convergence is reached with precision ftolpl */
1.206     brouard  2172:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2173:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2174:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2175:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2176:   /* Initial matrix pimij */
                   2177:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2178:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2179:   /*  0,                   0                  , 1} */
                   2180:   /*
                   2181:    * and after some iteration: */
                   2182:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2183:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2184:   /*  0,                   0                  , 1} */
                   2185:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2186:   /* {0.51571254859325999, 0.4842874514067399, */
                   2187:   /*  0.51326036147820708, 0.48673963852179264} */
                   2188:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2189: 
1.126     brouard  2190:   int i, ii,j,k;
1.209     brouard  2191:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2192:   /* double **matprod2(); */ /* test */
1.218     brouard  2193:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2194:   double **newm;
1.209     brouard  2195:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2196:   int ncvloop=0;
1.169     brouard  2197:   
1.209     brouard  2198:   min=vector(1,nlstate);
                   2199:   max=vector(1,nlstate);
                   2200:   meandiff=vector(1,nlstate);
                   2201: 
1.218     brouard  2202:        /* Starting with matrix unity */
1.126     brouard  2203:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2204:     for (j=1;j<=nlstate+ndeath;j++){
                   2205:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2206:     }
1.169     brouard  2207:   
                   2208:   cov[1]=1.;
                   2209:   
                   2210:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2211:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2212:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2213:     ncvloop++;
1.126     brouard  2214:     newm=savm;
                   2215:     /* Covariates have to be included here again */
1.138     brouard  2216:     cov[2]=agefin;
1.187     brouard  2217:     if(nagesqr==1)
                   2218:       cov[3]= agefin*agefin;;
1.138     brouard  2219:     for (k=1; k<=cptcovn;k++) {
1.200     brouard  2220:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.218     brouard  2221:                        /* Here comes the value of the covariate 'ij' */
1.200     brouard  2222:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
1.198     brouard  2223:       /* 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  2224:     }
1.186     brouard  2225:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  2226:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
                   2227:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
1.186     brouard  2228:     for (k=1; k<=cptcovprod;k++) /* Useless */
1.200     brouard  2229:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   2230:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
1.138     brouard  2231:     
                   2232:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2233:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2234:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2235:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2236:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2237:                /* age and covariate values of ij are in 'cov' */
1.142     brouard  2238:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2239:     
1.126     brouard  2240:     savm=oldm;
                   2241:     oldm=newm;
1.209     brouard  2242: 
                   2243:     for(j=1; j<=nlstate; j++){
                   2244:       max[j]=0.;
                   2245:       min[j]=1.;
                   2246:     }
                   2247:     for(i=1;i<=nlstate;i++){
                   2248:       sumnew=0;
                   2249:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2250:       for(j=1; j<=nlstate; j++){ 
                   2251:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2252:        max[j]=FMAX(max[j],prlim[i][j]);
                   2253:        min[j]=FMIN(min[j],prlim[i][j]);
                   2254:       }
                   2255:     }
                   2256: 
1.126     brouard  2257:     maxmax=0.;
1.209     brouard  2258:     for(j=1; j<=nlstate; j++){
                   2259:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2260:       maxmax=FMAX(maxmax,meandiff[j]);
                   2261:       /* 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  2262:     } /* j loop */
1.203     brouard  2263:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2264:     /* 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  2265:     if(maxmax < ftolpl){
1.209     brouard  2266:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2267:       free_vector(min,1,nlstate);
                   2268:       free_vector(max,1,nlstate);
                   2269:       free_vector(meandiff,1,nlstate);
1.126     brouard  2270:       return prlim;
                   2271:     }
1.169     brouard  2272:   } /* age loop */
1.208     brouard  2273:     /* After some age loop it doesn't converge */
1.209     brouard  2274:   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  2275: 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  2276:   /* 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); */
                   2277:   free_vector(min,1,nlstate);
                   2278:   free_vector(max,1,nlstate);
                   2279:   free_vector(meandiff,1,nlstate);
1.208     brouard  2280:   
1.169     brouard  2281:   return prlim; /* should not reach here */
1.126     brouard  2282: }
                   2283: 
1.217     brouard  2284: 
                   2285:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   2286: 
1.218     brouard  2287:  /* 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) */
                   2288:  /* 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) */
                   2289:  double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij)
1.217     brouard  2290: {
1.218     brouard  2291:   /* Computes the prevalence limit in each live state at age x and covariate ij by left multiplying the unit
1.217     brouard  2292:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   2293:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2294:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2295:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2296:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2297:   /* Initial matrix pimij */
                   2298:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2299:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2300:   /*  0,                   0                  , 1} */
                   2301:   /*
                   2302:    * and after some iteration: */
                   2303:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2304:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2305:   /*  0,                   0                  , 1} */
                   2306:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2307:   /* {0.51571254859325999, 0.4842874514067399, */
                   2308:   /*  0.51326036147820708, 0.48673963852179264} */
                   2309:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2310: 
                   2311:   int i, ii,j,k;
                   2312:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   2313:   /* double **matprod2(); */ /* test */
                   2314:   double **out, cov[NCOVMAX+1], **bmij();
                   2315:   double **newm;
1.218     brouard  2316:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   2317:   double        **oldm, **savm;  /* for use */
                   2318: 
1.217     brouard  2319:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   2320:   int ncvloop=0;
                   2321:   
                   2322:   min=vector(1,nlstate);
                   2323:   max=vector(1,nlstate);
                   2324:   meandiff=vector(1,nlstate);
                   2325: 
1.218     brouard  2326:        dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   2327:        oldm=oldms; savm=savms;
                   2328: 
                   2329:        /* Starting with matrix unity */
                   2330:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2331:                for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  2332:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2333:     }
                   2334:   
                   2335:   cov[1]=1.;
                   2336:   
                   2337:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2338:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  2339:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   2340:   for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  2341:     ncvloop++;
1.218     brouard  2342:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   2343:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  2344:     /* Covariates have to be included here again */
                   2345:     cov[2]=agefin;
                   2346:     if(nagesqr==1)
                   2347:       cov[3]= agefin*agefin;;
                   2348:     for (k=1; k<=cptcovn;k++) {
                   2349:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
                   2350:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   2351:       /* 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])]); */
                   2352:     }
                   2353:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   2354:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
                   2355:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
                   2356:     for (k=1; k<=cptcovprod;k++) /* Useless */
                   2357:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   2358:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2359:     
                   2360:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2361:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2362:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   2363:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2364:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2365:                /* ij should be linked to the correct index of cov */
                   2366:                /* age and covariate values ij are in 'cov', but we need to pass
                   2367:                 * ij for the observed prevalence at age and status and covariate
                   2368:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   2369:                 */
                   2370:     /* 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 *\/ */
                   2371:     /* 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 *\/ */
                   2372:     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  2373:     savm=oldm;
                   2374:     oldm=newm;
                   2375:     for(j=1; j<=nlstate; j++){
                   2376:       max[j]=0.;
                   2377:       min[j]=1.;
                   2378:     }
                   2379:     for(j=1; j<=nlstate; j++){ 
                   2380:       for(i=1;i<=nlstate;i++){
1.218     brouard  2381:                                /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   2382:                                bprlim[i][j]= newm[i][j];
                   2383:                                max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   2384:                                min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  2385:       }
                   2386:     }
1.218     brouard  2387:                
1.217     brouard  2388:     maxmax=0.;
                   2389:     for(i=1; i<=nlstate; i++){
                   2390:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column */
                   2391:       maxmax=FMAX(maxmax,meandiff[i]);
                   2392:       /* 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); */
                   2393:     } /* j loop */
                   2394:     *ncvyear= -( (int)age- (int)agefin);
1.218     brouard  2395:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear);*/
1.217     brouard  2396:     if(maxmax < ftolpl){
1.220     brouard  2397:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  2398:       free_vector(min,1,nlstate);
                   2399:       free_vector(max,1,nlstate);
                   2400:       free_vector(meandiff,1,nlstate);
                   2401:       return bprlim;
                   2402:     }
                   2403:   } /* age loop */
                   2404:     /* After some age loop it doesn't converge */
                   2405:   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\
                   2406: 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);
                   2407:   /* 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); */
                   2408:   free_vector(min,1,nlstate);
                   2409:   free_vector(max,1,nlstate);
                   2410:   free_vector(meandiff,1,nlstate);
                   2411:   
                   2412:   return bprlim; /* should not reach here */
                   2413: }
                   2414: 
1.126     brouard  2415: /*************** transition probabilities ***************/ 
                   2416: 
                   2417: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   2418: {
1.138     brouard  2419:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2420:      computes the probability to be observed in state j being in state i by appying the
                   2421:      model to the ncovmodel covariates (including constant and age).
                   2422:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2423:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2424:      ncth covariate in the global vector x is given by the formula:
                   2425:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2426:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2427:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2428:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2429:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2430:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2431:   */
                   2432:   double s1, lnpijopii;
1.126     brouard  2433:   /*double t34;*/
1.164     brouard  2434:   int i,j, nc, ii, jj;
1.126     brouard  2435: 
1.223     brouard  2436:   for(i=1; i<= nlstate; i++){
                   2437:     for(j=1; j<i;j++){
                   2438:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2439:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2440:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2441:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2442:       }
                   2443:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2444:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2445:     }
                   2446:     for(j=i+1; j<=nlstate+ndeath;j++){
                   2447:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2448:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2449:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2450:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   2451:       }
                   2452:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2453:     }
                   2454:   }
1.218     brouard  2455:   
1.223     brouard  2456:   for(i=1; i<= nlstate; i++){
                   2457:     s1=0;
                   2458:     for(j=1; j<i; j++){
                   2459:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2460:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2461:     }
                   2462:     for(j=i+1; j<=nlstate+ndeath; j++){
                   2463:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2464:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2465:     }
                   2466:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   2467:     ps[i][i]=1./(s1+1.);
                   2468:     /* Computing other pijs */
                   2469:     for(j=1; j<i; j++)
                   2470:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2471:     for(j=i+1; j<=nlstate+ndeath; j++)
                   2472:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2473:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2474:   } /* end i */
1.218     brouard  2475:   
1.223     brouard  2476:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2477:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   2478:       ps[ii][jj]=0;
                   2479:       ps[ii][ii]=1;
                   2480:     }
                   2481:   }
1.218     brouard  2482:   
                   2483:   
1.223     brouard  2484:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2485:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2486:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2487:   /*   } */
                   2488:   /*   printf("\n "); */
                   2489:   /* } */
                   2490:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   2491:   /*
                   2492:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  2493:                goto end;*/
1.223     brouard  2494:   return ps;
1.126     brouard  2495: }
                   2496: 
1.218     brouard  2497: /*************** backward transition probabilities ***************/ 
                   2498: 
                   2499:  /* 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 ) */
                   2500: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   2501:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   2502: {
1.222     brouard  2503:   /* Computes the backward probability at age agefin and covariate ij
                   2504:    * and returns in **ps as well as **bmij.
                   2505:    */
1.218     brouard  2506:   int i, ii, j,k;
1.222     brouard  2507:   
                   2508:   double **out, **pmij();
                   2509:   double sumnew=0.;
1.218     brouard  2510:   double agefin;
1.222     brouard  2511:   
                   2512:   double **dnewm, **dsavm, **doldm;
                   2513:   double **bbmij;
                   2514:   
1.218     brouard  2515:   doldm=ddoldms; /* global pointers */
1.222     brouard  2516:   dnewm=ddnewms;
                   2517:   dsavm=ddsavms;
                   2518:   
                   2519:   agefin=cov[2];
                   2520:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
                   2521:      the observed prevalence (with this covariate ij) */
                   2522:   dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate);
                   2523:   /* We do have the matrix Px in savm  and we need pij */
                   2524:   for (j=1;j<=nlstate+ndeath;j++){
                   2525:     sumnew=0.; /* w1 p11 + w2 p21 only on live states */
                   2526:     for (ii=1;ii<=nlstate;ii++){
                   2527:       sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij];
                   2528:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
                   2529:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   2530:       if(sumnew >= 1.e-10){
                   2531:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
                   2532:        /*      doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
                   2533:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
                   2534:        /*      doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
                   2535:        /* }else */
                   2536:        doldm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   2537:       }else{
                   2538:        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);
                   2539:       }
                   2540:     } /*End ii */
                   2541:   } /* End j, At the end doldm is diag[1/(w_1p1i+w_2 p2i)] */
                   2542:   /* left Product of this diag matrix by dsavm=Px (newm=dsavm*doldm) */
                   2543:   bbmij=matprod2(dnewm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, doldm); /* Bug Valgrind */
                   2544:   /* dsavm=doldm; /\* dsavm is now diag [1/(w_1p1i+w_2 p2i)] but can be overwritten*\/ */
                   2545:   /* doldm=dnewm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
                   2546:   /* dnewm=dsavm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
                   2547:   /* left Product of this matrix by diag matrix of prevalences (savm) */
                   2548:   for (j=1;j<=nlstate+ndeath;j++){
                   2549:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   2550:       dsavm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij] : 0.0);
                   2551:     }
                   2552:   } /* End j, At the end oldm is diag[1/(w_1p1i+w_2 p2i)] */
                   2553:   ps=matprod2(doldm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dnewm); /* Bug Valgrind */
                   2554:   /* newm or out is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
                   2555:   /* end bmij */
                   2556:   return ps; 
1.218     brouard  2557: }
1.217     brouard  2558: /*************** transition probabilities ***************/ 
                   2559: 
1.218     brouard  2560: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  2561: {
                   2562:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2563:      computes the probability to be observed in state j being in state i by appying the
                   2564:      model to the ncovmodel covariates (including constant and age).
                   2565:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2566:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2567:      ncth covariate in the global vector x is given by the formula:
                   2568:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2569:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2570:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2571:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2572:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2573:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2574:   */
                   2575:   double s1, lnpijopii;
                   2576:   /*double t34;*/
                   2577:   int i,j, nc, ii, jj;
                   2578: 
1.218     brouard  2579:        for(i=1; i<= nlstate; i++){
                   2580:                for(j=1; j<i;j++){
                   2581:                        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2582:                                /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2583:                                lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2584:                                /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2585:                        }
                   2586:                        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2587:                        /*      printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2588:                }
                   2589:                for(j=i+1; j<=nlstate+ndeath;j++){
                   2590:                        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2591:                                /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2592:                                lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2593:                                /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   2594:                        }
                   2595:                        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2596:                }
                   2597:        }
                   2598:        
                   2599:        for(i=1; i<= nlstate; i++){
                   2600:                s1=0;
                   2601:                for(j=1; j<i; j++){
                   2602:                        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2603:                        /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2604:                }
                   2605:                for(j=i+1; j<=nlstate+ndeath; j++){
                   2606:                        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2607:                        /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2608:                }
                   2609:                /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   2610:                ps[i][i]=1./(s1+1.);
                   2611:                /* Computing other pijs */
                   2612:                for(j=1; j<i; j++)
                   2613:                        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2614:                for(j=i+1; j<=nlstate+ndeath; j++)
                   2615:                        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2616:                /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2617:        } /* end i */
                   2618:        
                   2619:        for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2620:                for(jj=1; jj<= nlstate+ndeath; jj++){
                   2621:                        ps[ii][jj]=0;
                   2622:                        ps[ii][ii]=1;
                   2623:                }
                   2624:        }
                   2625:        /* Added for backcast */ /* Transposed matrix too */
                   2626:        for(jj=1; jj<= nlstate+ndeath; jj++){
                   2627:                s1=0.;
                   2628:                for(ii=1; ii<= nlstate+ndeath; ii++){
                   2629:                        s1+=ps[ii][jj];
                   2630:                }
                   2631:                for(ii=1; ii<= nlstate; ii++){
                   2632:                        ps[ii][jj]=ps[ii][jj]/s1;
                   2633:                }
                   2634:        }
                   2635:        /* Transposition */
                   2636:        for(jj=1; jj<= nlstate+ndeath; jj++){
                   2637:                for(ii=jj; ii<= nlstate+ndeath; ii++){
                   2638:                        s1=ps[ii][jj];
                   2639:                        ps[ii][jj]=ps[jj][ii];
                   2640:                        ps[jj][ii]=s1;
                   2641:                }
                   2642:        }
                   2643:        /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2644:        /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2645:        /*      printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2646:        /*   } */
                   2647:        /*   printf("\n "); */
                   2648:        /* } */
                   2649:        /* printf("\n ");printf("%lf ",cov[2]);*/
                   2650:        /*
                   2651:                for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   2652:                goto end;*/
                   2653:        return ps;
1.217     brouard  2654: }
                   2655: 
                   2656: 
1.126     brouard  2657: /**************** Product of 2 matrices ******************/
                   2658: 
1.145     brouard  2659: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  2660: {
                   2661:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   2662:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   2663:   /* in, b, out are matrice of pointers which should have been initialized 
                   2664:      before: only the contents of out is modified. The function returns
                   2665:      a pointer to pointers identical to out */
1.145     brouard  2666:   int i, j, k;
1.126     brouard  2667:   for(i=nrl; i<= nrh; i++)
1.145     brouard  2668:     for(k=ncolol; k<=ncoloh; k++){
                   2669:       out[i][k]=0.;
                   2670:       for(j=ncl; j<=nch; j++)
                   2671:        out[i][k] +=in[i][j]*b[j][k];
                   2672:     }
1.126     brouard  2673:   return out;
                   2674: }
                   2675: 
                   2676: 
                   2677: /************* Higher Matrix Product ***************/
                   2678: 
                   2679: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
                   2680: {
1.218     brouard  2681:   /* Computes the transition matrix starting at age 'age' and combination of covariate values corresponding to ij over 
1.126     brouard  2682:      'nhstepm*hstepm*stepm' months (i.e. until
                   2683:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   2684:      nhstepm*hstepm matrices. 
                   2685:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   2686:      (typically every 2 years instead of every month which is too big 
                   2687:      for the memory).
                   2688:      Model is determined by parameters x and covariates have to be 
                   2689:      included manually here. 
                   2690: 
                   2691:      */
                   2692: 
                   2693:   int i, j, d, h, k;
1.131     brouard  2694:   double **out, cov[NCOVMAX+1];
1.126     brouard  2695:   double **newm;
1.187     brouard  2696:   double agexact;
1.214     brouard  2697:   double agebegin, ageend;
1.126     brouard  2698: 
                   2699:   /* Hstepm could be zero and should return the unit matrix */
                   2700:   for (i=1;i<=nlstate+ndeath;i++)
                   2701:     for (j=1;j<=nlstate+ndeath;j++){
                   2702:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   2703:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   2704:     }
                   2705:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2706:   for(h=1; h <=nhstepm; h++){
                   2707:     for(d=1; d <=hstepm; d++){
                   2708:       newm=savm;
                   2709:       /* Covariates have to be included here again */
                   2710:       cov[1]=1.;
1.214     brouard  2711:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  2712:       cov[2]=agexact;
                   2713:       if(nagesqr==1)
1.218     brouard  2714:                                cov[3]= agexact*agexact;
1.131     brouard  2715:       for (k=1; k<=cptcovn;k++) 
1.218     brouard  2716:                                cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   2717:                        /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.186     brouard  2718:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
1.218     brouard  2719:                                /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   2720:                                cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2721:                        /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
1.145     brouard  2722:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.218     brouard  2723:                                cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2724:                        /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
1.126     brouard  2725: 
                   2726: 
                   2727:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   2728:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.218     brouard  2729:                        /* right multiplication of oldm by the current matrix */
1.126     brouard  2730:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   2731:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  2732:       /* if((int)age == 70){ */
                   2733:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   2734:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   2735:       /*         printf("%d pmmij ",i); */
                   2736:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2737:       /*           printf("%f ",pmmij[i][j]); */
                   2738:       /*         } */
                   2739:       /*         printf(" oldm "); */
                   2740:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2741:       /*           printf("%f ",oldm[i][j]); */
                   2742:       /*         } */
                   2743:       /*         printf("\n"); */
                   2744:       /*       } */
                   2745:       /* } */
1.126     brouard  2746:       savm=oldm;
                   2747:       oldm=newm;
                   2748:     }
                   2749:     for(i=1; i<=nlstate+ndeath; i++)
                   2750:       for(j=1;j<=nlstate+ndeath;j++) {
1.218     brouard  2751:                                po[i][j][h]=newm[i][j];
                   2752:                                /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  2753:       }
1.128     brouard  2754:     /*printf("h=%d ",h);*/
1.126     brouard  2755:   } /* end h */
1.218     brouard  2756:        /*     printf("\n H=%d \n",h); */
1.126     brouard  2757:   return po;
                   2758: }
                   2759: 
1.217     brouard  2760: /************* Higher Back Matrix Product ***************/
1.218     brouard  2761: /* 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  2762: double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, double ***prevacurrent, int nlstate, int stepm, int ij )
1.217     brouard  2763: {
1.218     brouard  2764:   /* Computes the transition matrix starting at age 'age' over
1.217     brouard  2765:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  2766:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   2767:      nhstepm*hstepm matrices.
                   2768:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   2769:      (typically every 2 years instead of every month which is too big
1.217     brouard  2770:      for the memory).
1.218     brouard  2771:      Model is determined by parameters x and covariates have to be
                   2772:      included manually here.
1.217     brouard  2773: 
1.222     brouard  2774:   */
1.217     brouard  2775: 
                   2776:   int i, j, d, h, k;
                   2777:   double **out, cov[NCOVMAX+1];
                   2778:   double **newm;
                   2779:   double agexact;
                   2780:   double agebegin, ageend;
1.222     brouard  2781:   double **oldm, **savm;
1.217     brouard  2782: 
1.222     brouard  2783:   oldm=oldms;savm=savms;
1.217     brouard  2784:   /* Hstepm could be zero and should return the unit matrix */
                   2785:   for (i=1;i<=nlstate+ndeath;i++)
                   2786:     for (j=1;j<=nlstate+ndeath;j++){
                   2787:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   2788:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   2789:     }
                   2790:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2791:   for(h=1; h <=nhstepm; h++){
                   2792:     for(d=1; d <=hstepm; d++){
                   2793:       newm=savm;
                   2794:       /* Covariates have to be included here again */
                   2795:       cov[1]=1.;
                   2796:       agexact=age-((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
                   2797:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
                   2798:       cov[2]=agexact;
                   2799:       if(nagesqr==1)
1.222     brouard  2800:        cov[3]= agexact*agexact;
1.218     brouard  2801:       for (k=1; k<=cptcovn;k++)
1.222     brouard  2802:        cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   2803:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.217     brouard  2804:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
1.222     brouard  2805:        /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   2806:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2807:       /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
1.217     brouard  2808:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.222     brouard  2809:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2810:       /* 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  2811:                        
                   2812:                        
1.217     brouard  2813:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   2814:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.218     brouard  2815:       /* Careful transposed matrix */
1.222     brouard  2816:       /* age is in cov[2] */
1.218     brouard  2817:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  2818:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  2819:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.222     brouard  2820:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
1.217     brouard  2821:       /* if((int)age == 70){ */
                   2822:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   2823:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   2824:       /*         printf("%d pmmij ",i); */
                   2825:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2826:       /*           printf("%f ",pmmij[i][j]); */
                   2827:       /*         } */
                   2828:       /*         printf(" oldm "); */
                   2829:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2830:       /*           printf("%f ",oldm[i][j]); */
                   2831:       /*         } */
                   2832:       /*         printf("\n"); */
                   2833:       /*       } */
                   2834:       /* } */
                   2835:       savm=oldm;
                   2836:       oldm=newm;
                   2837:     }
                   2838:     for(i=1; i<=nlstate+ndeath; i++)
                   2839:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  2840:        po[i][j][h]=newm[i][j];
                   2841:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.217     brouard  2842:       }
                   2843:     /*printf("h=%d ",h);*/
                   2844:   } /* end h */
1.222     brouard  2845:   /*     printf("\n H=%d \n",h); */
1.217     brouard  2846:   return po;
                   2847: }
                   2848: 
                   2849: 
1.162     brouard  2850: #ifdef NLOPT
                   2851:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   2852:   double fret;
                   2853:   double *xt;
                   2854:   int j;
                   2855:   myfunc_data *d2 = (myfunc_data *) pd;
                   2856: /* xt = (p1-1); */
                   2857:   xt=vector(1,n); 
                   2858:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   2859: 
                   2860:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   2861:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   2862:   printf("Function = %.12lf ",fret);
                   2863:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   2864:   printf("\n");
                   2865:  free_vector(xt,1,n);
                   2866:   return fret;
                   2867: }
                   2868: #endif
1.126     brouard  2869: 
                   2870: /*************** log-likelihood *************/
                   2871: double func( double *x)
                   2872: {
1.224   ! brouard  2873:        int i, ii, j, k, mi, d, kk;
        !          2874:        int ioffset=0;
        !          2875:        double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
        !          2876:        double **out;
        !          2877:        double sw; /* Sum of weights */
        !          2878:        double lli; /* Individual log likelihood */
        !          2879:        int s1, s2;
        !          2880:        int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate */
        !          2881:        double bbh, survp;
        !          2882:        long ipmx;
        !          2883:        double agexact;
        !          2884:        /*extern weight */
        !          2885:        /* We are differentiating ll according to initial status */
        !          2886:        /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
        !          2887:        /*for(i=1;i<imx;i++) 
        !          2888:                printf(" %d\n",s[4][i]);
        !          2889:        */
1.162     brouard  2890: 
1.224   ! brouard  2891:        ++countcallfunc;
1.162     brouard  2892: 
1.224   ! brouard  2893:        cov[1]=1.;
1.126     brouard  2894: 
1.224   ! brouard  2895:        for(k=1; k<=nlstate; k++) ll[k]=0.;
        !          2896:   ioffset=0;
        !          2897:        if(mle==1){
        !          2898:                for (i=1,ipmx=0, sw=0.; i<=imx; i++){
        !          2899:                        /* Computes the values of the ncovmodel covariates of the model
        !          2900:                                 depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
        !          2901:                                 Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
        !          2902:                                 to be observed in j being in i according to the model.
        !          2903:                        */
        !          2904:                        ioffset=2+nagesqr+cptcovage;
        !          2905:                        /* for (k=1; k<=cptcovn;k++){ /\* Simple and product covariates without age* products *\/ */
        !          2906:                        for (k=1; k<=ncoveff;k++){ /* Simple and product covariates without age* products */
        !          2907:                                cov[++ioffset]=covar[Tvar[k]][i];
        !          2908:                        }
        !          2909:                        for(iqv=1; iqv <= nqveff; iqv++){ /* Quantitatives covariates */
        !          2910:                                cov[++ioffset]=coqvar[iqv][i];
        !          2911:                        }
1.126     brouard  2912: 
1.224   ! brouard  2913:                        /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
        !          2914:                                 is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
        !          2915:                                 has been calculated etc */
        !          2916:                        /* For an individual i, wav[i] gives the number of effective waves */
        !          2917:                        /* We compute the contribution to Likelihood of each effective transition
        !          2918:                                 mw[mi][i] is real wave of the mi th effectve wave */
        !          2919:                        /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
        !          2920:                                 s2=s[mw[mi+1][i]][i];
        !          2921:                                 And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
        !          2922:                                 But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
        !          2923:                                 meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
        !          2924:                        */
        !          2925:                        for(mi=1; mi<= wav[i]-1; mi++){
        !          2926:                                for(itv=1; itv <= ntveff; itv++){ /* Varying dummy covariates */
        !          2927:                                        cov[ioffset+itv]=cotvar[mw[mi][i]][itv][i];
        !          2928:                                }
        !          2929:                                for(iqtv=1; iqtv <= nqtveff; iqtv++){ /* Varying quantitatives covariates */
        !          2930:                                        cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][iqtv][i];
        !          2931:                                }
        !          2932:                                /* ioffset=2+nagesqr+cptcovn+nqv+ntv+nqtv; */
        !          2933:                                for (ii=1;ii<=nlstate+ndeath;ii++)
        !          2934:                                        for (j=1;j<=nlstate+ndeath;j++){
        !          2935:                                                oldm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          2936:                                                savm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          2937:                                        }
        !          2938:                                for(d=0; d<dh[mi][i]; d++){
        !          2939:                                        newm=savm;
        !          2940:                                        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
        !          2941:                                        cov[2]=agexact;
        !          2942:                                        if(nagesqr==1)
        !          2943:                                                cov[3]= agexact*agexact;  /* Should be changed here */
        !          2944:                                        for (kk=1; kk<=cptcovage;kk++) {
        !          2945:                                                cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
        !          2946:                                        }
        !          2947:                                        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
        !          2948:                                                                                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
        !          2949:                                        savm=oldm;
        !          2950:                                        oldm=newm;
        !          2951:                                } /* end mult */
        !          2952:                                
        !          2953:                                        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
        !          2954:                                /* But now since version 0.9 we anticipate for bias at large stepm.
        !          2955:                                 * If stepm is larger than one month (smallest stepm) and if the exact delay 
        !          2956:                                 * (in months) between two waves is not a multiple of stepm, we rounded to 
        !          2957:                                 * the nearest (and in case of equal distance, to the lowest) interval but now
        !          2958:                                 * we keep into memory the bias bh[mi][i] and also the previous matrix product
        !          2959:                                 * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
        !          2960:                                 * probability in order to take into account the bias as a fraction of the way
        !          2961:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
        !          2962:                                 * -stepm/2 to stepm/2 .
        !          2963:                                 * For stepm=1 the results are the same as for previous versions of Imach.
        !          2964:                                 * For stepm > 1 the results are less biased than in previous versions. 
        !          2965:                                 */
        !          2966:                                s1=s[mw[mi][i]][i];
        !          2967:                                s2=s[mw[mi+1][i]][i];
        !          2968:                                bbh=(double)bh[mi][i]/(double)stepm; 
        !          2969:                                /* bias bh is positive if real duration
        !          2970:                                 * is higher than the multiple of stepm and negative otherwise.
        !          2971:                                 */
        !          2972:                                /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
        !          2973:                                if( s2 > nlstate){ 
        !          2974:                                        /* i.e. if s2 is a death state and if the date of death is known 
        !          2975:                                                 then the contribution to the likelihood is the probability to 
        !          2976:                                                 die between last step unit time and current  step unit time, 
        !          2977:                                                 which is also equal to probability to die before dh 
        !          2978:                                                 minus probability to die before dh-stepm . 
        !          2979:                                                 In version up to 0.92 likelihood was computed
        !          2980:                                                 as if date of death was unknown. Death was treated as any other
        !          2981:                                                 health state: the date of the interview describes the actual state
        !          2982:                                                 and not the date of a change in health state. The former idea was
        !          2983:                                                 to consider that at each interview the state was recorded
        !          2984:                                                 (healthy, disable or death) and IMaCh was corrected; but when we
        !          2985:                                                 introduced the exact date of death then we should have modified
        !          2986:                                                 the contribution of an exact death to the likelihood. This new
        !          2987:                                                 contribution is smaller and very dependent of the step unit
        !          2988:                                                 stepm. It is no more the probability to die between last interview
        !          2989:                                                 and month of death but the probability to survive from last
        !          2990:                                                 interview up to one month before death multiplied by the
        !          2991:                                                 probability to die within a month. Thanks to Chris
        !          2992:                                                 Jackson for correcting this bug.  Former versions increased
        !          2993:                                                 mortality artificially. The bad side is that we add another loop
        !          2994:                                                 which slows down the processing. The difference can be up to 10%
        !          2995:                                                 lower mortality.
        !          2996:                                        */
        !          2997:                                        /* If, at the beginning of the maximization mostly, the
        !          2998:                                                 cumulative probability or probability to be dead is
        !          2999:                                                 constant (ie = 1) over time d, the difference is equal to
        !          3000:                                                 0.  out[s1][3] = savm[s1][3]: probability, being at state
        !          3001:                                                 s1 at precedent wave, to be dead a month before current
        !          3002:                                                 wave is equal to probability, being at state s1 at
        !          3003:                                                 precedent wave, to be dead at mont of the current
        !          3004:                                                 wave. Then the observed probability (that this person died)
        !          3005:                                                 is null according to current estimated parameter. In fact,
        !          3006:                                                 it should be very low but not zero otherwise the log go to
        !          3007:                                                 infinity.
        !          3008:                                        */
1.183     brouard  3009: /* #ifdef INFINITYORIGINAL */
                   3010: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3011: /* #else */
                   3012: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   3013: /*         lli=log(mytinydouble); */
                   3014: /*       else */
                   3015: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3016: /* #endif */
1.224   ! brouard  3017:                                        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3018:          
1.224   ! brouard  3019:                                } else if  ( s2==-1 ) { /* alive */
        !          3020:                                        for (j=1,survp=0. ; j<=nlstate; j++) 
        !          3021:                                                survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
        !          3022:                                        /*survp += out[s1][j]; */
        !          3023:                                        lli= log(survp);
        !          3024:                                }
        !          3025:                                else if  (s2==-4) { 
        !          3026:                                        for (j=3,survp=0. ; j<=nlstate; j++)  
        !          3027:                                                survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
        !          3028:                                        lli= log(survp); 
        !          3029:                                } 
        !          3030:                                else if  (s2==-5) { 
        !          3031:                                        for (j=1,survp=0. ; j<=2; j++)  
        !          3032:                                                survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
        !          3033:                                        lli= log(survp); 
        !          3034:                                } 
        !          3035:                                else{
        !          3036:                                        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
        !          3037:                                        /*  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 */
        !          3038:                                } 
        !          3039:                                /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
        !          3040:                                /*if(lli ==000.0)*/
        !          3041:                                /*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); */
        !          3042:                                ipmx +=1;
        !          3043:                                sw += weight[i];
        !          3044:                                ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
        !          3045:                                /* if (lli < log(mytinydouble)){ */
        !          3046:                                /*   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); */
        !          3047:                                /*   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]); */
        !          3048:                                /* } */
        !          3049:                        } /* end of wave */
        !          3050:                } /* end of individual */
        !          3051:        }  else if(mle==2){
        !          3052:                for (i=1,ipmx=0, sw=0.; i<=imx; i++){
        !          3053:                        for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
        !          3054:                        for(mi=1; mi<= wav[i]-1; mi++){
        !          3055:                                for (ii=1;ii<=nlstate+ndeath;ii++)
        !          3056:                                        for (j=1;j<=nlstate+ndeath;j++){
        !          3057:                                                oldm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          3058:                                                savm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          3059:                                        }
        !          3060:                                for(d=0; d<=dh[mi][i]; d++){
        !          3061:                                        newm=savm;
        !          3062:                                        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
        !          3063:                                        cov[2]=agexact;
        !          3064:                                        if(nagesqr==1)
        !          3065:                                                cov[3]= agexact*agexact;
        !          3066:                                        for (kk=1; kk<=cptcovage;kk++) {
        !          3067:                                                cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
        !          3068:                                        }
        !          3069:                                        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
        !          3070:                                                                                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
        !          3071:                                        savm=oldm;
        !          3072:                                        oldm=newm;
        !          3073:                                } /* end mult */
        !          3074:       
        !          3075:                                s1=s[mw[mi][i]][i];
        !          3076:                                s2=s[mw[mi+1][i]][i];
        !          3077:                                bbh=(double)bh[mi][i]/(double)stepm; 
        !          3078:                                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 */
        !          3079:                                ipmx +=1;
        !          3080:                                sw += weight[i];
        !          3081:                                ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
        !          3082:                        } /* end of wave */
        !          3083:                } /* end of individual */
        !          3084:        }  else if(mle==3){  /* exponential inter-extrapolation */
        !          3085:                for (i=1,ipmx=0, sw=0.; i<=imx; i++){
        !          3086:                        for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
        !          3087:                        for(mi=1; mi<= wav[i]-1; mi++){
        !          3088:                                for (ii=1;ii<=nlstate+ndeath;ii++)
        !          3089:                                        for (j=1;j<=nlstate+ndeath;j++){
        !          3090:                                                oldm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          3091:                                                savm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          3092:                                        }
        !          3093:                                for(d=0; d<dh[mi][i]; d++){
        !          3094:                                        newm=savm;
        !          3095:                                        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
        !          3096:                                        cov[2]=agexact;
        !          3097:                                        if(nagesqr==1)
        !          3098:                                                cov[3]= agexact*agexact;
        !          3099:                                        for (kk=1; kk<=cptcovage;kk++) {
        !          3100:                                                cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
        !          3101:                                        }
        !          3102:                                        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
        !          3103:                                                                                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
        !          3104:                                        savm=oldm;
        !          3105:                                        oldm=newm;
        !          3106:                                } /* end mult */
        !          3107:       
        !          3108:                                s1=s[mw[mi][i]][i];
        !          3109:                                s2=s[mw[mi+1][i]][i];
        !          3110:                                bbh=(double)bh[mi][i]/(double)stepm; 
        !          3111:                                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 */
        !          3112:                                ipmx +=1;
        !          3113:                                sw += weight[i];
        !          3114:                                ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
        !          3115:                        } /* end of wave */
        !          3116:                } /* end of individual */
        !          3117:        }else if (mle==4){  /* ml=4 no inter-extrapolation */
        !          3118:                for (i=1,ipmx=0, sw=0.; i<=imx; i++){
        !          3119:                        for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
        !          3120:                        for(mi=1; mi<= wav[i]-1; mi++){
        !          3121:                                for (ii=1;ii<=nlstate+ndeath;ii++)
        !          3122:                                        for (j=1;j<=nlstate+ndeath;j++){
        !          3123:                                                oldm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          3124:                                                savm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          3125:                                        }
        !          3126:                                for(d=0; d<dh[mi][i]; d++){
        !          3127:                                        newm=savm;
        !          3128:                                        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
        !          3129:                                        cov[2]=agexact;
        !          3130:                                        if(nagesqr==1)
        !          3131:                                                cov[3]= agexact*agexact;
        !          3132:                                        for (kk=1; kk<=cptcovage;kk++) {
        !          3133:                                                cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
        !          3134:                                        }
1.126     brouard  3135:        
1.224   ! brouard  3136:                                        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
        !          3137:                                                                                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
        !          3138:                                        savm=oldm;
        !          3139:                                        oldm=newm;
        !          3140:                                } /* end mult */
        !          3141:       
        !          3142:                                s1=s[mw[mi][i]][i];
        !          3143:                                s2=s[mw[mi+1][i]][i];
        !          3144:                                if( s2 > nlstate){ 
        !          3145:                                        lli=log(out[s1][s2] - savm[s1][s2]);
        !          3146:                                } else if  ( s2==-1 ) { /* alive */
        !          3147:                                        for (j=1,survp=0. ; j<=nlstate; j++) 
        !          3148:                                                survp += out[s1][j];
        !          3149:                                        lli= log(survp);
        !          3150:                                }else{
        !          3151:                                        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
        !          3152:                                }
        !          3153:                                ipmx +=1;
        !          3154:                                sw += weight[i];
        !          3155:                                ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.126     brouard  3156: /*     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.224   ! brouard  3157:                        } /* end of wave */
        !          3158:                } /* end of individual */
        !          3159:        }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
        !          3160:                for (i=1,ipmx=0, sw=0.; i<=imx; i++){
        !          3161:                        for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
        !          3162:                        for(mi=1; mi<= wav[i]-1; mi++){
        !          3163:                                for (ii=1;ii<=nlstate+ndeath;ii++)
        !          3164:                                        for (j=1;j<=nlstate+ndeath;j++){
        !          3165:                                                oldm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          3166:                                                savm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          3167:                                        }
        !          3168:                                for(d=0; d<dh[mi][i]; d++){
        !          3169:                                        newm=savm;
        !          3170:                                        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
        !          3171:                                        cov[2]=agexact;
        !          3172:                                        if(nagesqr==1)
        !          3173:                                                cov[3]= agexact*agexact;
        !          3174:                                        for (kk=1; kk<=cptcovage;kk++) {
        !          3175:                                                cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
        !          3176:                                        }
1.126     brouard  3177:        
1.224   ! brouard  3178:                                        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
        !          3179:                                                                                         1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
        !          3180:                                        savm=oldm;
        !          3181:                                        oldm=newm;
        !          3182:                                } /* end mult */
        !          3183:       
        !          3184:                                s1=s[mw[mi][i]][i];
        !          3185:                                s2=s[mw[mi+1][i]][i];
        !          3186:                                lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
        !          3187:                                ipmx +=1;
        !          3188:                                sw += weight[i];
        !          3189:                                ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
        !          3190:                                /*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]);*/
        !          3191:                        } /* end of wave */
        !          3192:                } /* end of individual */
        !          3193:        } /* End of if */
        !          3194:        for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
        !          3195:        /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
        !          3196:        l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
        !          3197:        return -l;
1.126     brouard  3198: }
                   3199: 
                   3200: /*************** log-likelihood *************/
                   3201: double funcone( double *x)
                   3202: {
                   3203:   /* Same as likeli but slower because of a lot of printf and if */
                   3204:   int i, ii, j, k, mi, d, kk;
1.224   ! brouard  3205:        int ioffset=0;
1.131     brouard  3206:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  3207:   double **out;
                   3208:   double lli; /* Individual log likelihood */
                   3209:   double llt;
                   3210:   int s1, s2;
1.224   ! brouard  3211:        int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate */
1.126     brouard  3212:   double bbh, survp;
1.187     brouard  3213:   double agexact;
1.214     brouard  3214:   double agebegin, ageend;
1.126     brouard  3215:   /*extern weight */
                   3216:   /* We are differentiating ll according to initial status */
                   3217:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3218:   /*for(i=1;i<imx;i++) 
                   3219:     printf(" %d\n",s[4][i]);
                   3220:   */
                   3221:   cov[1]=1.;
                   3222: 
                   3223:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224   ! brouard  3224:   ioffset=0;
        !          3225:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
        !          3226:                ioffset=2+nagesqr+cptcovage;
        !          3227:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
        !          3228:                for (k=1; k<=ncoveff;k++){ /* Simple and product covariates without age* products */
        !          3229:                        cov[++ioffset]=covar[Tvar[k]][i];
        !          3230:                }
        !          3231:                for(iqv=1; iqv <= nqveff; iqv++){ /* Quantitatives covariates */
        !          3232:                        cov[++ioffset]=coqvar[iqv][i];
        !          3233:                }
1.126     brouard  3234: 
                   3235:     for(mi=1; mi<= wav[i]-1; mi++){
1.224   ! brouard  3236:                        for(itv=1; itv <= ntveff; itv++){ /* Varying dummy covariates */
        !          3237:                                cov[ioffset+itv]=cotvar[mw[mi][i]][itv][i];
        !          3238:                        }
        !          3239:                        for(iqtv=1; iqtv <= nqtveff; iqtv++){ /* Varying quantitatives covariates */
        !          3240:                                cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][iqtv][i];
        !          3241:                        }
1.126     brouard  3242:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.224   ! brouard  3243:                                for (j=1;j<=nlstate+ndeath;j++){
        !          3244:                                        oldm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          3245:                                        savm[ii][j]=(ii==j ? 1.0 : 0.0);
        !          3246:                                }
1.214     brouard  3247:       
                   3248:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   3249:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   3250:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.224   ! brouard  3251:                                /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
        !          3252:                                        and mw[mi+1][i]. dh depends on stepm.*/
        !          3253:                                newm=savm;
        !          3254:                                agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
        !          3255:                                cov[2]=agexact;
        !          3256:                                if(nagesqr==1)
        !          3257:                                        cov[3]= agexact*agexact;
        !          3258:                                for (kk=1; kk<=cptcovage;kk++) {
        !          3259:                                        cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
        !          3260:                                }
        !          3261:                                
        !          3262:                                /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
        !          3263:                                out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
        !          3264:                                                                                 1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
        !          3265:                                /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
        !          3266:                                /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
        !          3267:                                savm=oldm;
        !          3268:                                oldm=newm;
1.126     brouard  3269:       } /* end mult */
                   3270:       
                   3271:       s1=s[mw[mi][i]][i];
                   3272:       s2=s[mw[mi+1][i]][i];
1.217     brouard  3273:       /* if(s2==-1){ */
                   3274:       /*       printf(" s1=%d, s2=%d i=%d \n", s1, s2, i); */
                   3275:       /*       /\* exit(1); *\/ */
                   3276:       /* } */
1.126     brouard  3277:       bbh=(double)bh[mi][i]/(double)stepm; 
                   3278:       /* bias is positive if real duration
                   3279:        * is higher than the multiple of stepm and negative otherwise.
                   3280:        */
                   3281:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.224   ! brouard  3282:                                lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3283:       } else if  ( s2==-1 ) { /* alive */
1.224   ! brouard  3284:                                for (j=1,survp=0. ; j<=nlstate; j++) 
        !          3285:                                        survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
        !          3286:                                lli= log(survp);
1.126     brouard  3287:       }else if (mle==1){
1.224   ! brouard  3288:                                lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  3289:       } else if(mle==2){
1.224   ! brouard  3290:                                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  3291:       } else if(mle==3){  /* exponential inter-extrapolation */
1.224   ! brouard  3292:                                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  3293:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.224   ! brouard  3294:                                lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  3295:       } else{  /* mle=0 back to 1 */
1.224   ! brouard  3296:                                lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
        !          3297:                                /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  3298:       } /* End of if */
                   3299:       ipmx +=1;
                   3300:       sw += weight[i];
                   3301:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  3302:       /*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  3303:       if(globpr){
1.224   ! brouard  3304:                                fprintf(ficresilk,"%9ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  3305:  %11.6f %11.6f %11.6f ", \
1.224   ! brouard  3306:                                                                num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
        !          3307:                                                                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
        !          3308:                                for(k=1,llt=0.,l=0.; k<=nlstate; k++){
        !          3309:                                        llt +=ll[k]*gipmx/gsw;
        !          3310:                                        fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
        !          3311:                                }
        !          3312:                                fprintf(ficresilk," %10.6f\n", -llt);
1.126     brouard  3313:       }
                   3314:     } /* end of wave */
                   3315:   } /* end of individual */
                   3316:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3317:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3318:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3319:   if(globpr==0){ /* First time we count the contributions and weights */
                   3320:     gipmx=ipmx;
                   3321:     gsw=sw;
                   3322:   }
                   3323:   return -l;
                   3324: }
                   3325: 
                   3326: 
                   3327: /*************** function likelione ***********/
                   3328: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   3329: {
                   3330:   /* This routine should help understanding what is done with 
                   3331:      the selection of individuals/waves and
                   3332:      to check the exact contribution to the likelihood.
                   3333:      Plotting could be done.
                   3334:    */
                   3335:   int k;
                   3336: 
                   3337:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  3338:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  3339:     strcat(fileresilk,fileresu);
1.126     brouard  3340:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   3341:       printf("Problem with resultfile: %s\n", fileresilk);
                   3342:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   3343:     }
1.214     brouard  3344:     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");
                   3345:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  3346:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   3347:     for(k=1; k<=nlstate; k++) 
                   3348:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   3349:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   3350:   }
                   3351: 
                   3352:   *fretone=(*funcone)(p);
                   3353:   if(*globpri !=0){
                   3354:     fclose(ficresilk);
1.205     brouard  3355:     if (mle ==0)
                   3356:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   3357:     else if(mle >=1)
                   3358:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   3359:     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  3360:     
1.208     brouard  3361:       
                   3362:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  3363:       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  3364: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   3365:     }
1.207     brouard  3366:     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  3367: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3368:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  3369: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3370:     fflush(fichtm);
1.205     brouard  3371:   }
1.126     brouard  3372:   return;
                   3373: }
                   3374: 
                   3375: 
                   3376: /*********** Maximum Likelihood Estimation ***************/
                   3377: 
                   3378: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   3379: {
1.165     brouard  3380:   int i,j, iter=0;
1.126     brouard  3381:   double **xi;
                   3382:   double fret;
                   3383:   double fretone; /* Only one call to likelihood */
                   3384:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  3385: 
                   3386: #ifdef NLOPT
                   3387:   int creturn;
                   3388:   nlopt_opt opt;
                   3389:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   3390:   double *lb;
                   3391:   double minf; /* the minimum objective value, upon return */
                   3392:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   3393:   myfunc_data dinst, *d = &dinst;
                   3394: #endif
                   3395: 
                   3396: 
1.126     brouard  3397:   xi=matrix(1,npar,1,npar);
                   3398:   for (i=1;i<=npar;i++)
                   3399:     for (j=1;j<=npar;j++)
                   3400:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   3401:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  3402:   strcpy(filerespow,"POW_"); 
1.126     brouard  3403:   strcat(filerespow,fileres);
                   3404:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   3405:     printf("Problem with resultfile: %s\n", filerespow);
                   3406:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   3407:   }
                   3408:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   3409:   for (i=1;i<=nlstate;i++)
                   3410:     for(j=1;j<=nlstate+ndeath;j++)
                   3411:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   3412:   fprintf(ficrespow,"\n");
1.162     brouard  3413: #ifdef POWELL
1.126     brouard  3414:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  3415: #endif
1.126     brouard  3416: 
1.162     brouard  3417: #ifdef NLOPT
                   3418: #ifdef NEWUOA
                   3419:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   3420: #else
                   3421:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   3422: #endif
                   3423:   lb=vector(0,npar-1);
                   3424:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   3425:   nlopt_set_lower_bounds(opt, lb);
                   3426:   nlopt_set_initial_step1(opt, 0.1);
                   3427:   
                   3428:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   3429:   d->function = func;
                   3430:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   3431:   nlopt_set_min_objective(opt, myfunc, d);
                   3432:   nlopt_set_xtol_rel(opt, ftol);
                   3433:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   3434:     printf("nlopt failed! %d\n",creturn); 
                   3435:   }
                   3436:   else {
                   3437:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   3438:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   3439:     iter=1; /* not equal */
                   3440:   }
                   3441:   nlopt_destroy(opt);
                   3442: #endif
1.126     brouard  3443:   free_matrix(xi,1,npar,1,npar);
                   3444:   fclose(ficrespow);
1.203     brouard  3445:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   3446:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  3447:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  3448: 
                   3449: }
                   3450: 
                   3451: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  3452: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  3453: {
                   3454:   double  **a,**y,*x,pd;
1.203     brouard  3455:   /* double **hess; */
1.164     brouard  3456:   int i, j;
1.126     brouard  3457:   int *indx;
                   3458: 
                   3459:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  3460:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  3461:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   3462:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   3463:   double gompertz(double p[]);
1.203     brouard  3464:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  3465: 
                   3466:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   3467:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   3468:   for (i=1;i<=npar;i++){
1.203     brouard  3469:     printf("%d-",i);fflush(stdout);
                   3470:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  3471:    
                   3472:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   3473:     
                   3474:     /*  printf(" %f ",p[i]);
                   3475:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   3476:   }
                   3477:   
                   3478:   for (i=1;i<=npar;i++) {
                   3479:     for (j=1;j<=npar;j++)  {
                   3480:       if (j>i) { 
1.203     brouard  3481:        printf(".%d-%d",i,j);fflush(stdout);
                   3482:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   3483:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  3484:        
                   3485:        hess[j][i]=hess[i][j];    
                   3486:        /*printf(" %lf ",hess[i][j]);*/
                   3487:       }
                   3488:     }
                   3489:   }
                   3490:   printf("\n");
                   3491:   fprintf(ficlog,"\n");
                   3492: 
                   3493:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   3494:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   3495:   
                   3496:   a=matrix(1,npar,1,npar);
                   3497:   y=matrix(1,npar,1,npar);
                   3498:   x=vector(1,npar);
                   3499:   indx=ivector(1,npar);
                   3500:   for (i=1;i<=npar;i++)
                   3501:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   3502:   ludcmp(a,npar,indx,&pd);
                   3503: 
                   3504:   for (j=1;j<=npar;j++) {
                   3505:     for (i=1;i<=npar;i++) x[i]=0;
                   3506:     x[j]=1;
                   3507:     lubksb(a,npar,indx,x);
                   3508:     for (i=1;i<=npar;i++){ 
                   3509:       matcov[i][j]=x[i];
                   3510:     }
                   3511:   }
                   3512: 
                   3513:   printf("\n#Hessian matrix#\n");
                   3514:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   3515:   for (i=1;i<=npar;i++) { 
                   3516:     for (j=1;j<=npar;j++) { 
1.203     brouard  3517:       printf("%.6e ",hess[i][j]);
                   3518:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  3519:     }
                   3520:     printf("\n");
                   3521:     fprintf(ficlog,"\n");
                   3522:   }
                   3523: 
1.203     brouard  3524:   /* printf("\n#Covariance matrix#\n"); */
                   3525:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   3526:   /* for (i=1;i<=npar;i++) {  */
                   3527:   /*   for (j=1;j<=npar;j++) {  */
                   3528:   /*     printf("%.6e ",matcov[i][j]); */
                   3529:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   3530:   /*   } */
                   3531:   /*   printf("\n"); */
                   3532:   /*   fprintf(ficlog,"\n"); */
                   3533:   /* } */
                   3534: 
1.126     brouard  3535:   /* Recompute Inverse */
1.203     brouard  3536:   /* for (i=1;i<=npar;i++) */
                   3537:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   3538:   /* ludcmp(a,npar,indx,&pd); */
                   3539: 
                   3540:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   3541: 
                   3542:   /* for (j=1;j<=npar;j++) { */
                   3543:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   3544:   /*   x[j]=1; */
                   3545:   /*   lubksb(a,npar,indx,x); */
                   3546:   /*   for (i=1;i<=npar;i++){  */
                   3547:   /*     y[i][j]=x[i]; */
                   3548:   /*     printf("%.3e ",y[i][j]); */
                   3549:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   3550:   /*   } */
                   3551:   /*   printf("\n"); */
                   3552:   /*   fprintf(ficlog,"\n"); */
                   3553:   /* } */
                   3554: 
                   3555:   /* Verifying the inverse matrix */
                   3556: #ifdef DEBUGHESS
                   3557:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  3558: 
1.203     brouard  3559:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   3560:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  3561: 
                   3562:   for (j=1;j<=npar;j++) {
                   3563:     for (i=1;i<=npar;i++){ 
1.203     brouard  3564:       printf("%.2f ",y[i][j]);
                   3565:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  3566:     }
                   3567:     printf("\n");
                   3568:     fprintf(ficlog,"\n");
                   3569:   }
1.203     brouard  3570: #endif
1.126     brouard  3571: 
                   3572:   free_matrix(a,1,npar,1,npar);
                   3573:   free_matrix(y,1,npar,1,npar);
                   3574:   free_vector(x,1,npar);
                   3575:   free_ivector(indx,1,npar);
1.203     brouard  3576:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  3577: 
                   3578: 
                   3579: }
                   3580: 
                   3581: /*************** hessian matrix ****************/
                   3582: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  3583: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  3584:   int i;
                   3585:   int l=1, lmax=20;
1.203     brouard  3586:   double k1,k2, res, fx;
1.132     brouard  3587:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  3588:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   3589:   int k=0,kmax=10;
                   3590:   double l1;
                   3591: 
                   3592:   fx=func(x);
                   3593:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  3594:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  3595:     l1=pow(10,l);
                   3596:     delts=delt;
                   3597:     for(k=1 ; k <kmax; k=k+1){
                   3598:       delt = delta*(l1*k);
                   3599:       p2[theta]=x[theta] +delt;
1.145     brouard  3600:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  3601:       p2[theta]=x[theta]-delt;
                   3602:       k2=func(p2)-fx;
                   3603:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  3604:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  3605:       
1.203     brouard  3606: #ifdef DEBUGHESSII
1.126     brouard  3607:       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);
                   3608:       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);
                   3609: #endif
                   3610:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   3611:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   3612:        k=kmax;
                   3613:       }
                   3614:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  3615:        k=kmax; l=lmax*10;
1.126     brouard  3616:       }
                   3617:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   3618:        delts=delt;
                   3619:       }
1.203     brouard  3620:     } /* End loop k */
1.126     brouard  3621:   }
                   3622:   delti[theta]=delts;
                   3623:   return res; 
                   3624:   
                   3625: }
                   3626: 
1.203     brouard  3627: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  3628: {
                   3629:   int i;
1.164     brouard  3630:   int l=1, lmax=20;
1.126     brouard  3631:   double k1,k2,k3,k4,res,fx;
1.132     brouard  3632:   double p2[MAXPARM+1];
1.203     brouard  3633:   int k, kmax=1;
                   3634:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  3635: 
                   3636:   int firstime=0;
1.203     brouard  3637:   
1.126     brouard  3638:   fx=func(x);
1.203     brouard  3639:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  3640:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  3641:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   3642:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  3643:     k1=func(p2)-fx;
                   3644:   
1.203     brouard  3645:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   3646:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  3647:     k2=func(p2)-fx;
                   3648:   
1.203     brouard  3649:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   3650:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  3651:     k3=func(p2)-fx;
                   3652:   
1.203     brouard  3653:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   3654:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  3655:     k4=func(p2)-fx;
1.203     brouard  3656:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   3657:     if(k1*k2*k3*k4 <0.){
1.208     brouard  3658:       firstime=1;
1.203     brouard  3659:       kmax=kmax+10;
1.208     brouard  3660:     }
                   3661:     if(kmax >=10 || firstime ==1){
1.218     brouard  3662:       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);
                   3663:       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  3664:       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);
                   3665:       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);
                   3666:     }
                   3667: #ifdef DEBUGHESSIJ
                   3668:     v1=hess[thetai][thetai];
                   3669:     v2=hess[thetaj][thetaj];
                   3670:     cv12=res;
                   3671:     /* Computing eigen value of Hessian matrix */
                   3672:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   3673:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   3674:     if ((lc2 <0) || (lc1 <0) ){
                   3675:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   3676:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   3677:       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);
                   3678:       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);
                   3679:     }
1.126     brouard  3680: #endif
                   3681:   }
                   3682:   return res;
                   3683: }
                   3684: 
1.203     brouard  3685:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   3686: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   3687: /* { */
                   3688: /*   int i; */
                   3689: /*   int l=1, lmax=20; */
                   3690: /*   double k1,k2,k3,k4,res,fx; */
                   3691: /*   double p2[MAXPARM+1]; */
                   3692: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   3693: /*   int k=0,kmax=10; */
                   3694: /*   double l1; */
                   3695:   
                   3696: /*   fx=func(x); */
                   3697: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   3698: /*     l1=pow(10,l); */
                   3699: /*     delts=delt; */
                   3700: /*     for(k=1 ; k <kmax; k=k+1){ */
                   3701: /*       delt = delti*(l1*k); */
                   3702: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   3703: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   3704: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   3705: /*       k1=func(p2)-fx; */
                   3706:       
                   3707: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   3708: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   3709: /*       k2=func(p2)-fx; */
                   3710:       
                   3711: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   3712: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   3713: /*       k3=func(p2)-fx; */
                   3714:       
                   3715: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   3716: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   3717: /*       k4=func(p2)-fx; */
                   3718: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   3719: /* #ifdef DEBUGHESSIJ */
                   3720: /*       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); */
                   3721: /*       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); */
                   3722: /* #endif */
                   3723: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   3724: /*     k=kmax; */
                   3725: /*       } */
                   3726: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   3727: /*     k=kmax; l=lmax*10; */
                   3728: /*       } */
                   3729: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   3730: /*     delts=delt; */
                   3731: /*       } */
                   3732: /*     } /\* End loop k *\/ */
                   3733: /*   } */
                   3734: /*   delti[theta]=delts; */
                   3735: /*   return res;  */
                   3736: /* } */
                   3737: 
                   3738: 
1.126     brouard  3739: /************** Inverse of matrix **************/
                   3740: void ludcmp(double **a, int n, int *indx, double *d) 
                   3741: { 
                   3742:   int i,imax,j,k; 
                   3743:   double big,dum,sum,temp; 
                   3744:   double *vv; 
                   3745:  
                   3746:   vv=vector(1,n); 
                   3747:   *d=1.0; 
                   3748:   for (i=1;i<=n;i++) { 
                   3749:     big=0.0; 
                   3750:     for (j=1;j<=n;j++) 
                   3751:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   3752:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   3753:     vv[i]=1.0/big; 
                   3754:   } 
                   3755:   for (j=1;j<=n;j++) { 
                   3756:     for (i=1;i<j;i++) { 
                   3757:       sum=a[i][j]; 
                   3758:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   3759:       a[i][j]=sum; 
                   3760:     } 
                   3761:     big=0.0; 
                   3762:     for (i=j;i<=n;i++) { 
                   3763:       sum=a[i][j]; 
                   3764:       for (k=1;k<j;k++) 
                   3765:        sum -= a[i][k]*a[k][j]; 
                   3766:       a[i][j]=sum; 
                   3767:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   3768:        big=dum; 
                   3769:        imax=i; 
                   3770:       } 
                   3771:     } 
                   3772:     if (j != imax) { 
                   3773:       for (k=1;k<=n;k++) { 
                   3774:        dum=a[imax][k]; 
                   3775:        a[imax][k]=a[j][k]; 
                   3776:        a[j][k]=dum; 
                   3777:       } 
                   3778:       *d = -(*d); 
                   3779:       vv[imax]=vv[j]; 
                   3780:     } 
                   3781:     indx[j]=imax; 
                   3782:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   3783:     if (j != n) { 
                   3784:       dum=1.0/(a[j][j]); 
                   3785:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   3786:     } 
                   3787:   } 
                   3788:   free_vector(vv,1,n);  /* Doesn't work */
                   3789: ;
                   3790: } 
                   3791: 
                   3792: void lubksb(double **a, int n, int *indx, double b[]) 
                   3793: { 
                   3794:   int i,ii=0,ip,j; 
                   3795:   double sum; 
                   3796:  
                   3797:   for (i=1;i<=n;i++) { 
                   3798:     ip=indx[i]; 
                   3799:     sum=b[ip]; 
                   3800:     b[ip]=b[i]; 
                   3801:     if (ii) 
                   3802:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   3803:     else if (sum) ii=i; 
                   3804:     b[i]=sum; 
                   3805:   } 
                   3806:   for (i=n;i>=1;i--) { 
                   3807:     sum=b[i]; 
                   3808:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   3809:     b[i]=sum/a[i][i]; 
                   3810:   } 
                   3811: } 
                   3812: 
                   3813: void pstamp(FILE *fichier)
                   3814: {
1.196     brouard  3815:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  3816: }
                   3817: 
                   3818: /************ Frequencies ********************/
1.220     brouard  3819:  void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
                   3820:                                                                         int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[],  \
                   3821:                                                                         int firstpass,  int lastpass, int stepm, int weightopt, char model[])
                   3822:  {  /* Some frequencies */
                   3823:   
                   3824:         int i, m, jk, j1, bool, z1,j;
                   3825:         int iind=0, iage=0;
                   3826:         int mi; /* Effective wave */
                   3827:         int first;
                   3828:         double ***freq; /* Frequencies */
1.224   ! brouard  3829:         double *meanq;
        !          3830:         double **meanqt;
1.220     brouard  3831:         double *pp, **prop, *posprop, *pospropt;
                   3832:         double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   3833:         char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   3834:         double agebegin, ageend;
                   3835:     
                   3836:         pp=vector(1,nlstate);
                   3837:         prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
                   3838:         posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   3839:         pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   3840:         /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
1.224   ! brouard  3841:         meanq=vector(1,nqveff);
        !          3842:         meanqt=matrix(1,lastpass,1,nqtveff);
1.220     brouard  3843:         strcpy(fileresp,"P_");
                   3844:         strcat(fileresp,fileresu);
                   3845:         /*strcat(fileresphtm,fileresu);*/
                   3846:         if((ficresp=fopen(fileresp,"w"))==NULL) {
                   3847:                 printf("Problem with prevalence resultfile: %s\n", fileresp);
                   3848:                 fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   3849:                 exit(0);
                   3850:         }
1.214     brouard  3851: 
1.220     brouard  3852:         strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   3853:         if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   3854:                 printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   3855:                 fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   3856:                 fflush(ficlog);
                   3857:                 exit(70); 
                   3858:         }
                   3859:         else{
                   3860:                 fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.214     brouard  3861: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   3862: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.220     brouard  3863:                                                 fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   3864:         }
                   3865:         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  3866:     
1.220     brouard  3867:         strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   3868:         if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   3869:                 printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   3870:                 fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   3871:                 fflush(ficlog);
                   3872:                 exit(70); 
                   3873:         }
                   3874:         else{
                   3875:                 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  3876: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   3877: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.220     brouard  3878:                                                 fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   3879:         }
                   3880:         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  3881: 
1.220     brouard  3882:         freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+3+AGEMARGE);
                   3883:         j1=0;
1.126     brouard  3884:   
1.224   ! brouard  3885:         j=ncoveff;
1.220     brouard  3886:         if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   3887: 
                   3888:         first=1;
                   3889: 
                   3890:         /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   3891:                        reference=low_education V1=0,V2=0
                   3892:                        med_educ                V1=1 V2=0, 
                   3893:                        high_educ               V1=0 V2=1
                   3894:                        Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcoveff 
                   3895:         */
1.126     brouard  3896: 
1.224   ! brouard  3897:         for (j1 = 1; j1 <= (int) pow(2,j); j1++){ /* Loop on covariates combination excluding varying and quantitatives */
1.220     brouard  3898:                 posproptt=0.;
                   3899:                 /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   3900:                         scanf("%d", i);*/
                   3901:                 for (i=-5; i<=nlstate+ndeath; i++)  
                   3902:                         for (jk=-5; jk<=nlstate+ndeath; jk++)  
                   3903:                                 for(m=iagemin; m <= iagemax+3; m++)
                   3904:                                         freq[i][jk][m]=0;
                   3905:       
                   3906:                 for (i=1; i<=nlstate; i++)  {
                   3907:                         for(m=iagemin; m <= iagemax+3; m++)
                   3908:                                 prop[i][m]=0;
                   3909:                         posprop[i]=0;
                   3910:                         pospropt[i]=0;
                   3911:                 }
1.224   ! brouard  3912:                 for (z1=1; z1<= nqveff; z1++) {  
        !          3913:                         meanq[z1]+=0.;
        !          3914:                         for(m=1;m<=lastpass;m++){
        !          3915:                                 meanqt[m][z1]=0.;
        !          3916:                         }
        !          3917:                 }
1.220     brouard  3918:       
                   3919:                 dateintsum=0;
                   3920:                 k2cpt=0;
1.224   ! brouard  3921:      /* For that comination of covariate j1, we count and print the frequencies */
1.220     brouard  3922:                 for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   3923:                         bool=1;
1.224   ! brouard  3924:                         if (nqveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
        !          3925:                                 for (z1=1; z1<= nqveff; z1++) {  
        !          3926:                                         meanq[z1]+=coqvar[Tvar[z1]][iind];
        !          3927:                                 }
        !          3928:                                 for (z1=1; z1<=ncoveff; z1++) {  
        !          3929:                                         /* if(Tvaraff[z1] ==-20){ */
        !          3930:                                         /*      /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
        !          3931:                                         /* }else  if(Tvaraff[z1] ==-10){ */
        !          3932:                                         /*      /\* sumnew+=coqvar[z1][iind]; *\/ */
        !          3933:                                         /* }else  */
1.220     brouard  3934:                                         if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
1.224   ! brouard  3935:                                                 /* Tests if this individual i responded to j1 (V4=1 V3=0) */
1.220     brouard  3936:                                                 bool=0;
                   3937:                                                 /* 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", 
1.198     brouard  3938:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   3939:                 j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
1.220     brouard  3940:                                                 /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   3941:                                         } 
                   3942:                                 } /* end z1 */
                   3943:                         } /* cptcovn > 0 */
                   3944: 
1.224   ! brouard  3945:                         if (bool==1){ /* We selected an individual iin satisfying combination j1 */
1.220     brouard  3946:                                 /* for(m=firstpass; m<=lastpass; m++){ */
                   3947:                                 for(mi=1; mi<wav[iind];mi++){
                   3948:                                         m=mw[mi][iind];
                   3949:                                         /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   3950:                                                        and mw[mi+1][iind]. dh depends on stepm. */
                   3951:                                         agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   3952:                                         ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   3953:                                         if(m >=firstpass && m <=lastpass){
                   3954:                                                 k2=anint[m][iind]+(mint[m][iind]/12.);
                   3955:                                                 /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   3956:                                                 if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   3957:                                                 if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   3958:                                                 if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   3959:                                                         prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   3960:                                                 if (m<lastpass) {
                   3961:                                                         /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   3962:                                                         /*   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]); */
                   3963:                                                         if(s[m][iind]==-1)
                   3964:                                                                 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.));
                   3965:                                                         freq[s[m][iind]][s[m+1][iind]][(int)agev[m][iind]] += weight[iind]; /* At age of beginning of transition, where status is known */
                   3966:                                                         /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   3967:                                                         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 */
                   3968:                                                 }
                   3969:                                         }  
                   3970:                                         if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99)) {
                   3971:                                                 dateintsum=dateintsum+k2;
                   3972:                                                 k2cpt++;
                   3973:                                                 /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
                   3974:                                         }
                   3975:                                         /*}*/
                   3976:                                 } /* end m */
                   3977:                         } /* end bool */
                   3978:                 } /* end iind = 1 to imx */
                   3979:        /* prop[s][age] is feeded for any initial and valid live state as well as
                   3980:                                        freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   3981: 
                   3982: 
                   3983:                 /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   3984:                 pstamp(ficresp);
1.224   ! brouard  3985:                 if  (ncoveff>0) {
1.220     brouard  3986:                         fprintf(ficresp, "\n#********** Variable "); 
                   3987:                         fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   3988:                         fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
1.224   ! brouard  3989:                         for (z1=1; z1<=ncoveff; z1++){
1.220     brouard  3990:                                 fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   3991:                                 fprintf(ficresphtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   3992:                                 fprintf(ficresphtmfr, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   3993:                         }
                   3994:                         fprintf(ficresp, "**********\n#");
                   3995:                         fprintf(ficresphtm, "**********</h3>\n");
                   3996:                         fprintf(ficresphtmfr, "**********</h3>\n");
                   3997:                         fprintf(ficlog, "\n#********** Variable "); 
1.224   ! brouard  3998:                         for (z1=1; z1<=ncoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.220     brouard  3999:                         fprintf(ficlog, "**********\n");
                   4000:                 }
                   4001:                 fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
                   4002:                 for(i=1; i<=nlstate;i++) {
                   4003:                         fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
                   4004:                         fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   4005:                 }
                   4006:                 fprintf(ficresp, "\n");
                   4007:                 fprintf(ficresphtm, "\n");
                   4008:       
                   4009:                 /* Header of frequency table by age */
                   4010:                 fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   4011:                 fprintf(ficresphtmfr,"<th>Age</th> ");
                   4012:                 for(jk=-1; jk <=nlstate+ndeath; jk++){
                   4013:                         for(m=-1; m <=nlstate+ndeath; m++){
                   4014:                                 if(jk!=0 && m!=0)
                   4015:                                         fprintf(ficresphtmfr,"<th>%d%d</th> ",jk,m);
                   4016:                         }
                   4017:                 }
                   4018:                 fprintf(ficresphtmfr, "\n");
1.214     brouard  4019:       
1.220     brouard  4020:                 /* For each age */
                   4021:                 for(iage=iagemin; iage <= iagemax+3; iage++){
                   4022:                         fprintf(ficresphtm,"<tr>");
                   4023:                         if(iage==iagemax+1){
                   4024:                                 fprintf(ficlog,"1");
                   4025:                                 fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   4026:                         }else if(iage==iagemax+2){
                   4027:                                 fprintf(ficlog,"0");
                   4028:                                 fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   4029:                         }else if(iage==iagemax+3){
                   4030:                                 fprintf(ficlog,"Total");
                   4031:                                 fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   4032:                         }else{
                   4033:                                 if(first==1){
                   4034:                                         first=0;
                   4035:                                         printf("See log file for details...\n");
                   4036:                                 }
                   4037:                                 fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   4038:                                 fprintf(ficlog,"Age %d", iage);
                   4039:                         }
                   4040:                         for(jk=1; jk <=nlstate ; jk++){
                   4041:                                 for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   4042:                                         pp[jk] += freq[jk][m][iage]; 
                   4043:                         }
                   4044:                         for(jk=1; jk <=nlstate ; jk++){
                   4045:                                 for(m=-1, pos=0; m <=0 ; m++)
                   4046:                                         pos += freq[jk][m][iage];
                   4047:                                 if(pp[jk]>=1.e-10){
                   4048:                                         if(first==1){
                   4049:                                                 printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   4050:                                         }
                   4051:                                         fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   4052:                                 }else{
                   4053:                                         if(first==1)
                   4054:                                                 printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   4055:                                         fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   4056:                                 }
                   4057:                         }
                   4058: 
                   4059:                         for(jk=1; jk <=nlstate ; jk++){ 
                   4060:                                 /* posprop[jk]=0; */
                   4061:                                 for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   4062:                                         pp[jk] += freq[jk][m][iage];
                   4063:                         }      /* pp[jk] is the total number of transitions starting from state jk and any ending status until this age */
                   4064: 
                   4065:                         for(jk=1,pos=0, pospropta=0.; jk <=nlstate ; jk++){
                   4066:                                 pos += pp[jk]; /* pos is the total number of transitions until this age */
                   4067:                                 posprop[jk] += prop[jk][iage]; /* prop is the number of transitions from a live state
                   4068:                                                                                                                                                                         from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   4069:                                 pospropta += prop[jk][iage]; /* prop is the number of transitions from a live state
                   4070:                                                                                                                                                                         from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   4071:                         }
                   4072:                         for(jk=1; jk <=nlstate ; jk++){
                   4073:                                 if(pos>=1.e-5){
                   4074:                                         if(first==1)
                   4075:                                                 printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   4076:                                         fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   4077:                                 }else{
                   4078:                                         if(first==1)
                   4079:                                                 printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   4080:                                         fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   4081:                                 }
                   4082:                                 if( iage <= iagemax){
                   4083:                                         if(pos>=1.e-5){
                   4084:                                                 fprintf(ficresp," %d %.5f %.0f %.0f",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
                   4085:                                                 fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
                   4086:                                                 /*probs[iage][jk][j1]= pp[jk]/pos;*/
                   4087:                                                 /*printf("\niage=%d jk=%d j1=%d %.5f %.0f %.0f %f",iage,jk,j1,pp[jk]/pos, pp[jk],pos,probs[iage][jk][j1]);*/
                   4088:                                         }
                   4089:                                         else{
                   4090:                                                 fprintf(ficresp," %d NaNq %.0f %.0f",iage,prop[jk][iage],pospropta);
                   4091:                                                 fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[jk][iage],pospropta);
                   4092:                                         }
                   4093:                                 }
                   4094:                                 pospropt[jk] +=posprop[jk];
                   4095:                         } /* end loop jk */
                   4096:                         /* pospropt=0.; */
                   4097:                         for(jk=-1; jk <=nlstate+ndeath; jk++){
                   4098:                                 for(m=-1; m <=nlstate+ndeath; m++){
                   4099:                                         if(freq[jk][m][iage] !=0 ) { /* minimizing output */
                   4100:                                                 if(first==1){
                   4101:                                                         printf(" %d%d=%.0f",jk,m,freq[jk][m][iage]);
                   4102:                                                 }
                   4103:                                                 fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][iage]);
                   4104:                                         }
                   4105:                                         if(jk!=0 && m!=0)
                   4106:                                                 fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[jk][m][iage]);
                   4107:                                 }
                   4108:                         } /* end loop jk */
                   4109:                         posproptt=0.; 
                   4110:                         for(jk=1; jk <=nlstate; jk++){
                   4111:                                 posproptt += pospropt[jk];
                   4112:                         }
                   4113:                         fprintf(ficresphtmfr,"</tr>\n ");
                   4114:                         if(iage <= iagemax){
                   4115:                                 fprintf(ficresp,"\n");
                   4116:                                 fprintf(ficresphtm,"</tr>\n");
                   4117:                         }
                   4118:                         if(first==1)
                   4119:                                 printf("Others in log...\n");
                   4120:                         fprintf(ficlog,"\n");
                   4121:                 } /* end loop age iage */
                   4122:                 fprintf(ficresphtm,"<tr><th>Tot</th>");
                   4123:                 for(jk=1; jk <=nlstate ; jk++){
                   4124:                         if(posproptt < 1.e-5){
1.221     brouard  4125:                                 fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[jk],posproptt);  
                   4126:                         }else{
1.220     brouard  4127:                                 fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[jk]/posproptt,pospropt[jk],posproptt);   
                   4128:                         }
                   4129:                 }
                   4130:                 fprintf(ficresphtm,"</tr>\n");
                   4131:                 fprintf(ficresphtm,"</table>\n");
                   4132:                 fprintf(ficresphtmfr,"</table>\n");
                   4133:                 if(posproptt < 1.e-5){
                   4134:                         fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   4135:                         fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   4136:                         fprintf(ficres,"\n  This combination (%d) is not valid and no result will be produced\n\n",j1);
                   4137:                         invalidvarcomb[j1]=1;
                   4138:                 }else{
                   4139:                         fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
                   4140:                         invalidvarcomb[j1]=0;
                   4141:                 }
                   4142:                 fprintf(ficresphtmfr,"</table>\n");
                   4143:         } /* end selected combination of covariate j1 */
                   4144:         dateintmean=dateintsum/k2cpt; 
                   4145:                 
                   4146:         fclose(ficresp);
                   4147:         fclose(ficresphtm);
                   4148:         fclose(ficresphtmfr);
1.224   ! brouard  4149:         free_vector(meanq,1,nqveff);
        !          4150:         free_matrix(meanqt,1,lastpass,1,nqtveff);
1.220     brouard  4151:         free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+3+AGEMARGE);
                   4152:         free_vector(pospropt,1,nlstate);
                   4153:         free_vector(posprop,1,nlstate);
                   4154:         free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+3+AGEMARGE);
                   4155:         free_vector(pp,1,nlstate);
1.224   ! brouard  4156:         /* End of freqsummary */
1.220     brouard  4157:  }
1.126     brouard  4158: 
                   4159: /************ Prevalence ********************/
1.222     brouard  4160:  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)
                   4161:  {  
                   4162:    /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   4163:       in each health status at the date of interview (if between dateprev1 and dateprev2).
                   4164:       We still use firstpass and lastpass as another selection.
                   4165:    */
1.126     brouard  4166:  
1.222     brouard  4167:    int i, m, jk, j1, bool, z1,j;
                   4168:    int mi; /* Effective wave */
                   4169:    int iage;
                   4170:    double agebegin, ageend;
                   4171: 
                   4172:    double **prop;
                   4173:    double posprop; 
                   4174:    double  y2; /* in fractional years */
                   4175:    int iagemin, iagemax;
                   4176:    int first; /** to stop verbosity which is redirected to log file */
                   4177: 
                   4178:    iagemin= (int) agemin;
                   4179:    iagemax= (int) agemax;
                   4180:    /*pp=vector(1,nlstate);*/
                   4181:    prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
                   4182:    /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   4183:    j1=0;
                   4184:   
                   4185:    /*j=cptcoveff;*/
                   4186:    if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   4187:   
                   4188:    first=1;
1.224   ! brouard  4189:    for(j1=1; j1<= (int) pow(2,nqveff);j1++){ /* For each combination of covariate */
1.222     brouard  4190:      for (i=1; i<=nlstate; i++)  
                   4191:        for(iage=iagemin-AGEMARGE; iage <= iagemax+3+AGEMARGE; iage++)
                   4192:         prop[i][iage]=0.0;
                   4193:     
                   4194:      for (i=1; i<=imx; i++) { /* Each individual */
                   4195:        bool=1;
                   4196:        if  (cptcovn>0) {  /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
1.224   ! brouard  4197:         for (z1=1; z1<=nqveff; z1++) /* For each covariate, look at the value for individual i and checks if it is equal to the corresponding value of this covariate according to current combination j1*/
1.222     brouard  4198:           if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) 
                   4199:             bool=0;
                   4200:        } 
                   4201:        if (bool==1) { /* For this combination of covariates values, this individual fits */
                   4202:         /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   4203:         for(mi=1; mi<wav[i];mi++){
                   4204:           m=mw[mi][i];
                   4205:           agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   4206:           /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   4207:           if(m >=firstpass && m <=lastpass){
                   4208:             y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   4209:             if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   4210:               if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   4211:               if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   4212:               if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+3+AGEMARGE){
                   4213:                 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); 
                   4214:                 exit(1);
                   4215:               }
                   4216:               if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   4217:                 /*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]]);*/
                   4218:                 prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   4219:                 prop[s[m][i]][iagemax+3] += weight[i]; 
                   4220:               } /* end valid statuses */ 
                   4221:             } /* end selection of dates */
                   4222:           } /* end selection of waves */
                   4223:         } /* end effective waves */
                   4224:        } /* end bool */
                   4225:      }
                   4226:      for(i=iagemin; i <= iagemax+3; i++){  
                   4227:        for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   4228:         posprop += prop[jk][i]; 
                   4229:        } 
                   4230:       
                   4231:        for(jk=1; jk <=nlstate ; jk++){     
                   4232:         if( i <=  iagemax){ 
                   4233:           if(posprop>=1.e-5){ 
                   4234:             probs[i][jk][j1]= prop[jk][i]/posprop;
                   4235:           } else{
                   4236:             if(first==1){
                   4237:               first=0;
                   4238:               printf("Warning Observed prevalence probs[%d][%d][%d]=%lf because of lack of cases\nSee others on log file...\n",jk,i,j1,probs[i][jk][j1]);
                   4239:             }
                   4240:           }
                   4241:         } 
                   4242:        }/* end jk */ 
                   4243:      }/* end i */ 
                   4244:      /*} *//* end i1 */
                   4245:    } /* end j1 */
                   4246:   
                   4247:    /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   4248:    /*free_vector(pp,1,nlstate);*/
                   4249:    free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+3+AGEMARGE);
                   4250:  }  /* End of prevalence */
1.126     brouard  4251: 
                   4252: /************* Waves Concatenation ***************/
                   4253: 
                   4254: 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)
                   4255: {
                   4256:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   4257:      Death is a valid wave (if date is known).
                   4258:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   4259:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4260:      and mw[mi+1][i]. dh depends on stepm.
                   4261:      */
                   4262: 
1.224   ! brouard  4263:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  4264:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   4265:      double sum=0., jmean=0.;*/
1.224   ! brouard  4266:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  4267:   int j, k=0,jk, ju, jl;
                   4268:   double sum=0.;
                   4269:   first=0;
1.214     brouard  4270:   firstwo=0;
1.217     brouard  4271:   firsthree=0;
1.218     brouard  4272:   firstfour=0;
1.164     brouard  4273:   jmin=100000;
1.126     brouard  4274:   jmax=-1;
                   4275:   jmean=0.;
1.224   ! brouard  4276: 
        !          4277: /* Treating live states */
1.214     brouard  4278:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224   ! brouard  4279:     mi=0;  /* First valid wave */
        !          4280:                mli=0; /* Last valid wave */
1.126     brouard  4281:     m=firstpass;
1.214     brouard  4282:     while(s[m][i] <= nlstate){  /* a live state */
1.224   ! brouard  4283:                        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 */
        !          4284:                                mli=m-1;/* mw[++mi][i]=m-1; */
        !          4285:                        }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 */
1.223     brouard  4286:                                mw[++mi][i]=m;
1.224   ! brouard  4287:                                mli=m;
        !          4288:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
        !          4289:       if(m < lastpass){ /* m < lastpass, standard case */
        !          4290:                                m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  4291:       }
1.224   ! brouard  4292:                        else{ /* m >= lastpass, eventual special issue with warning */
        !          4293: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
        !          4294:                                break;
        !          4295: #else
1.223     brouard  4296:                                if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){
                   4297:                                        if(firsthree == 0){
1.224   ! brouard  4298:                                                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);
1.223     brouard  4299:                                                firsthree=1;
                   4300:                                        }
1.224   ! brouard  4301:                                        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);
1.223     brouard  4302:                                        mw[++mi][i]=m;
1.224   ! brouard  4303:                                        mli=m;
1.223     brouard  4304:                                }
                   4305:                                if(s[m][i]==-2){ /* Vital status is really unknown */
                   4306:                                        nbwarn++;
                   4307:                                        if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified? */
                   4308:                                                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);
1.224   ! brouard  4309:                                                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);
1.223     brouard  4310:                                        }
                   4311:                                        break;
                   4312:                                }
                   4313:                                break;
1.224   ! brouard  4314: #endif
        !          4315:                        }/* End m >= lastpass */
1.126     brouard  4316:     }/* end while */
1.224   ! brouard  4317: 
        !          4318:        /* 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  4319:     /* After last pass */
1.224   ! brouard  4320: /* Treating death states */
1.214     brouard  4321:     if (s[m][i] > nlstate){  /* In a death state */
1.224   ! brouard  4322:                        /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
        !          4323:                        /* } */
1.126     brouard  4324:       mi++;    /* Death is another wave */
                   4325:       /* if(mi==0)  never been interviewed correctly before death */
1.223     brouard  4326:                        /* Only death is a correct wave */
1.126     brouard  4327:       mw[mi][i]=m;
1.224   ! brouard  4328:     }
        !          4329: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
        !          4330:                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  4331:       /* m++; */
                   4332:       /* mi++; */
                   4333:       /* s[m][i]=nlstate+1;  /\* We are setting the status to the last of non live state *\/ */
                   4334:       /* mw[mi][i]=m; */
1.218     brouard  4335:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.224   ! brouard  4336:                                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 */
        !          4337:                                        nbwarn++;
        !          4338:                                        if(firstfiv==0){
        !          4339:                                                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 );
        !          4340:                                                firstfiv=1;
        !          4341:                                        }else{
        !          4342:                                                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 );
        !          4343:                                        }
        !          4344:                                }else{ /* Death occured afer last wave potential bias */
        !          4345:                                        nberr++;
        !          4346:                                        if(firstwo==0){
        !          4347:                                                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 );
        !          4348:                                                firstwo=1;
        !          4349:                                        }
        !          4350:                                        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 );
1.223     brouard  4351:                                }
1.218     brouard  4352:       }else{ /* end date of interview is known */
1.223     brouard  4353:                                /* death is known but not confirmed by death status at any wave */
                   4354:                                if(firstfour==0){
                   4355:                                        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 );
                   4356:                                        firstfour=1;
                   4357:                                }
                   4358:                                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  4359:       }
1.224   ! brouard  4360:     } /* end if date of death is known */
        !          4361: #endif
        !          4362:     wav[i]=mi; /* mi should be the last effective wave (or mli) */
        !          4363:     /* wav[i]=mw[mi][i]; */
1.126     brouard  4364:     if(mi==0){
                   4365:       nbwarn++;
                   4366:       if(first==0){
1.223     brouard  4367:                                printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   4368:                                first=1;
1.126     brouard  4369:       }
                   4370:       if(first==1){
1.223     brouard  4371:                                fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  4372:       }
                   4373:     } /* end mi==0 */
                   4374:   } /* End individuals */
1.214     brouard  4375:   /* wav and mw are no more changed */
1.223     brouard  4376:        
1.214     brouard  4377:   
1.126     brouard  4378:   for(i=1; i<=imx; i++){
                   4379:     for(mi=1; mi<wav[i];mi++){
                   4380:       if (stepm <=0)
1.223     brouard  4381:                                dh[mi][i]=1;
1.126     brouard  4382:       else{
1.223     brouard  4383:                                if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                   4384:                                        if (agedc[i] < 2*AGESUP) {
                   4385:                                                j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   4386:                                                if(j==0) j=1;  /* Survives at least one month after exam */
                   4387:                                                else if(j<0){
                   4388:                                                        nberr++;
                   4389:                                                        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]);
                   4390:                                                        j=1; /* Temporary Dangerous patch */
                   4391:                                                        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);
                   4392:                                                        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]);
                   4393:                                                        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);
                   4394:                                                }
                   4395:                                                k=k+1;
                   4396:                                                if (j >= jmax){
                   4397:                                                        jmax=j;
                   4398:                                                        ijmax=i;
                   4399:                                                }
                   4400:                                                if (j <= jmin){
                   4401:                                                        jmin=j;
                   4402:                                                        ijmin=i;
                   4403:                                                }
                   4404:                                                sum=sum+j;
                   4405:                                                /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   4406:                                                /*        printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   4407:                                        }
                   4408:                                }
                   4409:                                else{
                   4410:                                        j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  4411: /*       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  4412:                                        
                   4413:                                        k=k+1;
                   4414:                                        if (j >= jmax) {
                   4415:                                                jmax=j;
                   4416:                                                ijmax=i;
                   4417:                                        }
                   4418:                                        else if (j <= jmin){
                   4419:                                                jmin=j;
                   4420:                                                ijmin=i;
                   4421:                                        }
                   4422:                                        /*          if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   4423:                                        /*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]);*/
                   4424:                                        if(j<0){
                   4425:                                                nberr++;
                   4426:                                                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]);
                   4427:                                                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]);
                   4428:                                        }
                   4429:                                        sum=sum+j;
                   4430:                                }
                   4431:                                jk= j/stepm;
                   4432:                                jl= j -jk*stepm;
                   4433:                                ju= j -(jk+1)*stepm;
                   4434:                                if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   4435:                                        if(jl==0){
                   4436:                                                dh[mi][i]=jk;
                   4437:                                                bh[mi][i]=0;
                   4438:                                        }else{ /* We want a negative bias in order to only have interpolation ie
                   4439:                                                                        * to avoid the price of an extra matrix product in likelihood */
                   4440:                                                dh[mi][i]=jk+1;
                   4441:                                                bh[mi][i]=ju;
                   4442:                                        }
                   4443:                                }else{
                   4444:                                        if(jl <= -ju){
                   4445:                                                dh[mi][i]=jk;
                   4446:                                                bh[mi][i]=jl;   /* bias is positive if real duration
                   4447:                                                                                                         * is higher than the multiple of stepm and negative otherwise.
                   4448:                                                                                                         */
                   4449:                                        }
                   4450:                                        else{
                   4451:                                                dh[mi][i]=jk+1;
                   4452:                                                bh[mi][i]=ju;
                   4453:                                        }
                   4454:                                        if(dh[mi][i]==0){
                   4455:                                                dh[mi][i]=1; /* At least one step */
                   4456:                                                bh[mi][i]=ju; /* At least one step */
                   4457:                                                /*  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);*/
                   4458:                                        }
                   4459:                                } /* end if mle */
1.126     brouard  4460:       }
                   4461:     } /* end wave */
                   4462:   }
                   4463:   jmean=sum/k;
                   4464:   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  4465:   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.126     brouard  4466:  }
                   4467: 
                   4468: /*********** Tricode ****************************/
1.220     brouard  4469:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.126     brouard  4470: {
1.144     brouard  4471:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   4472:   /*     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  4473:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.224   ! brouard  4474:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
        !          4475:    * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
1.144     brouard  4476:   */
1.130     brouard  4477: 
1.145     brouard  4478:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136     brouard  4479:   int modmaxcovj=0; /* Modality max of covariates j */
1.145     brouard  4480:   int cptcode=0; /* Modality max of covariates j */
                   4481:   int modmincovj=0; /* Modality min of covariates j */
                   4482: 
                   4483: 
1.220     brouard  4484:   /* cptcoveff=0;  */
1.224   ! brouard  4485:        /* *cptcov=0; */
1.126     brouard  4486:  
1.144     brouard  4487:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  4488: 
1.224   ! brouard  4489:   /* Loop on covariates without age and products and no quantitative variable */
        !          4490:   /* for (j=1; j<=(cptcovs); j++) { /\* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only *\/ */
        !          4491:   for (j=1; j<=(*cptcov); j++) { /* From model V1 + V2*age + V3 + V3*V4 keeps V1 + V3 = 2 only */
1.192     brouard  4492:     for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.186     brouard  4493:     for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the 
1.224   ! brouard  4494:                                                                                                                                modality of this covariate Vj*/
        !          4495:                        if(Tvar[j]  >=1 && Tvar[j]  <= *cptcov){ /* A real fixed covariate */
        !          4496:                                ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
        !          4497:                                                                                                                                                        * If product of Vn*Vm, still boolean *:
        !          4498:                                                                                                                                                        * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
        !          4499:                                                                                                                                                        * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
        !          4500:                                /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
        !          4501:                                         modality of the nth covariate of individual i. */
        !          4502:                                if (ij > modmaxcovj)
        !          4503:                                        modmaxcovj=ij; 
        !          4504:                                else if (ij < modmincovj) 
        !          4505:                                        modmincovj=ij; 
        !          4506:                                if ((ij < -1) && (ij > NCOVMAX)){
        !          4507:                                        printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
        !          4508:                                        exit(1);
        !          4509:                                }else
        !          4510:                                        Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145     brouard  4511:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126     brouard  4512:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136     brouard  4513:       /* getting the maximum value of the modality of the covariate
1.224   ! brouard  4514:                                 (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
        !          4515:                                 female ies 1, then modmaxcovj=1.*/
        !          4516:                        }
        !          4517:                } /* end for loop on individuals i */
1.145     brouard  4518:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
1.192     brouard  4519:     fprintf(ficlog," Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
1.145     brouard  4520:     cptcode=modmaxcovj;
1.137     brouard  4521:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.224   ! brouard  4522:                /*for (i=0; i<=cptcode; i++) {*/
1.192     brouard  4523:     for (k=modmincovj;  k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
                   4524:       printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   4525:       fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   4526:       if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
1.219     brouard  4527:                                if( k != -1){
                   4528:                                        ncodemax[j]++;  /* ncodemax[j]= Number of modalities of the j th
                   4529:                                                                                                                 covariate for which somebody answered excluding 
                   4530:                                                                                                                 undefined. Usually 2: 0 and 1. */
                   4531:                                }
                   4532:                                ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
                   4533:                                                                                                                                covariate for which somebody answered including 
                   4534:                                                                                                                                undefined. Usually 3: -1, 0 and 1. */
1.145     brouard  4535:       }
                   4536:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
1.224   ! brouard  4537:                         * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131     brouard  4538:     } /* Ndum[-1] number of undefined modalities */
1.219     brouard  4539:                
1.136     brouard  4540:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.186     brouard  4541:     /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. 
                   4542:        If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125;
1.145     brouard  4543:        modmincovj=3; modmaxcovj = 7;
1.186     brouard  4544:        There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
                   4545:        which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
                   4546:        defining two dummy variables: variables V1_1 and V1_2.
1.145     brouard  4547:        nbcode[Tvar[j]][ij]=k;
                   4548:        nbcode[Tvar[j]][1]=0;
                   4549:        nbcode[Tvar[j]][2]=1;
                   4550:        nbcode[Tvar[j]][3]=2;
1.197     brouard  4551:        To be continued (not working yet).
1.145     brouard  4552:     */
1.197     brouard  4553:     ij=0; /* ij is similar to i but can jump over null modalities */
                   4554:     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*/
                   4555:        if (Ndum[i] == 0) { /* If nobody responded to this modality k */
1.219     brouard  4556:                                break;
                   4557:                        }
1.224   ! brouard  4558:                        ij++;
        !          4559:                        nbcode[Tvar[j]][ij]=i;  /* stores the original value of modality i in an array nbcode, ij modality from 1 to last non-nul modality.*/
        !          4560:                        cptcode = ij; /* New max modality for covar j */
1.192     brouard  4561:     } /* end of loop on modality i=-1 to 1 or more */
1.224   ! brouard  4562:                
1.192     brouard  4563:     /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
                   4564:     /*         /\*recode from 0 *\/ */
                   4565:     /*                                      k is a modality. If we have model=V1+V1*sex  */
                   4566:     /*                                      then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
                   4567:     /*                                   But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
                   4568:     /*         } */
                   4569:     /*         /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
                   4570:     /*         if (ij > ncodemax[j]) { */
                   4571:     /*           printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
                   4572:     /*           fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
                   4573:     /*           break; */
                   4574:     /*         } */
                   4575:     /*   }  /\* end of loop on modality k *\/ */
1.137     brouard  4576:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   4577:   
1.219     brouard  4578:        for (k=-1; k< maxncov; k++) Ndum[k]=0; 
1.137     brouard  4579:   
1.187     brouard  4580:   for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
1.219     brouard  4581:                /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   4582:                ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
                   4583:                Ndum[ij]++; /* Might be supersed V1 + V1*age */
1.224   ! brouard  4584:        } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
1.219     brouard  4585:        
                   4586:        ij=0;
                   4587:        for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   4588:                /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   4589:                if((Ndum[i]!=0) && (i<=ncovcol)){
                   4590:                        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
1.224   ! brouard  4591:                        Tvaraff[++ij]=i; /*For printing (unclear) */
        !          4592:                }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){
        !          4593:                        Tvaraff[++ij]=-10; /* Dont'n know how to treat quantitative variables yet */
        !          4594:                }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){
        !          4595:                        Tvaraff[++ij]=i; /*For printing (unclear) */
        !          4596:                }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){
        !          4597:                 Tvaraff[++ij]=-20; /* Dont'n know how to treat quantitative variables yet */
1.219     brouard  4598:                }
1.224   ! brouard  4599:        } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
1.219     brouard  4600:        /* ij--; */
1.220     brouard  4601:        /* cptcoveff=ij; /\*Number of total covariates*\/ */
1.224   ! brouard  4602:        *cptcov=ij; /*Number of total real effective covariates: effective
        !          4603:                                                         * because they can be excluded from the model and real
        !          4604:                                                         * if in the model but excluded because missing values*/
1.126     brouard  4605: }
                   4606: 
1.145     brouard  4607: 
1.126     brouard  4608: /*********** Health Expectancies ****************/
                   4609: 
1.127     brouard  4610: 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  4611: 
                   4612: {
                   4613:   /* Health expectancies, no variances */
1.164     brouard  4614:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  4615:   int nhstepma, nstepma; /* Decreasing with age */
                   4616:   double age, agelim, hf;
                   4617:   double ***p3mat;
                   4618:   double eip;
                   4619: 
                   4620:   pstamp(ficreseij);
                   4621:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   4622:   fprintf(ficreseij,"# Age");
                   4623:   for(i=1; i<=nlstate;i++){
                   4624:     for(j=1; j<=nlstate;j++){
                   4625:       fprintf(ficreseij," e%1d%1d ",i,j);
                   4626:     }
                   4627:     fprintf(ficreseij," e%1d. ",i);
                   4628:   }
                   4629:   fprintf(ficreseij,"\n");
                   4630: 
                   4631:   
                   4632:   if(estepm < stepm){
                   4633:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4634:   }
                   4635:   else  hstepm=estepm;   
                   4636:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   4637:    * This is mainly to measure the difference between two models: for example
                   4638:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   4639:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   4640:    * progression in between and thus overestimating or underestimating according
                   4641:    * to the curvature of the survival function. If, for the same date, we 
                   4642:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   4643:    * to compare the new estimate of Life expectancy with the same linear 
                   4644:    * hypothesis. A more precise result, taking into account a more precise
                   4645:    * curvature will be obtained if estepm is as small as stepm. */
                   4646: 
                   4647:   /* For example we decided to compute the life expectancy with the smallest unit */
                   4648:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   4649:      nhstepm is the number of hstepm from age to agelim 
                   4650:      nstepm is the number of stepm from age to agelin. 
                   4651:      Look at hpijx to understand the reason of that which relies in memory size
                   4652:      and note for a fixed period like estepm months */
                   4653:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   4654:      survival function given by stepm (the optimization length). Unfortunately it
                   4655:      means that if the survival funtion is printed only each two years of age and if
                   4656:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   4657:      results. So we changed our mind and took the option of the best precision.
                   4658:   */
                   4659:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   4660: 
                   4661:   agelim=AGESUP;
                   4662:   /* If stepm=6 months */
                   4663:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   4664:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   4665:     
                   4666: /* nhstepm age range expressed in number of stepm */
                   4667:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   4668:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   4669:   /* if (stepm >= YEARM) hstepm=1;*/
                   4670:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   4671:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4672: 
                   4673:   for (age=bage; age<=fage; age ++){ 
                   4674:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   4675:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   4676:     /* if (stepm >= YEARM) hstepm=1;*/
                   4677:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   4678: 
                   4679:     /* If stepm=6 months */
                   4680:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   4681:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   4682:     
                   4683:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   4684:     
                   4685:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   4686:     
                   4687:     printf("%d|",(int)age);fflush(stdout);
                   4688:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   4689:     
                   4690:     /* Computing expectancies */
                   4691:     for(i=1; i<=nlstate;i++)
                   4692:       for(j=1; j<=nlstate;j++)
                   4693:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   4694:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   4695:          
                   4696:          /* 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]);*/
                   4697: 
                   4698:        }
                   4699: 
                   4700:     fprintf(ficreseij,"%3.0f",age );
                   4701:     for(i=1; i<=nlstate;i++){
                   4702:       eip=0;
                   4703:       for(j=1; j<=nlstate;j++){
                   4704:        eip +=eij[i][j][(int)age];
                   4705:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   4706:       }
                   4707:       fprintf(ficreseij,"%9.4f", eip );
                   4708:     }
                   4709:     fprintf(ficreseij,"\n");
                   4710:     
                   4711:   }
                   4712:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4713:   printf("\n");
                   4714:   fprintf(ficlog,"\n");
                   4715:   
                   4716: }
                   4717: 
1.127     brouard  4718: 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  4719: 
                   4720: {
                   4721:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  4722:      to initial status i, ei. .
1.126     brouard  4723:   */
                   4724:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   4725:   int nhstepma, nstepma; /* Decreasing with age */
                   4726:   double age, agelim, hf;
                   4727:   double ***p3matp, ***p3matm, ***varhe;
                   4728:   double **dnewm,**doldm;
                   4729:   double *xp, *xm;
                   4730:   double **gp, **gm;
                   4731:   double ***gradg, ***trgradg;
                   4732:   int theta;
                   4733: 
                   4734:   double eip, vip;
                   4735: 
                   4736:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   4737:   xp=vector(1,npar);
                   4738:   xm=vector(1,npar);
                   4739:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   4740:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   4741:   
                   4742:   pstamp(ficresstdeij);
                   4743:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   4744:   fprintf(ficresstdeij,"# Age");
                   4745:   for(i=1; i<=nlstate;i++){
                   4746:     for(j=1; j<=nlstate;j++)
                   4747:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   4748:     fprintf(ficresstdeij," e%1d. ",i);
                   4749:   }
                   4750:   fprintf(ficresstdeij,"\n");
                   4751: 
                   4752:   pstamp(ficrescveij);
                   4753:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   4754:   fprintf(ficrescveij,"# Age");
                   4755:   for(i=1; i<=nlstate;i++)
                   4756:     for(j=1; j<=nlstate;j++){
                   4757:       cptj= (j-1)*nlstate+i;
                   4758:       for(i2=1; i2<=nlstate;i2++)
                   4759:        for(j2=1; j2<=nlstate;j2++){
                   4760:          cptj2= (j2-1)*nlstate+i2;
                   4761:          if(cptj2 <= cptj)
                   4762:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   4763:        }
                   4764:     }
                   4765:   fprintf(ficrescveij,"\n");
                   4766:   
                   4767:   if(estepm < stepm){
                   4768:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4769:   }
                   4770:   else  hstepm=estepm;   
                   4771:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   4772:    * This is mainly to measure the difference between two models: for example
                   4773:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   4774:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   4775:    * progression in between and thus overestimating or underestimating according
                   4776:    * to the curvature of the survival function. If, for the same date, we 
                   4777:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   4778:    * to compare the new estimate of Life expectancy with the same linear 
                   4779:    * hypothesis. A more precise result, taking into account a more precise
                   4780:    * curvature will be obtained if estepm is as small as stepm. */
                   4781: 
                   4782:   /* For example we decided to compute the life expectancy with the smallest unit */
                   4783:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   4784:      nhstepm is the number of hstepm from age to agelim 
                   4785:      nstepm is the number of stepm from age to agelin. 
                   4786:      Look at hpijx to understand the reason of that which relies in memory size
                   4787:      and note for a fixed period like estepm months */
                   4788:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   4789:      survival function given by stepm (the optimization length). Unfortunately it
                   4790:      means that if the survival funtion is printed only each two years of age and if
                   4791:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   4792:      results. So we changed our mind and took the option of the best precision.
                   4793:   */
                   4794:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   4795: 
                   4796:   /* If stepm=6 months */
                   4797:   /* nhstepm age range expressed in number of stepm */
                   4798:   agelim=AGESUP;
                   4799:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   4800:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   4801:   /* if (stepm >= YEARM) hstepm=1;*/
                   4802:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   4803:   
                   4804:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4805:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4806:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   4807:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   4808:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   4809:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   4810: 
                   4811:   for (age=bage; age<=fage; age ++){ 
                   4812:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   4813:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   4814:     /* if (stepm >= YEARM) hstepm=1;*/
                   4815:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  4816:                
1.126     brouard  4817:     /* If stepm=6 months */
                   4818:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   4819:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   4820:     
                   4821:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  4822:                
1.126     brouard  4823:     /* Computing  Variances of health expectancies */
                   4824:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   4825:        decrease memory allocation */
                   4826:     for(theta=1; theta <=npar; theta++){
                   4827:       for(i=1; i<=npar; i++){ 
1.222     brouard  4828:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4829:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  4830:       }
                   4831:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
                   4832:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
1.218     brouard  4833:                        
1.126     brouard  4834:       for(j=1; j<= nlstate; j++){
1.222     brouard  4835:        for(i=1; i<=nlstate; i++){
                   4836:          for(h=0; h<=nhstepm-1; h++){
                   4837:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   4838:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   4839:          }
                   4840:        }
1.126     brouard  4841:       }
1.218     brouard  4842:                        
1.126     brouard  4843:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  4844:        for(h=0; h<=nhstepm-1; h++){
                   4845:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   4846:        }
1.126     brouard  4847:     }/* End theta */
                   4848:     
                   4849:     
                   4850:     for(h=0; h<=nhstepm-1; h++)
                   4851:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  4852:        for(theta=1; theta <=npar; theta++)
                   4853:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  4854:     
1.218     brouard  4855:                
1.222     brouard  4856:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  4857:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  4858:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  4859:                
1.222     brouard  4860:     printf("%d|",(int)age);fflush(stdout);
                   4861:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   4862:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  4863:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  4864:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   4865:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   4866:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   4867:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   4868:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  4869:       }
                   4870:     }
1.218     brouard  4871:                
1.126     brouard  4872:     /* Computing expectancies */
                   4873:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   4874:     for(i=1; i<=nlstate;i++)
                   4875:       for(j=1; j<=nlstate;j++)
1.222     brouard  4876:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   4877:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  4878:                                        
1.222     brouard  4879:          /* 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  4880:                                        
1.222     brouard  4881:        }
1.218     brouard  4882:                
1.126     brouard  4883:     fprintf(ficresstdeij,"%3.0f",age );
                   4884:     for(i=1; i<=nlstate;i++){
                   4885:       eip=0.;
                   4886:       vip=0.;
                   4887:       for(j=1; j<=nlstate;j++){
1.222     brouard  4888:        eip += eij[i][j][(int)age];
                   4889:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   4890:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   4891:        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  4892:       }
                   4893:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   4894:     }
                   4895:     fprintf(ficresstdeij,"\n");
1.218     brouard  4896:                
1.126     brouard  4897:     fprintf(ficrescveij,"%3.0f",age );
                   4898:     for(i=1; i<=nlstate;i++)
                   4899:       for(j=1; j<=nlstate;j++){
1.222     brouard  4900:        cptj= (j-1)*nlstate+i;
                   4901:        for(i2=1; i2<=nlstate;i2++)
                   4902:          for(j2=1; j2<=nlstate;j2++){
                   4903:            cptj2= (j2-1)*nlstate+i2;
                   4904:            if(cptj2 <= cptj)
                   4905:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   4906:          }
1.126     brouard  4907:       }
                   4908:     fprintf(ficrescveij,"\n");
1.218     brouard  4909:                
1.126     brouard  4910:   }
                   4911:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   4912:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   4913:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   4914:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   4915:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4916:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4917:   printf("\n");
                   4918:   fprintf(ficlog,"\n");
1.218     brouard  4919:        
1.126     brouard  4920:   free_vector(xm,1,npar);
                   4921:   free_vector(xp,1,npar);
                   4922:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   4923:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   4924:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   4925: }
1.218     brouard  4926:  
1.126     brouard  4927: /************ Variance ******************/
1.209     brouard  4928:  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  4929:  {
                   4930:    /* Variance of health expectancies */
                   4931:    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   4932:    /* double **newm;*/
                   4933:    /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
                   4934:   
                   4935:    /* int movingaverage(); */
                   4936:    double **dnewm,**doldm;
                   4937:    double **dnewmp,**doldmp;
                   4938:    int i, j, nhstepm, hstepm, h, nstepm ;
                   4939:    int k;
                   4940:    double *xp;
                   4941:    double **gp, **gm;  /* for var eij */
                   4942:    double ***gradg, ***trgradg; /*for var eij */
                   4943:    double **gradgp, **trgradgp; /* for var p point j */
                   4944:    double *gpp, *gmp; /* for var p point j */
                   4945:    double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   4946:    double ***p3mat;
                   4947:    double age,agelim, hf;
                   4948:    /* double ***mobaverage; */
                   4949:    int theta;
                   4950:    char digit[4];
                   4951:    char digitp[25];
                   4952: 
                   4953:    char fileresprobmorprev[FILENAMELENGTH];
                   4954: 
                   4955:    if(popbased==1){
                   4956:      if(mobilav!=0)
                   4957:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   4958:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   4959:    }
                   4960:    else 
                   4961:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  4962: 
1.218     brouard  4963:    /* if (mobilav!=0) { */
                   4964:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   4965:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   4966:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   4967:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   4968:    /*   } */
                   4969:    /* } */
                   4970: 
                   4971:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   4972:    sprintf(digit,"%-d",ij);
                   4973:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   4974:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   4975:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   4976:    strcat(fileresprobmorprev,fileresu);
                   4977:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   4978:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   4979:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   4980:    }
                   4981:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   4982:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   4983:    pstamp(ficresprobmorprev);
                   4984:    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);
                   4985:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   4986:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   4987:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   4988:      for(i=1; i<=nlstate;i++)
                   4989:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   4990:    }  
                   4991:    fprintf(ficresprobmorprev,"\n");
                   4992:   
                   4993:    fprintf(ficgp,"\n# Routine varevsij");
                   4994:    fprintf(ficgp,"\nunset title \n");
                   4995:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   4996:    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");
                   4997:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   4998:    /*   } */
                   4999:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5000:    pstamp(ficresvij);
                   5001:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   5002:    if(popbased==1)
                   5003:      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);
                   5004:    else
                   5005:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   5006:    fprintf(ficresvij,"# Age");
                   5007:    for(i=1; i<=nlstate;i++)
                   5008:      for(j=1; j<=nlstate;j++)
                   5009:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   5010:    fprintf(ficresvij,"\n");
                   5011: 
                   5012:    xp=vector(1,npar);
                   5013:    dnewm=matrix(1,nlstate,1,npar);
                   5014:    doldm=matrix(1,nlstate,1,nlstate);
                   5015:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   5016:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5017: 
                   5018:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   5019:    gpp=vector(nlstate+1,nlstate+ndeath);
                   5020:    gmp=vector(nlstate+1,nlstate+ndeath);
                   5021:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  5022:   
1.218     brouard  5023:    if(estepm < stepm){
                   5024:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   5025:    }
                   5026:    else  hstepm=estepm;   
                   5027:    /* For example we decided to compute the life expectancy with the smallest unit */
                   5028:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5029:       nhstepm is the number of hstepm from age to agelim 
                   5030:       nstepm is the number of stepm from age to agelim. 
                   5031:       Look at function hpijx to understand why because of memory size limitations, 
                   5032:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   5033:       survival function given by stepm (the optimization length). Unfortunately it
                   5034:       means that if the survival funtion is printed every two years of age and if
                   5035:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5036:       results. So we changed our mind and took the option of the best precision.
                   5037:    */
                   5038:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5039:    agelim = AGESUP;
                   5040:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   5041:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   5042:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5043:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5044:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   5045:      gp=matrix(0,nhstepm,1,nlstate);
                   5046:      gm=matrix(0,nhstepm,1,nlstate);
                   5047:                
                   5048:                
                   5049:      for(theta=1; theta <=npar; theta++){
                   5050:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   5051:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5052:        }
                   5053:                        
                   5054:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
                   5055:                        
                   5056:        if (popbased==1) {
                   5057:         if(mobilav ==0){
                   5058:           for(i=1; i<=nlstate;i++)
                   5059:             prlim[i][i]=probs[(int)age][i][ij];
                   5060:         }else{ /* mobilav */ 
                   5061:           for(i=1; i<=nlstate;i++)
                   5062:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   5063:         }
                   5064:        }
                   5065:                        
                   5066:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  /* Returns p3mat[i][j][h] for h=1 to nhstepm */
                   5067:        for(j=1; j<= nlstate; j++){
                   5068:         for(h=0; h<=nhstepm; h++){
                   5069:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   5070:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   5071:         }
                   5072:        }
                   5073:        /* Next for computing probability of death (h=1 means
                   5074:          computed over hstepm matrices product = hstepm*stepm months) 
                   5075:          as a weighted average of prlim.
                   5076:        */
                   5077:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   5078:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   5079:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   5080:        }    
                   5081:        /* end probability of death */
                   5082:                        
                   5083:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   5084:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   5085:                        
                   5086:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij);
                   5087:                        
                   5088:        if (popbased==1) {
                   5089:         if(mobilav ==0){
                   5090:           for(i=1; i<=nlstate;i++)
                   5091:             prlim[i][i]=probs[(int)age][i][ij];
                   5092:         }else{ /* mobilav */ 
                   5093:           for(i=1; i<=nlstate;i++)
                   5094:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   5095:         }
                   5096:        }
                   5097:                        
                   5098:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   5099:                        
                   5100:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   5101:         for(h=0; h<=nhstepm; h++){
                   5102:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   5103:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   5104:         }
                   5105:        }
                   5106:        /* This for computing probability of death (h=1 means
                   5107:          computed over hstepm matrices product = hstepm*stepm months) 
                   5108:          as a weighted average of prlim.
                   5109:        */
                   5110:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   5111:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   5112:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   5113:        }    
                   5114:        /* end probability of death */
                   5115:                        
                   5116:        for(j=1; j<= nlstate; j++) /* vareij */
                   5117:         for(h=0; h<=nhstepm; h++){
                   5118:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   5119:         }
                   5120:                        
                   5121:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   5122:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   5123:        }
                   5124:                        
                   5125:      } /* End theta */
                   5126:                
                   5127:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   5128:                
                   5129:      for(h=0; h<=nhstepm; h++) /* veij */
                   5130:        for(j=1; j<=nlstate;j++)
                   5131:         for(theta=1; theta <=npar; theta++)
                   5132:           trgradg[h][j][theta]=gradg[h][theta][j];
                   5133:                
                   5134:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   5135:        for(theta=1; theta <=npar; theta++)
                   5136:         trgradgp[j][theta]=gradgp[theta][j];
                   5137:                
                   5138:                
                   5139:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   5140:      for(i=1;i<=nlstate;i++)
                   5141:        for(j=1;j<=nlstate;j++)
                   5142:         vareij[i][j][(int)age] =0.;
                   5143:                
                   5144:      for(h=0;h<=nhstepm;h++){
                   5145:        for(k=0;k<=nhstepm;k++){
                   5146:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   5147:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   5148:         for(i=1;i<=nlstate;i++)
                   5149:           for(j=1;j<=nlstate;j++)
                   5150:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   5151:        }
                   5152:      }
                   5153:                
                   5154:      /* pptj */
                   5155:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   5156:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   5157:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   5158:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   5159:         varppt[j][i]=doldmp[j][i];
                   5160:      /* end ppptj */
                   5161:      /*  x centered again */
                   5162:                
                   5163:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij);
                   5164:                
                   5165:      if (popbased==1) {
                   5166:        if(mobilav ==0){
                   5167:         for(i=1; i<=nlstate;i++)
                   5168:           prlim[i][i]=probs[(int)age][i][ij];
                   5169:        }else{ /* mobilav */ 
                   5170:         for(i=1; i<=nlstate;i++)
                   5171:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   5172:        }
                   5173:      }
                   5174:                
                   5175:      /* This for computing probability of death (h=1 means
                   5176:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   5177:        as a weighted average of prlim.
                   5178:      */
                   5179:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
                   5180:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   5181:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   5182:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   5183:      }    
                   5184:      /* end probability of death */
                   5185:                
                   5186:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   5187:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   5188:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   5189:        for(i=1; i<=nlstate;i++){
                   5190:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   5191:        }
                   5192:      } 
                   5193:      fprintf(ficresprobmorprev,"\n");
                   5194:                
                   5195:      fprintf(ficresvij,"%.0f ",age );
                   5196:      for(i=1; i<=nlstate;i++)
                   5197:        for(j=1; j<=nlstate;j++){
                   5198:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   5199:        }
                   5200:      fprintf(ficresvij,"\n");
                   5201:      free_matrix(gp,0,nhstepm,1,nlstate);
                   5202:      free_matrix(gm,0,nhstepm,1,nlstate);
                   5203:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   5204:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   5205:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5206:    } /* End age */
                   5207:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   5208:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   5209:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   5210:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   5211:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   5212:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   5213:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   5214:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   5215:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   5216:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   5217:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   5218:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   5219:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   5220:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   5221:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   5222:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   5223:    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);
                   5224:    /*  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  5225:     */
1.218     brouard  5226:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   5227:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  5228: 
1.218     brouard  5229:    free_vector(xp,1,npar);
                   5230:    free_matrix(doldm,1,nlstate,1,nlstate);
                   5231:    free_matrix(dnewm,1,nlstate,1,npar);
                   5232:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5233:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   5234:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5235:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   5236:    fclose(ficresprobmorprev);
                   5237:    fflush(ficgp);
                   5238:    fflush(fichtm); 
                   5239:  }  /* end varevsij */
1.126     brouard  5240: 
                   5241: /************ Variance of prevlim ******************/
1.209     brouard  5242:  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  5243: {
1.205     brouard  5244:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  5245:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  5246: 
1.126     brouard  5247:   double **dnewm,**doldm;
                   5248:   int i, j, nhstepm, hstepm;
                   5249:   double *xp;
                   5250:   double *gp, *gm;
                   5251:   double **gradg, **trgradg;
1.208     brouard  5252:   double **mgm, **mgp;
1.126     brouard  5253:   double age,agelim;
                   5254:   int theta;
                   5255:   
                   5256:   pstamp(ficresvpl);
                   5257:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
                   5258:   fprintf(ficresvpl,"# Age");
                   5259:   for(i=1; i<=nlstate;i++)
                   5260:       fprintf(ficresvpl," %1d-%1d",i,i);
                   5261:   fprintf(ficresvpl,"\n");
                   5262: 
                   5263:   xp=vector(1,npar);
                   5264:   dnewm=matrix(1,nlstate,1,npar);
                   5265:   doldm=matrix(1,nlstate,1,nlstate);
                   5266:   
                   5267:   hstepm=1*YEARM; /* Every year of age */
                   5268:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   5269:   agelim = AGESUP;
                   5270:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   5271:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   5272:     if (stepm >= YEARM) hstepm=1;
                   5273:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   5274:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  5275:     mgp=matrix(1,npar,1,nlstate);
                   5276:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  5277:     gp=vector(1,nlstate);
                   5278:     gm=vector(1,nlstate);
                   5279: 
                   5280:     for(theta=1; theta <=npar; theta++){
                   5281:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   5282:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5283:       }
1.209     brouard  5284:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
                   5285:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
                   5286:       else
                   5287:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
1.208     brouard  5288:       for(i=1;i<=nlstate;i++){
1.126     brouard  5289:        gp[i] = prlim[i][i];
1.208     brouard  5290:        mgp[theta][i] = prlim[i][i];
                   5291:       }
1.126     brouard  5292:       for(i=1; i<=npar; i++) /* Computes gradient */
                   5293:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.209     brouard  5294:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
                   5295:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
                   5296:       else
                   5297:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
1.208     brouard  5298:       for(i=1;i<=nlstate;i++){
1.126     brouard  5299:        gm[i] = prlim[i][i];
1.208     brouard  5300:        mgm[theta][i] = prlim[i][i];
                   5301:       }
1.126     brouard  5302:       for(i=1;i<=nlstate;i++)
                   5303:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  5304:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  5305:     } /* End theta */
                   5306: 
                   5307:     trgradg =matrix(1,nlstate,1,npar);
                   5308: 
                   5309:     for(j=1; j<=nlstate;j++)
                   5310:       for(theta=1; theta <=npar; theta++)
                   5311:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  5312:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   5313:     /*   printf("\nmgm mgp %d ",(int)age); */
                   5314:     /*   for(j=1; j<=nlstate;j++){ */
                   5315:     /*         printf(" %d ",j); */
                   5316:     /*         for(theta=1; theta <=npar; theta++) */
                   5317:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   5318:     /*         printf("\n "); */
                   5319:     /*   } */
                   5320:     /* } */
                   5321:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   5322:     /*   printf("\n gradg %d ",(int)age); */
                   5323:     /*   for(j=1; j<=nlstate;j++){ */
                   5324:     /*         printf("%d ",j); */
                   5325:     /*         for(theta=1; theta <=npar; theta++) */
                   5326:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   5327:     /*         printf("\n "); */
                   5328:     /*   } */
                   5329:     /* } */
1.126     brouard  5330: 
                   5331:     for(i=1;i<=nlstate;i++)
                   5332:       varpl[i][(int)age] =0.;
1.209     brouard  5333:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.205     brouard  5334:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   5335:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   5336:     }else{
1.126     brouard  5337:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   5338:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  5339:     }
1.126     brouard  5340:     for(i=1;i<=nlstate;i++)
                   5341:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   5342: 
                   5343:     fprintf(ficresvpl,"%.0f ",age );
                   5344:     for(i=1; i<=nlstate;i++)
                   5345:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   5346:     fprintf(ficresvpl,"\n");
                   5347:     free_vector(gp,1,nlstate);
                   5348:     free_vector(gm,1,nlstate);
1.208     brouard  5349:     free_matrix(mgm,1,npar,1,nlstate);
                   5350:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  5351:     free_matrix(gradg,1,npar,1,nlstate);
                   5352:     free_matrix(trgradg,1,nlstate,1,npar);
                   5353:   } /* End age */
                   5354: 
                   5355:   free_vector(xp,1,npar);
                   5356:   free_matrix(doldm,1,nlstate,1,npar);
                   5357:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   5358: 
                   5359: }
                   5360: 
                   5361: /************ Variance of one-step probabilities  ******************/
                   5362: 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  5363:  {
                   5364:    int i, j=0,  k1, l1, tj;
                   5365:    int k2, l2, j1,  z1;
                   5366:    int k=0, l;
                   5367:    int first=1, first1, first2;
                   5368:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   5369:    double **dnewm,**doldm;
                   5370:    double *xp;
                   5371:    double *gp, *gm;
                   5372:    double **gradg, **trgradg;
                   5373:    double **mu;
                   5374:    double age, cov[NCOVMAX+1];
                   5375:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   5376:    int theta;
                   5377:    char fileresprob[FILENAMELENGTH];
                   5378:    char fileresprobcov[FILENAMELENGTH];
                   5379:    char fileresprobcor[FILENAMELENGTH];
                   5380:    double ***varpij;
                   5381: 
                   5382:    strcpy(fileresprob,"PROB_"); 
                   5383:    strcat(fileresprob,fileres);
                   5384:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   5385:      printf("Problem with resultfile: %s\n", fileresprob);
                   5386:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   5387:    }
                   5388:    strcpy(fileresprobcov,"PROBCOV_"); 
                   5389:    strcat(fileresprobcov,fileresu);
                   5390:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   5391:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   5392:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   5393:    }
                   5394:    strcpy(fileresprobcor,"PROBCOR_"); 
                   5395:    strcat(fileresprobcor,fileresu);
                   5396:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   5397:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   5398:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   5399:    }
                   5400:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   5401:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   5402:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   5403:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   5404:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   5405:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   5406:    pstamp(ficresprob);
                   5407:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   5408:    fprintf(ficresprob,"# Age");
                   5409:    pstamp(ficresprobcov);
                   5410:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   5411:    fprintf(ficresprobcov,"# Age");
                   5412:    pstamp(ficresprobcor);
                   5413:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   5414:    fprintf(ficresprobcor,"# Age");
1.126     brouard  5415: 
                   5416: 
1.222     brouard  5417:    for(i=1; i<=nlstate;i++)
                   5418:      for(j=1; j<=(nlstate+ndeath);j++){
                   5419:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   5420:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   5421:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   5422:      }  
                   5423:    /* fprintf(ficresprob,"\n");
                   5424:       fprintf(ficresprobcov,"\n");
                   5425:       fprintf(ficresprobcor,"\n");
                   5426:    */
                   5427:    xp=vector(1,npar);
                   5428:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   5429:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   5430:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   5431:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   5432:    first=1;
                   5433:    fprintf(ficgp,"\n# Routine varprob");
                   5434:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   5435:    fprintf(fichtm,"\n");
                   5436: 
                   5437:    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);
                   5438:    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);
                   5439:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  5440: and drawn. It helps understanding how is the covariance between two incidences.\
                   5441:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  5442:    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  5443: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   5444: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   5445: standard deviations wide on each axis. <br>\
                   5446:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   5447:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   5448: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   5449: 
1.222     brouard  5450:    cov[1]=1;
                   5451:    /* tj=cptcoveff; */
1.224   ! brouard  5452:    tj = (int) pow(2,nqveff);
1.222     brouard  5453:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   5454:    j1=0;
1.224   ! brouard  5455:    for(j1=1; j1<=tj;j1++){  /* For each valid combination of covariates or only once*/
1.222     brouard  5456:      if  (cptcovn>0) {
                   5457:        fprintf(ficresprob, "\n#********** Variable "); 
1.224   ! brouard  5458:        for (z1=1; z1<=nqveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5459:        fprintf(ficresprob, "**********\n#\n");
                   5460:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.224   ! brouard  5461:        for (z1=1; z1<=nqveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5462:        fprintf(ficresprobcov, "**********\n#\n");
1.220     brouard  5463:                        
1.222     brouard  5464:        fprintf(ficgp, "\n#********** Variable "); 
1.224   ! brouard  5465:        for (z1=1; z1<=nqveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5466:        fprintf(ficgp, "**********\n#\n");
1.220     brouard  5467:                        
                   5468:                        
1.222     brouard  5469:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.224   ! brouard  5470:        for (z1=1; z1<=nqveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5471:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  5472:                        
1.222     brouard  5473:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.224   ! brouard  5474:        for (z1=1; z1<=nqveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  5475:        fprintf(ficresprobcor, "**********\n#");    
                   5476:        if(invalidvarcomb[j1]){
                   5477:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   5478:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   5479:         continue;
                   5480:        }
                   5481:      }
                   5482:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   5483:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   5484:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   5485:      gm=vector(1,(nlstate)*(nlstate+ndeath));
                   5486:      for (age=bage; age<=fage; age ++){ 
                   5487:        cov[2]=age;
                   5488:        if(nagesqr==1)
                   5489:         cov[3]= age*age;
                   5490:        for (k=1; k<=cptcovn;k++) {
                   5491:         cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
                   5492:         /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
                   5493:                                                                    * 1  1 1 1 1
                   5494:                                                                    * 2  2 1 1 1
                   5495:                                                                    * 3  1 2 1 1
                   5496:                                                                    */
                   5497:         /* nbcode[1][1]=0 nbcode[1][2]=1;*/
                   5498:        }
                   5499:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   5500:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   5501:        for (k=1; k<=cptcovprod;k++)
                   5502:         cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.220     brouard  5503:                        
                   5504:                        
1.222     brouard  5505:        for(theta=1; theta <=npar; theta++){
                   5506:         for(i=1; i<=npar; i++)
                   5507:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  5508:                                
1.222     brouard  5509:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  5510:                                
1.222     brouard  5511:         k=0;
                   5512:         for(i=1; i<= (nlstate); i++){
                   5513:           for(j=1; j<=(nlstate+ndeath);j++){
                   5514:             k=k+1;
                   5515:             gp[k]=pmmij[i][j];
                   5516:           }
                   5517:         }
1.220     brouard  5518:                                
1.222     brouard  5519:         for(i=1; i<=npar; i++)
                   5520:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  5521:                                
1.222     brouard  5522:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   5523:         k=0;
                   5524:         for(i=1; i<=(nlstate); i++){
                   5525:           for(j=1; j<=(nlstate+ndeath);j++){
                   5526:             k=k+1;
                   5527:             gm[k]=pmmij[i][j];
                   5528:           }
                   5529:         }
1.220     brouard  5530:                                
1.222     brouard  5531:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   5532:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   5533:        }
1.126     brouard  5534: 
1.222     brouard  5535:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   5536:         for(theta=1; theta <=npar; theta++)
                   5537:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  5538:                        
1.222     brouard  5539:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   5540:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  5541:                        
1.222     brouard  5542:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  5543:                        
1.222     brouard  5544:        k=0;
                   5545:        for(i=1; i<=(nlstate); i++){
                   5546:         for(j=1; j<=(nlstate+ndeath);j++){
                   5547:           k=k+1;
                   5548:           mu[k][(int) age]=pmmij[i][j];
                   5549:         }
                   5550:        }
                   5551:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   5552:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   5553:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  5554:                        
1.222     brouard  5555:        /*printf("\n%d ",(int)age);
                   5556:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   5557:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   5558:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   5559:         }*/
1.220     brouard  5560:                        
1.222     brouard  5561:        fprintf(ficresprob,"\n%d ",(int)age);
                   5562:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   5563:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  5564:                        
1.222     brouard  5565:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   5566:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   5567:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   5568:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   5569:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   5570:        }
                   5571:        i=0;
                   5572:        for (k=1; k<=(nlstate);k++){
                   5573:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   5574:           i++;
                   5575:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   5576:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   5577:           for (j=1; j<=i;j++){
                   5578:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   5579:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   5580:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   5581:           }
                   5582:         }
                   5583:        }/* end of loop for state */
                   5584:      } /* end of loop for age */
                   5585:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   5586:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   5587:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   5588:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   5589:     
                   5590:      /* Confidence intervalle of pij  */
                   5591:      /*
                   5592:        fprintf(ficgp,"\nunset parametric;unset label");
                   5593:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   5594:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   5595:        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);
                   5596:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   5597:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   5598:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   5599:      */
                   5600:                
                   5601:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   5602:      first1=1;first2=2;
                   5603:      for (k2=1; k2<=(nlstate);k2++){
                   5604:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   5605:         if(l2==k2) continue;
                   5606:         j=(k2-1)*(nlstate+ndeath)+l2;
                   5607:         for (k1=1; k1<=(nlstate);k1++){
                   5608:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   5609:             if(l1==k1) continue;
                   5610:             i=(k1-1)*(nlstate+ndeath)+l1;
                   5611:             if(i<=j) continue;
                   5612:             for (age=bage; age<=fage; age ++){ 
                   5613:               if ((int)age %5==0){
                   5614:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   5615:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   5616:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   5617:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   5618:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   5619:                 c12=cv12/sqrt(v1*v2);
                   5620:                 /* Computing eigen value of matrix of covariance */
                   5621:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5622:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5623:                 if ((lc2 <0) || (lc1 <0) ){
                   5624:                   if(first2==1){
                   5625:                     first1=0;
                   5626:                     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);
                   5627:                   }
                   5628:                   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);
                   5629:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   5630:                   /* lc2=fabs(lc2); */
                   5631:                 }
1.220     brouard  5632:                                                                
1.222     brouard  5633:                 /* Eigen vectors */
                   5634:                 v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   5635:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   5636:                 v21=(lc1-v1)/cv12*v11;
                   5637:                 v12=-v21;
                   5638:                 v22=v11;
                   5639:                 tnalp=v21/v11;
                   5640:                 if(first1==1){
                   5641:                   first1=0;
                   5642:                   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);
                   5643:                 }
                   5644:                 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);
                   5645:                 /*printf(fignu*/
                   5646:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   5647:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   5648:                 if(first==1){
                   5649:                   first=0;
                   5650:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   5651:                   fprintf(ficgp,"\nset parametric;unset label");
                   5652:                   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);
                   5653:                   fprintf(ficgp,"\nset ter svg size 640, 480");
                   5654:                   fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  5655:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  5656: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  5657:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   5658:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   5659:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   5660:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   5661:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   5662:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   5663:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   5664:                   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",      \
                   5665:                           mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),                                                                         \
                   5666:                           mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   5667:                 }else{
                   5668:                   first=0;
                   5669:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   5670:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   5671:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   5672:                   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", \
                   5673:                           mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),                                 \
                   5674:                           mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   5675:                 }/* if first */
                   5676:               } /* age mod 5 */
                   5677:             } /* end loop age */
                   5678:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   5679:             first=1;
                   5680:           } /*l12 */
                   5681:         } /* k12 */
                   5682:        } /*l1 */
                   5683:      }/* k1 */
                   5684:    }  /* loop on combination of covariates j1 */
                   5685:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   5686:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   5687:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   5688:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   5689:    free_vector(xp,1,npar);
                   5690:    fclose(ficresprob);
                   5691:    fclose(ficresprobcov);
                   5692:    fclose(ficresprobcor);
                   5693:    fflush(ficgp);
                   5694:    fflush(fichtmcov);
                   5695:  }
1.126     brouard  5696: 
                   5697: 
                   5698: /******************* Printing html file ***********/
1.201     brouard  5699: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  5700:                  int lastpass, int stepm, int weightopt, char model[],\
                   5701:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.217     brouard  5702:                  int popforecast, int prevfcast, int backcast, int estepm , \
1.213     brouard  5703:                  double jprev1, double mprev1,double anprev1, double dateprev1, \
                   5704:                  double jprev2, double mprev2,double anprev2, double dateprev2){
1.126     brouard  5705:   int jj1, k1, i1, cpt;
                   5706: 
                   5707:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   5708:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   5709: </ul>");
1.214     brouard  5710:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   5711:    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",
                   5712:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
                   5713:    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  5714:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   5715:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  5716:    fprintf(fichtm,"\
                   5717:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  5718:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  5719:    fprintf(fichtm,"\
1.217     brouard  5720:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   5721:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   5722:    fprintf(fichtm,"\
1.126     brouard  5723:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  5724:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  5725:    fprintf(fichtm,"\
1.217     brouard  5726:  - Period (stable) back prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
                   5727:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   5728:    fprintf(fichtm,"\
1.211     brouard  5729:  - (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  5730:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  5731:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  5732:    if(prevfcast==1){
                   5733:      fprintf(fichtm,"\
                   5734:  - Prevalence projections by age and states:                           \
1.201     brouard  5735:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  5736:    }
1.126     brouard  5737: 
1.222     brouard  5738:    fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
1.126     brouard  5739: 
1.224   ! brouard  5740:    m=pow(2,nqveff);
1.222     brouard  5741:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  5742: 
1.222     brouard  5743:    jj1=0;
                   5744:    for(k1=1; k1<=m;k1++){
1.220     brouard  5745: 
1.222     brouard  5746:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   5747:      jj1++;
                   5748:      if (cptcovn > 0) {
                   5749:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.224   ! brouard  5750:        for (cpt=1; cpt<=nqveff;cpt++){ 
1.222     brouard  5751:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
                   5752:         printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout);
                   5753:        }
                   5754:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   5755:        if(invalidvarcomb[k1]){
                   5756:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   5757:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   5758:         continue;
                   5759:        }
                   5760:      }
                   5761:      /* aij, bij */
                   5762:      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  5763: <img src=\"%s_%d-1.svg\">",model,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
1.222     brouard  5764:      /* Pij */
                   5765:      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  5766: <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);     
1.222     brouard  5767:      /* Quasi-incidences */
                   5768:      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  5769:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  5770:  incidence (rates) are the limit when h tends to zero of the ratio of the probability  <sub>h</sub>P<sub>ij</sub> \
                   5771: 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  5772: <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1); 
1.222     brouard  5773:      /* Survival functions (period) in state j */
                   5774:      for(cpt=1; cpt<=nlstate;cpt++){
                   5775:        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  5776: <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  5777:      }
                   5778:      /* State specific survival functions (period) */
                   5779:      for(cpt=1; cpt<=nlstate;cpt++){
                   5780:        fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
1.220     brouard  5781:  Or probability to survive in various states (1 to %d) being in state %d at different ages.    \
1.201     brouard  5782:  <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  5783:      }
                   5784:      /* Period (stable) prevalence in each health state */
                   5785:      for(cpt=1; cpt<=nlstate;cpt++){
                   5786:        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  5787: <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  5788:      }
                   5789:      if(backcast==1){
                   5790:        /* Period (stable) back prevalence in each health state */
                   5791:        for(cpt=1; cpt<=nlstate;cpt++){
                   5792:         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  5793: <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  5794:        }
1.217     brouard  5795:      }
1.222     brouard  5796:      if(prevfcast==1){
                   5797:        /* Projection of prevalence up to period (stable) prevalence in each health state */
                   5798:        for(cpt=1; cpt<=nlstate;cpt++){
                   5799:         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  5800: <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  5801:        }
                   5802:      }
1.220     brouard  5803:         
1.222     brouard  5804:      for(cpt=1; cpt<=nlstate;cpt++) {
                   5805:        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  5806: <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  5807:      }
                   5808:      /* } /\* end i1 *\/ */
                   5809:    }/* End k1 */
                   5810:    fprintf(fichtm,"</ul>");
1.126     brouard  5811: 
1.222     brouard  5812:    fprintf(fichtm,"\
1.126     brouard  5813: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  5814:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  5815:  - 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  5816: But because parameters are usually highly correlated (a higher incidence of disability \
                   5817: and a higher incidence of recovery can give very close observed transition) it might \
                   5818: be very useful to look not only at linear confidence intervals estimated from the \
                   5819: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   5820: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   5821: covariance matrix of the one-step probabilities. \
                   5822: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  5823: 
1.222     brouard  5824:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   5825:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   5826:    fprintf(fichtm,"\
1.126     brouard  5827:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  5828:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  5829: 
1.222     brouard  5830:    fprintf(fichtm,"\
1.126     brouard  5831:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  5832:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   5833:    fprintf(fichtm,"\
1.126     brouard  5834:  - 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): \
                   5835:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  5836:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  5837:    fprintf(fichtm,"\
1.126     brouard  5838:  - (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): \
                   5839:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  5840:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  5841:    fprintf(fichtm,"\
1.128     brouard  5842:  - 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  5843:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   5844:    fprintf(fichtm,"\
1.128     brouard  5845:  - 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  5846:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   5847:    fprintf(fichtm,"\
1.126     brouard  5848:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  5849:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  5850: 
                   5851: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   5852: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   5853: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   5854: /*     <br>",fileres,fileres,fileres,fileres); */
                   5855: /*  else  */
                   5856: /*    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  5857:    fflush(fichtm);
                   5858:    fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
1.126     brouard  5859: 
1.224   ! brouard  5860:    m=pow(2,nqveff);
1.222     brouard  5861:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  5862: 
1.222     brouard  5863:    jj1=0;
                   5864:    for(k1=1; k1<=m;k1++){
                   5865:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   5866:      jj1++;
1.126     brouard  5867:      if (cptcovn > 0) {
                   5868:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.224   ! brouard  5869:        for (cpt=1; cpt<=nqveff;cpt++) 
1.222     brouard  5870:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
1.126     brouard  5871:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  5872: 
1.222     brouard  5873:        if(invalidvarcomb[k1]){
                   5874:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   5875:         continue;
                   5876:        }
1.126     brouard  5877:      }
                   5878:      for(cpt=1; cpt<=nlstate;cpt++) {
1.218     brouard  5879:        fprintf(fichtm,"\n<br>- Observed (cross-sectional) and period (incidence based) \
                   5880: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d-%d.svg\"> %s_%d-%d.svg</a>\n <br>\
1.205     brouard  5881: <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  5882:      }
                   5883:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  5884: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   5885: true period expectancies (those weighted with period prevalences are also\
                   5886:  drawn in addition to the population based expectancies computed using\
1.218     brouard  5887:  observed and cahotic prevalences:  <a href=\"%s_%d.svg\">%s_%d.svg</a>\n<br>\
1.205     brouard  5888: <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);
1.222     brouard  5889:      /* } /\* end i1 *\/ */
                   5890:    }/* End k1 */
                   5891:    fprintf(fichtm,"</ul>");
                   5892:    fflush(fichtm);
1.126     brouard  5893: }
                   5894: 
                   5895: /******************* Gnuplot file **************/
1.223     brouard  5896: void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , int prevfcast, int backcast, char pathc[], double p[]){
1.126     brouard  5897: 
                   5898:   char dirfileres[132],optfileres[132];
1.223     brouard  5899:   char gplotcondition[132];
1.164     brouard  5900:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.211     brouard  5901:   int lv=0, vlv=0, kl=0;
1.130     brouard  5902:   int ng=0;
1.201     brouard  5903:   int vpopbased;
1.223     brouard  5904:   int ioffset; /* variable offset for columns */
1.219     brouard  5905: 
1.126     brouard  5906: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   5907: /*     printf("Problem with file %s",optionfilegnuplot); */
                   5908: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   5909: /*   } */
                   5910: 
                   5911:   /*#ifdef windows */
                   5912:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  5913:   /*#endif */
1.224   ! brouard  5914:   m=pow(2,nqveff);
1.126     brouard  5915: 
1.202     brouard  5916:   /* Contribution to likelihood */
                   5917:   /* Plot the probability implied in the likelihood */
1.223     brouard  5918:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   5919:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   5920:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   5921:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  5922: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  5923:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   5924: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  5925:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   5926:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   5927:   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));
                   5928:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   5929:   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));
                   5930:   for (i=1; i<= nlstate ; i ++) {
                   5931:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   5932:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   5933:     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);
                   5934:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   5935:       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);
                   5936:     }
                   5937:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   5938:   }
                   5939:   /* 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 */               
                   5940:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   5941:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   5942:   fprintf(ficgp,"\nset out;unset log\n");
                   5943:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  5944: 
1.126     brouard  5945:   strcpy(dirfileres,optionfilefiname);
                   5946:   strcpy(optfileres,"vpl");
1.223     brouard  5947:   /* 1eme*/
1.211     brouard  5948:   for (cpt=1; cpt<= nlstate ; cpt ++) { /* For each live state */
1.220     brouard  5949:     for (k1=1; k1<= m ; k1 ++) { /* For each valid combination of covariate */
1.211     brouard  5950:       /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
                   5951:       fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files ");
1.224   ! brouard  5952:       for (k=1; k<=nqveff; k++){    /* For each covariate k get corresponding value lv for combination k1 */
        !          5953:        lv= decodtabm(k1,k,nqveff); /* Should be the value of the covariate corresponding to k1 combination */
1.223     brouard  5954:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5955:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5956:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5957:        vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
                   5958:        /* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
                   5959:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  5960:       }
                   5961:       fprintf(ficgp,"\n#\n");
1.223     brouard  5962:       if(invalidvarcomb[k1]){
                   5963:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   5964:        continue;
                   5965:       }
1.211     brouard  5966: 
1.223     brouard  5967:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);
                   5968:       fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);
                   5969:       fprintf(ficgp,"set xlabel \"Age\" \n\
1.219     brouard  5970: set ylabel \"Probability\" \n  \
                   5971: set ter svg size 640, 480\n    \
1.201     brouard  5972: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);
1.219     brouard  5973:                        
1.223     brouard  5974:       for (i=1; i<= nlstate ; i ++) {
                   5975:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   5976:        else        fprintf(ficgp," %%*lf (%%*lf)");
                   5977:       }
                   5978:       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);
                   5979:       for (i=1; i<= nlstate ; i ++) {
                   5980:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   5981:        else fprintf(ficgp," %%*lf (%%*lf)");
                   5982:       } 
                   5983:       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); 
                   5984:       for (i=1; i<= nlstate ; i ++) {
                   5985:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   5986:        else fprintf(ficgp," %%*lf (%%*lf)");
                   5987:       }  
                   5988:       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));
                   5989:       if(backcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
                   5990:        /* 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); */
                   5991:        fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1 */
1.224   ! brouard  5992:        if(nqveff ==0){
1.223     brouard  5993:          fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line ",  2+(cpt-1),  cpt );
                   5994:        }else{
                   5995:          kl=0;
1.224   ! brouard  5996:          for (k=1; k<=nqveff; k++){    /* For each combination of covariate  */
        !          5997:            lv= decodtabm(k1,k,nqveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
1.223     brouard  5998:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5999:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6000:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6001:            vlv= nbcode[Tvaraff[k]][lv];
                   6002:            kl++;
                   6003:            /* 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 *\/ */
                   6004:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   6005:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   6006:            /* ''  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.224   ! brouard  6007:            if(k==nqveff){
1.223     brouard  6008:              fprintf(ficgp,"$%d==%d && $%d==%d)? $%d : 1/0) t 'Backward prevalence in state %d' with line ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv], \
                   6009:                      6+(cpt-1),  cpt );
                   6010:            }else{
                   6011:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   6012:              kl++;
                   6013:            }
                   6014:          } /* end covariate */
                   6015:        } /* end if no covariate */
                   6016:       } /* end if backcast */
                   6017:       fprintf(ficgp,"\nset out \n");
1.201     brouard  6018:     } /* k1 */
                   6019:   } /* cpt */
1.126     brouard  6020:   /*2 eme*/
                   6021:   for (k1=1; k1<= m ; k1 ++) { 
1.220     brouard  6022: 
1.223     brouard  6023:     fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.224   ! brouard  6024:     for (k=1; k<=nqveff; k++){    /* For each covariate and each value */
        !          6025:       lv= decodtabm(k1,k,nqveff); /* Should be the covariate number corresponding to k1 combination */
1.223     brouard  6026:       /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6027:       /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6028:       /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6029:       vlv= nbcode[Tvaraff[k]][lv];
                   6030:       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6031:     }
                   6032:     fprintf(ficgp,"\n#\n");
                   6033:     if(invalidvarcomb[k1]){
                   6034:       fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6035:       continue;
                   6036:     }
1.219     brouard  6037:                        
1.223     brouard  6038:     fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);
                   6039:     for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
                   6040:       if(vpopbased==0)
                   6041:        fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
                   6042:       else
                   6043:        fprintf(ficgp,"\nreplot ");
                   6044:       for (i=1; i<= nlstate+1 ; i ++) {
                   6045:        k=2*i;
                   6046:        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);
                   6047:        for (j=1; j<= nlstate+1 ; j ++) {
                   6048:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   6049:          else fprintf(ficgp," %%*lf (%%*lf)");
                   6050:        }   
                   6051:        if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   6052:        else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
                   6053:        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);
                   6054:        for (j=1; j<= nlstate+1 ; j ++) {
                   6055:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   6056:          else fprintf(ficgp," %%*lf (%%*lf)");
                   6057:        }   
                   6058:        fprintf(ficgp,"\" t\"\" w l lt 0,");
                   6059:        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);
                   6060:        for (j=1; j<= nlstate+1 ; j ++) {
                   6061:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   6062:          else fprintf(ficgp," %%*lf (%%*lf)");
                   6063:        }   
                   6064:        if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   6065:        else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   6066:       } /* state */
                   6067:     } /* vpopbased */
                   6068:     fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
1.201     brouard  6069:   } /* k1 */
1.219     brouard  6070:        
                   6071:        
1.126     brouard  6072:   /*3eme*/
                   6073:   for (k1=1; k1<= m ; k1 ++) { 
1.220     brouard  6074: 
1.126     brouard  6075:     for (cpt=1; cpt<= nlstate ; cpt ++) {
1.211     brouard  6076:       fprintf(ficgp,"\n# 3d: Life expectancy with EXP_ files:  cov=%d state=%d",k1, cpt);
1.224   ! brouard  6077:       for (k=1; k<=nqveff; k++){    /* For each covariate and each value */
        !          6078:        lv= decodtabm(k1,k,nqveff); /* Should be the covariate number corresponding to k1 combination */
1.223     brouard  6079:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6080:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6081:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6082:        vlv= nbcode[Tvaraff[k]][lv];
                   6083:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  6084:       }
                   6085:       fprintf(ficgp,"\n#\n");
1.223     brouard  6086:       if(invalidvarcomb[k1]){
                   6087:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6088:        continue;
                   6089:       }
1.219     brouard  6090:                        
1.126     brouard  6091:       /*       k=2+nlstate*(2*cpt-2); */
                   6092:       k=2+(nlstate+1)*(cpt-1);
1.201     brouard  6093:       fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);
1.199     brouard  6094:       fprintf(ficgp,"set ter svg size 640, 480\n\
1.201     brouard  6095: 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  6096:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
1.223     brouard  6097:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   6098:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   6099:        fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   6100:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   6101:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  6102:                                
1.126     brouard  6103:       */
                   6104:       for (i=1; i< nlstate ; i ++) {
1.223     brouard  6105:        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);
                   6106:        /*      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  6107:                                
1.126     brouard  6108:       } 
1.201     brouard  6109:       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  6110:     }
                   6111:   }
                   6112:   
1.223     brouard  6113:   /* 4eme */
1.201     brouard  6114:   /* Survival functions (period) from state i in state j by initial state i */
                   6115:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
1.220     brouard  6116: 
1.201     brouard  6117:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.211     brouard  6118:       fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
1.224   ! brouard  6119:       for (k=1; k<=nqveff; k++){    /* For each covariate and each value */
        !          6120:        lv= decodtabm(k1,k,nqveff); /* Should be the covariate number corresponding to k1 combination */
1.223     brouard  6121:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6122:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6123:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6124:        vlv= nbcode[Tvaraff[k]][lv];
                   6125:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  6126:       }
                   6127:       fprintf(ficgp,"\n#\n");
1.223     brouard  6128:       if(invalidvarcomb[k1]){
                   6129:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6130:        continue;
                   6131:       }
1.220     brouard  6132:                        
1.201     brouard  6133:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);
                   6134:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
1.220     brouard  6135: set ter svg size 640, 480\n                                                                                                                                                                                    \
                   6136: unset log y\n                                                                                                                                                                                                                                          \
1.201     brouard  6137: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  6138:       k=3;
1.201     brouard  6139:       for (i=1; i<= nlstate ; i ++){
1.223     brouard  6140:        if(i==1){
                   6141:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   6142:        }else{
                   6143:          fprintf(ficgp,", '' ");
                   6144:        }
                   6145:        l=(nlstate+ndeath)*(i-1)+1;
                   6146:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   6147:        for (j=2; j<= nlstate+ndeath ; j ++)
                   6148:          fprintf(ficgp,"+$%d",k+l+j-1);
                   6149:        fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
1.201     brouard  6150:       } /* nlstate */
                   6151:       fprintf(ficgp,"\nset out\n");
                   6152:     } /* end cpt state*/ 
                   6153:   } /* end covariate */  
1.220     brouard  6154:        
                   6155: /* 5eme */
1.201     brouard  6156:   /* Survival functions (period) from state i in state j by final state j */
1.202     brouard  6157:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
1.201     brouard  6158:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.223     brouard  6159:                        
1.201     brouard  6160:       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.224   ! brouard  6161:       for (k=1; k<=nqveff; k++){    /* For each covariate and each value */
        !          6162:                                lv= decodtabm(k1,k,nqveff); /* Should be the covariate number corresponding to k1 combination */
1.220     brouard  6163:                                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6164:                                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6165:                                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6166:                                vlv= nbcode[Tvaraff[k]][lv];
                   6167:                                fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  6168:       }
                   6169:       fprintf(ficgp,"\n#\n");
1.223     brouard  6170:       if(invalidvarcomb[k1]){
                   6171:                                fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6172:                                continue;
                   6173:       }
1.220     brouard  6174:                        
1.201     brouard  6175:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);
                   6176:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
1.220     brouard  6177: set ter svg size 640, 480\n                                                                                                                                                                                    \
                   6178: unset log y\n                                                                                                                                                                                                                                          \
1.201     brouard  6179: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  6180:       k=3;
1.201     brouard  6181:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
1.220     brouard  6182:                                if(j==1)
                   6183:                                        fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   6184:                                else
                   6185:                                        fprintf(ficgp,", '' ");
                   6186:                                l=(nlstate+ndeath)*(cpt-1) +j;
                   6187:                                fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   6188:                                /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   6189:                                /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   6190:                                fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
1.201     brouard  6191:       } /* nlstate */
                   6192:       fprintf(ficgp,", '' ");
                   6193:       fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   6194:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
1.220     brouard  6195:                                l=(nlstate+ndeath)*(cpt-1) +j;
                   6196:                                if(j < nlstate)
                   6197:                                        fprintf(ficgp,"$%d +",k+l);
                   6198:                                else
                   6199:                                        fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
1.201     brouard  6200:       }
                   6201:       fprintf(ficgp,"\nset out\n");
                   6202:     } /* end cpt state*/ 
                   6203:   } /* end covariate */  
1.220     brouard  6204:        
                   6205: /* 6eme */
1.202     brouard  6206:   /* CV preval stable (period) for each covariate */
1.211     brouard  6207:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
1.153     brouard  6208:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.223     brouard  6209:                        
1.211     brouard  6210:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.224   ! brouard  6211:       for (k=1; k<=nqveff; k++){    /* For each covariate and each value */
        !          6212:                                lv= decodtabm(k1,k,nqveff); /* Should be the covariate number corresponding to k1 combination */
1.220     brouard  6213:                                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6214:                                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6215:                                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6216:                                vlv= nbcode[Tvaraff[k]][lv];
                   6217:                                fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  6218:       }
                   6219:       fprintf(ficgp,"\n#\n");
1.223     brouard  6220:       if(invalidvarcomb[k1]){
                   6221:                                fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6222:                                continue;
                   6223:       }
                   6224:                        
1.201     brouard  6225:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);
1.126     brouard  6226:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.223     brouard  6227: set ter svg size 640, 480\n                                                                                                                                                                             \
                   6228: unset log y\n                                                                                                                                                                                                                                   \
1.153     brouard  6229: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  6230:       k=3; /* Offset */
1.153     brouard  6231:       for (i=1; i<= nlstate ; i ++){
1.220     brouard  6232:                                if(i==1)
                   6233:                                        fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   6234:                                else
                   6235:                                        fprintf(ficgp,", '' ");
                   6236:                                l=(nlstate+ndeath)*(i-1)+1;
                   6237:                                fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   6238:                                for (j=2; j<= nlstate ; j ++)
                   6239:                                        fprintf(ficgp,"+$%d",k+l+j-1);
                   6240:                                fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  6241:       } /* nlstate */
1.201     brouard  6242:       fprintf(ficgp,"\nset out\n");
1.153     brouard  6243:     } /* end cpt state*/ 
                   6244:   } /* end covariate */  
1.223     brouard  6245:        
                   6246:        
1.220     brouard  6247: /* 7eme */
1.218     brouard  6248:   if(backcast == 1){
1.217     brouard  6249:     /* CV back preval stable (period) for each covariate */
1.218     brouard  6250:     for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
                   6251:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.220     brouard  6252:                                fprintf(ficgp,"\n#\n#\n#CV Back preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.224   ! brouard  6253:                                for (k=1; k<=nqveff; k++){    /* For each covariate and each value */
        !          6254:                                        lv= decodtabm(k1,k,nqveff); /* Should be the covariate number corresponding to k1 combination */
1.220     brouard  6255:                                        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6256:                                        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
1.223     brouard  6257:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.220     brouard  6258:                                        vlv= nbcode[Tvaraff[k]][lv];
                   6259:                                        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6260:                                }
                   6261:                                fprintf(ficgp,"\n#\n");
                   6262:                                if(invalidvarcomb[k1]){
1.223     brouard  6263:                                        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6264:                                        continue;
1.220     brouard  6265:                                }
                   6266:                                
                   6267:                                fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1);
                   6268:                                fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
                   6269: set ter svg size 640, 480\n                                                                                                                                                                                    \
                   6270: unset log y\n                                                                                                                                                                                                                                          \
1.218     brouard  6271: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.220     brouard  6272:                                k=3; /* Offset */
                   6273:                                for (i=1; i<= nlstate ; i ++){
                   6274:                                        if(i==1)
                   6275:                                                fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   6276:                                        else
                   6277:                                                fprintf(ficgp,", '' ");
                   6278:                                        /* l=(nlstate+ndeath)*(i-1)+1; */
                   6279:                                        l=(nlstate+ndeath)*(cpt-1)+1;
                   6280:                                        /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   6281:                                        /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l+(cpt-1)+i-1); /\* a vérifier *\/ */
                   6282:                                        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+(cpt-1)+i-1); /* a vérifier */
                   6283:                                        /* for (j=2; j<= nlstate ; j ++) */
                   6284:                                        /*      fprintf(ficgp,"+$%d",k+l+j-1); */
                   6285:                                        /*      /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
                   6286:                                        fprintf(ficgp,") t \"bprev(%d,%d)\" w l",i,cpt);
                   6287:                                } /* nlstate */
                   6288:                                fprintf(ficgp,"\nset out\n");
1.218     brouard  6289:       } /* end cpt state*/ 
                   6290:     } /* end covariate */  
                   6291:   } /* End if backcast */
                   6292:   
1.223     brouard  6293:   /* 8eme */
1.218     brouard  6294:   if(prevfcast==1){
                   6295:     /* Projection from cross-sectional to stable (period) for each covariate */
                   6296:     
                   6297:     for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
1.211     brouard  6298:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.219     brouard  6299:                                fprintf(ficgp,"\n#\n#\n#Projection of prevalence to stable (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.224   ! brouard  6300:                                for (k=1; k<=nqveff; k++){    /* For each correspondig covariate value  */
        !          6301:                                        lv= decodtabm(k1,k,nqveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
1.219     brouard  6302:                                        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6303:                                        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6304:                                        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6305:                                        vlv= nbcode[Tvaraff[k]][lv];
1.220     brouard  6306:                                        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.219     brouard  6307:                                }
                   6308:                                fprintf(ficgp,"\n#\n");
1.220     brouard  6309:                                if(invalidvarcomb[k1]){
1.223     brouard  6310:                                        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6311:                                        continue;
1.220     brouard  6312:                                }
1.219     brouard  6313:                                
                   6314:                                fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
                   6315:                                fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1);
                   6316:                                fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.223     brouard  6317: set ter svg size 640, 480\n                                                                                                                                                                                    \
                   6318: unset log y\n                                                                                                                                                                                                                                          \
1.219     brouard  6319: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   6320:                                for (i=1; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   6321:                                        /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   6322:                                        /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   6323:                                        /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   6324:                                        /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   6325:                                        if(i==1){
                   6326:                                                fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   6327:                                        }else{
                   6328:                                                fprintf(ficgp,",\\\n '' ");
                   6329:                                        }
1.224   ! brouard  6330:                                        if(nqveff ==0){ /* No covariate */
1.219     brouard  6331:                                                ioffset=2; /* Age is in 2 */
                   6332:                                                /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   6333:                                                /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   6334:                                                /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   6335:                                                /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   6336:                                                fprintf(ficgp," u %d:(", ioffset); 
                   6337:                                                if(i==nlstate+1)
                   6338:                                                        fprintf(ficgp," $%d/(1.-$%d)) t 'pw.%d' with line ",                    \
                   6339:                                                                                        ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   6340:                                                else
                   6341:                                                        fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",                    \
                   6342:                                                                                        ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   6343:                                        }else{ /* more than 2 covariates */
1.224   ! brouard  6344:                                                if(nqveff ==1){
1.219     brouard  6345:                                                        ioffset=4; /* Age is in 4 */
                   6346:                                                }else{
                   6347:                                                        ioffset=6; /* Age is in 6 */
1.223     brouard  6348:                                                        /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   6349:                                                        /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
1.219     brouard  6350:                                                }   
1.220     brouard  6351:                                                fprintf(ficgp," u %d:(",ioffset); 
1.219     brouard  6352:                                                kl=0;
1.220     brouard  6353:                                                strcpy(gplotcondition,"(");
1.224   ! brouard  6354:                                                for (k=1; k<=nqveff; k++){    /* For each covariate writing the chain of conditions */
        !          6355:                                                        lv= decodtabm(k1,k,nqveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
1.219     brouard  6356:                                                        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6357:                                                        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6358:                                                        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.220     brouard  6359:                                                        vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   6360:                                                        kl++;
                   6361:                                                        sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
1.219     brouard  6362:                                                        kl++;
1.224   ! brouard  6363:                                                        if(k <nqveff && nqveff>1)
1.220     brouard  6364:                                                                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   6365:                                                }
                   6366:                                                strcpy(gplotcondition+strlen(gplotcondition),")");
                   6367:                                                /* 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 *\/ */
                   6368:                                                /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   6369:                                                /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   6370:                                                /* ''  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*/
                   6371:                                                if(i==nlstate+1){
                   6372:                                                        fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p.%d' with line ", gplotcondition, \
                   6373:                                                                                        ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   6374:                                                }else{
1.223     brouard  6375:                                                        fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   6376:                                                                                        ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
1.220     brouard  6377:                                                }
1.219     brouard  6378:                                        } /* end if covariate */
                   6379:                                } /* nlstate */
                   6380:                                fprintf(ficgp,"\nset out\n");
1.223     brouard  6381:       } /* end cpt state*/
                   6382:     } /* end covariate */
                   6383:   } /* End if prevfcast */
1.219     brouard  6384:        
1.211     brouard  6385:        
1.223     brouard  6386:   /* proba elementaires */
                   6387:   fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
1.126     brouard  6388:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  6389:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  6390:     for(k=1; k <=(nlstate+ndeath); k++){
                   6391:       if (k != i) {
1.223     brouard  6392:                                fprintf(ficgp,"#   current state %d\n",k);
                   6393:                                for(j=1; j <=ncovmodel; j++){
                   6394:                                        fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   6395:                                        jk++; 
                   6396:                                }
                   6397:                                fprintf(ficgp,"\n");
1.126     brouard  6398:       }
                   6399:     }
1.223     brouard  6400:   }
1.187     brouard  6401:   fprintf(ficgp,"##############\n#\n");
1.223     brouard  6402:        
1.145     brouard  6403:   /*goto avoid;*/
1.200     brouard  6404:   fprintf(ficgp,"\n##############\n#Graphics of probabilities or incidences\n#############\n");
1.187     brouard  6405:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   6406:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   6407:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   6408:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   6409:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6410:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   6411:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6412:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   6413:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   6414:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6415:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   6416:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   6417:   fprintf(ficgp,"#\n");
1.223     brouard  6418:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
                   6419:     fprintf(ficgp,"# ng=%d\n",ng);
1.224   ! brouard  6420:     fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",nqveff,m);
1.223     brouard  6421:     for(jk=1; jk <=m; jk++) {
                   6422:       fprintf(ficgp,"#    jk=%d\n",jk);
                   6423:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);
                   6424:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   6425:       if (ng==1){
                   6426:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   6427:        fprintf(ficgp,"\nunset log y");
                   6428:       }else if (ng==2){
                   6429:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   6430:        fprintf(ficgp,"\nset log y");
                   6431:       }else if (ng==3){
                   6432:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   6433:        fprintf(ficgp,"\nset log y");
                   6434:       }else
                   6435:        fprintf(ficgp,"\nunset title ");
                   6436:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   6437:       i=1;
                   6438:       for(k2=1; k2<=nlstate; k2++) {
                   6439:        k3=i;
                   6440:        for(k=1; k<=(nlstate+ndeath); k++) {
                   6441:          if (k != k2){
                   6442:            switch( ng) {
                   6443:            case 1:
                   6444:              if(nagesqr==0)
                   6445:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   6446:              else /* nagesqr =1 */
                   6447:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   6448:              break;
                   6449:            case 2: /* ng=2 */
                   6450:              if(nagesqr==0)
                   6451:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   6452:              else /* nagesqr =1 */
                   6453:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   6454:              break;
                   6455:            case 3:
                   6456:              if(nagesqr==0)
                   6457:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   6458:              else /* nagesqr =1 */
                   6459:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   6460:              break;
                   6461:            }
                   6462:            ij=1;/* To be checked else nbcode[0][0] wrong */
                   6463:            for(j=3; j <=ncovmodel-nagesqr; j++) {
                   6464:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
                   6465:              if(ij <=cptcovage) { /* Bug valgrind */
                   6466:                if((j-2)==Tage[ij]) { /* Bug valgrind */
                   6467:                  fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   6468:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   6469:                  ij++;
                   6470:                }
                   6471:              }
                   6472:              else
                   6473:                fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   6474:            }
                   6475:          }else{
                   6476:            i=i-ncovmodel;
                   6477:            if(ng !=1 ) /* For logit formula of log p11 is more difficult to get */
                   6478:              fprintf(ficgp," (1.");
                   6479:          }
1.217     brouard  6480:           
1.223     brouard  6481:          if(ng != 1){
                   6482:            fprintf(ficgp,")/(1");
1.126     brouard  6483:             
1.223     brouard  6484:            for(k1=1; k1 <=nlstate; k1++){ 
                   6485:              if(nagesqr==0)
                   6486:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                   6487:              else /* nagesqr =1 */
                   6488:                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  6489:               
1.223     brouard  6490:              ij=1;
                   6491:              for(j=3; j <=ncovmodel-nagesqr; j++){
                   6492:                if(ij <=cptcovage) { /* Bug valgrind */
                   6493:                  if((j-2)==Tage[ij]) { /* Bug valgrind */
                   6494:                    fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   6495:                    /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   6496:                    ij++;
                   6497:                  }
                   6498:                }
                   6499:                else
                   6500:                  fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   6501:              }
                   6502:              fprintf(ficgp,")");
                   6503:            }
                   6504:            fprintf(ficgp,")");
                   6505:            if(ng ==2)
                   6506:              fprintf(ficgp," t \"p%d%d\" ", k2,k);
                   6507:            else /* ng= 3 */
                   6508:              fprintf(ficgp," t \"i%d%d\" ", k2,k);
                   6509:          }else{ /* end ng <> 1 */
                   6510:            if( k !=k2) /* logit p11 is hard to draw */
                   6511:              fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
                   6512:          }
                   6513:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   6514:            fprintf(ficgp,",");
                   6515:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   6516:            fprintf(ficgp,",");
                   6517:          i=i+ncovmodel;
                   6518:        } /* end k */
                   6519:       } /* end k2 */
                   6520:       fprintf(ficgp,"\n set out\n");
                   6521:     } /* end jk */
                   6522:   } /* end ng */
                   6523:   /* avoid: */
                   6524:   fflush(ficgp); 
1.126     brouard  6525: }  /* end gnuplot */
                   6526: 
                   6527: 
                   6528: /*************** Moving average **************/
1.219     brouard  6529: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  6530:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  6531:    
1.222     brouard  6532:    int i, cpt, cptcod;
                   6533:    int modcovmax =1;
                   6534:    int mobilavrange, mob;
                   6535:    int iage=0;
                   6536: 
                   6537:    double sum=0.;
                   6538:    double age;
                   6539:    double *sumnewp, *sumnewm;
                   6540:    double *agemingood, *agemaxgood; /* Currently identical for all covariates */
                   6541:   
                   6542:   
1.224   ! brouard  6543:    /* modcovmax=2*nqveff;/\* Max number of modalities. We suppose  */
1.222     brouard  6544:    /*             a covariate has 2 modalities, should be equal to ncovcombmax  *\/ */
                   6545: 
                   6546:    sumnewp = vector(1,ncovcombmax);
                   6547:    sumnewm = vector(1,ncovcombmax);
                   6548:    agemingood = vector(1,ncovcombmax); 
                   6549:    agemaxgood = vector(1,ncovcombmax);
                   6550: 
                   6551:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   6552:      sumnewm[cptcod]=0.;
                   6553:      sumnewp[cptcod]=0.;
                   6554:      agemingood[cptcod]=0;
                   6555:      agemaxgood[cptcod]=0;
                   6556:    }
                   6557:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   6558:   
                   6559:    if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   6560:      if(mobilav==1) mobilavrange=5; /* default */
                   6561:      else mobilavrange=mobilav;
                   6562:      for (age=bage; age<=fage; age++)
                   6563:        for (i=1; i<=nlstate;i++)
                   6564:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   6565:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   6566:      /* We keep the original values on the extreme ages bage, fage and for 
                   6567:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   6568:        we use a 5 terms etc. until the borders are no more concerned. 
                   6569:      */ 
                   6570:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   6571:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   6572:         for (i=1; i<=nlstate;i++){
                   6573:           for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   6574:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   6575:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   6576:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   6577:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   6578:             }
                   6579:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   6580:           }
                   6581:         }
                   6582:        }/* end age */
                   6583:      }/* end mob */
                   6584:    }else
                   6585:      return -1;
                   6586:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   6587:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   6588:      if(invalidvarcomb[cptcod]){
                   6589:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   6590:        continue;
                   6591:      }
1.219     brouard  6592: 
1.222     brouard  6593:      agemingood[cptcod]=fage-(mob-1)/2;
                   6594:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, finding the youngest wrong */
                   6595:        sumnewm[cptcod]=0.;
                   6596:        for (i=1; i<=nlstate;i++){
                   6597:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   6598:        }
                   6599:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   6600:         agemingood[cptcod]=age;
                   6601:        }else{ /* bad */
                   6602:         for (i=1; i<=nlstate;i++){
                   6603:           mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   6604:         } /* i */
                   6605:        } /* end bad */
                   6606:      }/* age */
                   6607:      sum=0.;
                   6608:      for (i=1; i<=nlstate;i++){
                   6609:        sum+=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   6610:      }
                   6611:      if(fabs(sum - 1.) > 1.e-3) { /* bad */
                   6612:        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);
                   6613:        /* for (i=1; i<=nlstate;i++){ */
                   6614:        /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   6615:        /* } /\* i *\/ */
                   6616:      } /* end bad */
                   6617:      /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   6618:      /* From youngest, finding the oldest wrong */
                   6619:      agemaxgood[cptcod]=bage+(mob-1)/2;
                   6620:      for (age=bage+(mob-1)/2; age<=fage; age++){
                   6621:        sumnewm[cptcod]=0.;
                   6622:        for (i=1; i<=nlstate;i++){
                   6623:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   6624:        }
                   6625:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   6626:         agemaxgood[cptcod]=age;
                   6627:        }else{ /* bad */
                   6628:         for (i=1; i<=nlstate;i++){
                   6629:           mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   6630:         } /* i */
                   6631:        } /* end bad */
                   6632:      }/* age */
                   6633:      sum=0.;
                   6634:      for (i=1; i<=nlstate;i++){
                   6635:        sum+=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   6636:      }
                   6637:      if(fabs(sum - 1.) > 1.e-3) { /* bad */
                   6638:        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);
                   6639:        /* for (i=1; i<=nlstate;i++){ */
                   6640:        /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   6641:        /* } /\* i *\/ */
                   6642:      } /* end bad */
                   6643:                
                   6644:      for (age=bage; age<=fage; age++){
                   6645:        printf("%d %d ", cptcod, (int)age);
                   6646:        sumnewp[cptcod]=0.;
                   6647:        sumnewm[cptcod]=0.;
                   6648:        for (i=1; i<=nlstate;i++){
                   6649:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   6650:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   6651:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   6652:        }
                   6653:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   6654:      }
                   6655:      /* printf("\n"); */
                   6656:      /* } */
                   6657:      /* brutal averaging */
                   6658:      for (i=1; i<=nlstate;i++){
                   6659:        for (age=1; age<=bage; age++){
                   6660:         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   6661:         /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
                   6662:        }       
                   6663:        for (age=fage; age<=AGESUP; age++){
                   6664:         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   6665:         /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
                   6666:        }
                   6667:      } /* end i status */
                   6668:      for (i=nlstate+1; i<=nlstate+ndeath;i++){
                   6669:        for (age=1; age<=AGESUP; age++){
                   6670:         /*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*/
                   6671:         mobaverage[(int)age][i][cptcod]=0.;
                   6672:        }
                   6673:      }
                   6674:    }/* end cptcod */
                   6675:    free_vector(sumnewm,1, ncovcombmax);
                   6676:    free_vector(sumnewp,1, ncovcombmax);
                   6677:    free_vector(agemaxgood,1, ncovcombmax);
                   6678:    free_vector(agemingood,1, ncovcombmax);
                   6679:    return 0;
                   6680:  }/* End movingaverage */
1.218     brouard  6681:  
1.126     brouard  6682: 
                   6683: /************** Forecasting ******************/
1.224   ! brouard  6684: 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 nqveff){
1.126     brouard  6685:   /* proj1, year, month, day of starting projection 
                   6686:      agemin, agemax range of age
                   6687:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   6688:      anproj2 year of en of projection (same day and month as proj1).
                   6689:   */
1.164     brouard  6690:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126     brouard  6691:   double agec; /* generic age */
                   6692:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   6693:   double *popeffectif,*popcount;
                   6694:   double ***p3mat;
1.218     brouard  6695:   /* double ***mobaverage; */
1.126     brouard  6696:   char fileresf[FILENAMELENGTH];
                   6697: 
                   6698:   agelim=AGESUP;
1.211     brouard  6699:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   6700:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   6701:      We still use firstpass and lastpass as another selection.
                   6702:   */
1.214     brouard  6703:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   6704:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  6705:  
1.201     brouard  6706:   strcpy(fileresf,"F_"); 
                   6707:   strcat(fileresf,fileresu);
1.126     brouard  6708:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   6709:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   6710:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   6711:   }
1.215     brouard  6712:   printf("Computing forecasting: result on file '%s', please wait... \n", fileresf);
                   6713:   fprintf(ficlog,"Computing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  6714: 
1.224   ! brouard  6715:   if (nqveff==0) ncodemax[nqveff]=1;
1.126     brouard  6716: 
                   6717: 
                   6718:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   6719:   if (stepm<=12) stepsize=1;
                   6720:   if(estepm < stepm){
                   6721:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6722:   }
                   6723:   else  hstepm=estepm;   
                   6724: 
                   6725:   hstepm=hstepm/stepm; 
                   6726:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   6727:                                fractional in yp1 */
                   6728:   anprojmean=yp;
                   6729:   yp2=modf((yp1*12),&yp);
                   6730:   mprojmean=yp;
                   6731:   yp1=modf((yp2*30.5),&yp);
                   6732:   jprojmean=yp;
                   6733:   if(jprojmean==0) jprojmean=1;
                   6734:   if(mprojmean==0) jprojmean=1;
                   6735: 
1.224   ! brouard  6736:   i1=nqveff;
1.126     brouard  6737:   if (cptcovn < 1){i1=1;}
                   6738:   
                   6739:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   6740:   
                   6741:   fprintf(ficresf,"#****** Routine prevforecast **\n");
                   6742: 
                   6743: /*           if (h==(int)(YEARM*yearp)){ */
                   6744:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
1.224   ! brouard  6745:     for(cptcod=1;cptcod<=ncodemax[nqveff];cptcod++){
1.126     brouard  6746:       k=k+1;
1.211     brouard  6747:       fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
1.224   ! brouard  6748:       for(j=1;j<=nqveff;j++) {
1.219     brouard  6749:                                fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  6750:       }
1.211     brouard  6751:       fprintf(ficresf," yearproj age");
1.126     brouard  6752:       for(j=1; j<=nlstate+ndeath;j++){ 
1.219     brouard  6753:                                for(i=1; i<=nlstate;i++)              
1.126     brouard  6754:           fprintf(ficresf," p%d%d",i,j);
1.219     brouard  6755:                                fprintf(ficresf," wp.%d",j);
1.126     brouard  6756:       }
1.217     brouard  6757:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
1.219     brouard  6758:                                fprintf(ficresf,"\n");
                   6759:                                fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   6760:                                for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   6761:                                        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   6762:                                        nhstepm = nhstepm/hstepm; 
                   6763:                                        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6764:                                        oldm=oldms;savm=savms;
                   6765:                                        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
                   6766:                                        
                   6767:                                        for (h=0; h<=nhstepm; h++){
                   6768:                                                if (h*hstepm/YEARM*stepm ==yearp) {
1.126     brouard  6769:               fprintf(ficresf,"\n");
1.224   ! brouard  6770:               for(j=1;j<=nqveff;j++) 
1.198     brouard  6771:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.219     brouard  6772:                                                        fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   6773:                                                } 
                   6774:                                                for(j=1; j<=nlstate+ndeath;j++) {
                   6775:                                                        ppij=0.;
                   6776:                                                        for(i=1; i<=nlstate;i++) {
                   6777:                                                                if (mobilav==1) 
                   6778:                                                                        ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
                   6779:                                                                else {
                   6780:                                                                        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
                   6781:                                                                }
                   6782:                                                                if (h*hstepm/YEARM*stepm== yearp) {
                   6783:                                                                        fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   6784:                                                                }
                   6785:                                                        } /* end i */
                   6786:                                                        if (h*hstepm/YEARM*stepm==yearp) {
                   6787:                                                                fprintf(ficresf," %.3f", ppij);
                   6788:                                                        }
                   6789:                                                }/* end j */
                   6790:                                        } /* end h */
                   6791:                                        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6792:                                } /* end agec */
1.126     brouard  6793:       } /* end yearp */
                   6794:     } /* end cptcod */
                   6795:   } /* end  cptcov */
1.219     brouard  6796:        
1.126     brouard  6797:   fclose(ficresf);
1.215     brouard  6798:   printf("End of Computing forecasting \n");
                   6799:   fprintf(ficlog,"End of Computing forecasting\n");
                   6800: 
1.126     brouard  6801: }
                   6802: 
1.218     brouard  6803: /* /\************** Back Forecasting ******************\/ */
1.224   ! brouard  6804: /* 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 nqveff){ */
1.218     brouard  6805: /*   /\* back1, year, month, day of starting backection  */
                   6806: /*      agemin, agemax range of age */
                   6807: /*      dateprev1 dateprev2 range of dates during which prevalence is computed */
                   6808: /*      anback2 year of en of backection (same day and month as back1). */
                   6809: /*   *\/ */
                   6810: /*   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1; */
                   6811: /*   double agec; /\* generic age *\/ */
                   6812: /*   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean; */
                   6813: /*   double *popeffectif,*popcount; */
                   6814: /*   double ***p3mat; */
                   6815: /*   /\* double ***mobaverage; *\/ */
                   6816: /*   char fileresfb[FILENAMELENGTH]; */
                   6817:        
                   6818: /*   agelim=AGESUP; */
                   6819: /*   /\* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people */
                   6820: /*      in each health status at the date of interview (if between dateprev1 and dateprev2). */
                   6821: /*      We still use firstpass and lastpass as another selection. */
                   6822: /*   *\/ */
                   6823: /*   /\* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ *\/ */
                   6824: /*   /\*             firstpass, lastpass,  stepm,  weightopt, model); *\/ */
                   6825: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   6826:        
                   6827: /*   strcpy(fileresfb,"FB_");  */
                   6828: /*   strcat(fileresfb,fileresu); */
                   6829: /*   if((ficresfb=fopen(fileresfb,"w"))==NULL) { */
                   6830: /*     printf("Problem with back forecast resultfile: %s\n", fileresfb); */
                   6831: /*     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb); */
                   6832: /*   } */
                   6833: /*   printf("Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
                   6834: /*   fprintf(ficlog,"Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
                   6835:        
1.224   ! brouard  6836: /*   if (nqveff==0) ncodemax[nqveff]=1; */
1.218     brouard  6837:        
                   6838: /*   /\* if (mobilav!=0) { *\/ */
                   6839: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   6840: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   6841: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   6842: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   6843: /*   /\*   } *\/ */
                   6844: /*   /\* } *\/ */
                   6845:        
                   6846: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   6847: /*   if (stepm<=12) stepsize=1; */
                   6848: /*   if(estepm < stepm){ */
                   6849: /*     printf ("Problem %d lower than %d\n",estepm, stepm); */
                   6850: /*   } */
                   6851: /*   else  hstepm=estepm;    */
                   6852:        
                   6853: /*   hstepm=hstepm/stepm;  */
                   6854: /*   yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   6855: /*                                fractional in yp1 *\/ */
                   6856: /*   anprojmean=yp; */
                   6857: /*   yp2=modf((yp1*12),&yp); */
                   6858: /*   mprojmean=yp; */
                   6859: /*   yp1=modf((yp2*30.5),&yp); */
                   6860: /*   jprojmean=yp; */
                   6861: /*   if(jprojmean==0) jprojmean=1; */
                   6862: /*   if(mprojmean==0) jprojmean=1; */
                   6863:        
1.224   ! brouard  6864: /*   i1=nqveff; */
1.218     brouard  6865: /*   if (cptcovn < 1){i1=1;} */
1.217     brouard  6866:   
1.218     brouard  6867: /*   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);  */
1.217     brouard  6868:   
1.218     brouard  6869: /*   fprintf(ficresfb,"#****** Routine prevbackforecast **\n"); */
                   6870:        
                   6871: /*     /\*           if (h==(int)(YEARM*yearp)){ *\/ */
                   6872: /*   for(cptcov=1, k=0;cptcov<=i1;cptcov++){ */
1.224   ! brouard  6873: /*     for(cptcod=1;cptcod<=ncodemax[nqveff];cptcod++){ */
1.218     brouard  6874: /*       k=k+1; */
                   6875: /*       fprintf(ficresfb,"\n#****** hbijx=probability over h years, hp.jx is weighted by observed prev \n#"); */
1.224   ! brouard  6876: /*       for(j=1;j<=nqveff;j++) { */
1.218     brouard  6877: /*                             fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   6878: /*       } */
                   6879: /*       fprintf(ficresfb," yearbproj age"); */
                   6880: /*       for(j=1; j<=nlstate+ndeath;j++){  */
                   6881: /*                             for(i=1; i<=nlstate;i++)               */
                   6882: /*           fprintf(ficresfb," p%d%d",i,j); */
                   6883: /*                             fprintf(ficresfb," p.%d",j); */
                   6884: /*       } */
                   6885: /*       for (yearp=0; yearp>=(anback2-anback1);yearp -=stepsize) {  */
                   6886: /*                             /\* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  *\/ */
                   6887: /*                             fprintf(ficresfb,"\n"); */
                   6888: /*                             fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp);    */
                   6889: /*                             for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   6890: /*                                     nhstepm=(int) rint((agelim-agec)*YEARM/stepm);  */
                   6891: /*                                     nhstepm = nhstepm/hstepm;  */
                   6892: /*                                     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   6893: /*                                     oldm=oldms;savm=savms; */
                   6894: /*                                     hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm,oldm,savm, dnewm, doldm, dsavm, k);       */
                   6895: /*                                     for (h=0; h<=nhstepm; h++){ */
                   6896: /*                                             if (h*hstepm/YEARM*stepm ==yearp) { */
                   6897: /*               fprintf(ficresfb,"\n"); */
1.224   ! brouard  6898: /*               for(j=1;j<=nqveff;j++)  */
1.218     brouard  6899: /*                 fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   6900: /*                                                     fprintf(ficresfb,"%.f %.f ",anback1+yearp,agec+h*hstepm/YEARM*stepm); */
                   6901: /*                                             }  */
                   6902: /*                                             for(j=1; j<=nlstate+ndeath;j++) { */
                   6903: /*                                                     ppij=0.; */
                   6904: /*                                                     for(i=1; i<=nlstate;i++) { */
                   6905: /*                                                             if (mobilav==1)  */
                   6906: /*                                                                     ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod]; */
                   6907: /*                                                             else { */
                   6908: /*                                                                     ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod]; */
                   6909: /*                                                             } */
                   6910: /*                                                             if (h*hstepm/YEARM*stepm== yearp) { */
                   6911: /*                                                                     fprintf(ficresfb," %.3f", p3mat[i][j][h]); */
                   6912: /*                                                             } */
                   6913: /*                                                     } /\* end i *\/ */
                   6914: /*                                                     if (h*hstepm/YEARM*stepm==yearp) { */
                   6915: /*                                                             fprintf(ficresfb," %.3f", ppij); */
                   6916: /*                                                     } */
                   6917: /*                                             }/\* end j *\/ */
                   6918: /*                                     } /\* end h *\/ */
                   6919: /*                                     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   6920: /*                             } /\* end agec *\/ */
                   6921: /*       } /\* end yearp *\/ */
                   6922: /*     } /\* end cptcod *\/ */
                   6923: /*   } /\* end  cptcov *\/ */
                   6924:        
                   6925: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   6926:        
                   6927: /*   fclose(ficresfb); */
                   6928: /*   printf("End of Computing Back forecasting \n"); */
                   6929: /*   fprintf(ficlog,"End of Computing Back forecasting\n"); */
1.217     brouard  6930:        
1.218     brouard  6931: /* } */
1.217     brouard  6932: 
1.126     brouard  6933: /************** Forecasting *****not tested NB*************/
1.169     brouard  6934: void populforecast(char fileres[], double anpyram,double mpyram,double jpyram,double ageminpar, double agemax,double dateprev1, double dateprev2, int mobilav, double agedeb, double fage, int popforecast, char popfile[], double anpyram1,double p[], int i2){
1.126     brouard  6935:   
                   6936:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
                   6937:   int *popage;
                   6938:   double calagedatem, agelim, kk1, kk2;
                   6939:   double *popeffectif,*popcount;
                   6940:   double ***p3mat,***tabpop,***tabpopprev;
1.218     brouard  6941:   /* double ***mobaverage; */
1.126     brouard  6942:   char filerespop[FILENAMELENGTH];
                   6943: 
                   6944:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6945:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6946:   agelim=AGESUP;
                   6947:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
                   6948:   
                   6949:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   6950:   
                   6951:   
1.201     brouard  6952:   strcpy(filerespop,"POP_"); 
                   6953:   strcat(filerespop,fileresu);
1.126     brouard  6954:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
                   6955:     printf("Problem with forecast resultfile: %s\n", filerespop);
                   6956:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
                   6957:   }
                   6958:   printf("Computing forecasting: result on file '%s' \n", filerespop);
                   6959:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
                   6960: 
1.224   ! brouard  6961:   if (nqveff==0) ncodemax[nqveff]=1;
1.126     brouard  6962: 
1.218     brouard  6963:   /* if (mobilav!=0) { */
                   6964:   /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6965:   /*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ */
                   6966:   /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   6967:   /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   6968:   /*   } */
                   6969:   /* } */
1.126     brouard  6970: 
                   6971:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   6972:   if (stepm<=12) stepsize=1;
                   6973:   
                   6974:   agelim=AGESUP;
                   6975:   
                   6976:   hstepm=1;
                   6977:   hstepm=hstepm/stepm; 
1.218     brouard  6978:        
1.126     brouard  6979:   if (popforecast==1) {
                   6980:     if((ficpop=fopen(popfile,"r"))==NULL) {
                   6981:       printf("Problem with population file : %s\n",popfile);exit(0);
                   6982:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
                   6983:     } 
                   6984:     popage=ivector(0,AGESUP);
                   6985:     popeffectif=vector(0,AGESUP);
                   6986:     popcount=vector(0,AGESUP);
                   6987:     
                   6988:     i=1;   
                   6989:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
1.218     brouard  6990:     
1.126     brouard  6991:     imx=i;
                   6992:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
                   6993:   }
1.218     brouard  6994:   
1.126     brouard  6995:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
1.224   ! brouard  6996:     for(cptcod=1;cptcod<=ncodemax[nqveff];cptcod++){
1.126     brouard  6997:       k=k+1;
                   6998:       fprintf(ficrespop,"\n#******");
1.224   ! brouard  6999:       for(j=1;j<=nqveff;j++) {
1.198     brouard  7000:        fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  7001:       }
                   7002:       fprintf(ficrespop,"******\n");
                   7003:       fprintf(ficrespop,"# Age");
                   7004:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
                   7005:       if (popforecast==1)  fprintf(ficrespop," [Population]");
                   7006:       
                   7007:       for (cpt=0; cpt<=0;cpt++) { 
                   7008:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   7009:        
1.218     brouard  7010:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
1.126     brouard  7011:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   7012:          nhstepm = nhstepm/hstepm; 
                   7013:          
                   7014:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7015:          oldm=oldms;savm=savms;
                   7016:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
1.218     brouard  7017:          
1.126     brouard  7018:          for (h=0; h<=nhstepm; h++){
                   7019:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   7020:              fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   7021:            } 
                   7022:            for(j=1; j<=nlstate+ndeath;j++) {
                   7023:              kk1=0.;kk2=0;
                   7024:              for(i=1; i<=nlstate;i++) {              
                   7025:                if (mobilav==1) 
                   7026:                  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
                   7027:                else {
                   7028:                  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
                   7029:                }
                   7030:              }
                   7031:              if (h==(int)(calagedatem+12*cpt)){
                   7032:                tabpop[(int)(agedeb)][j][cptcod]=kk1;
1.218     brouard  7033:                /*fprintf(ficrespop," %.3f", kk1);
                   7034:                  if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
1.126     brouard  7035:              }
                   7036:            }
                   7037:            for(i=1; i<=nlstate;i++){
                   7038:              kk1=0.;
1.218     brouard  7039:              for(j=1; j<=nlstate;j++){
                   7040:                kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
                   7041:              }
                   7042:              tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
1.126     brouard  7043:            }
1.218     brouard  7044:            
                   7045:            if (h==(int)(calagedatem+12*cpt))
                   7046:              for(j=1; j<=nlstate;j++) 
                   7047:                fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
1.126     brouard  7048:          }
                   7049:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7050:        }
                   7051:       }
1.218     brouard  7052:       
                   7053:       /******/
                   7054:       
1.126     brouard  7055:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
                   7056:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   7057:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   7058:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   7059:          nhstepm = nhstepm/hstepm; 
                   7060:          
                   7061:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7062:          oldm=oldms;savm=savms;
                   7063:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   7064:          for (h=0; h<=nhstepm; h++){
                   7065:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   7066:              fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   7067:            } 
                   7068:            for(j=1; j<=nlstate+ndeath;j++) {
                   7069:              kk1=0.;kk2=0;
                   7070:              for(i=1; i<=nlstate;i++) {              
                   7071:                kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
                   7072:              }
                   7073:              if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
                   7074:            }
                   7075:          }
                   7076:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7077:        }
                   7078:       }
1.218     brouard  7079:     } 
1.126     brouard  7080:   }
1.218     brouard  7081:   
                   7082:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7083:   
1.126     brouard  7084:   if (popforecast==1) {
                   7085:     free_ivector(popage,0,AGESUP);
                   7086:     free_vector(popeffectif,0,AGESUP);
                   7087:     free_vector(popcount,0,AGESUP);
                   7088:   }
                   7089:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7090:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7091:   fclose(ficrespop);
                   7092: } /* End of popforecast */
1.218     brouard  7093:  
1.126     brouard  7094: int fileappend(FILE *fichier, char *optionfich)
                   7095: {
                   7096:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   7097:     printf("Problem with file: %s\n", optionfich);
                   7098:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   7099:     return (0);
                   7100:   }
                   7101:   fflush(fichier);
                   7102:   return (1);
                   7103: }
                   7104: 
                   7105: 
                   7106: /**************** function prwizard **********************/
                   7107: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   7108: {
                   7109: 
                   7110:   /* Wizard to print covariance matrix template */
                   7111: 
1.164     brouard  7112:   char ca[32], cb[32];
                   7113:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  7114:   int numlinepar;
                   7115: 
                   7116:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7117:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7118:   for(i=1; i <=nlstate; i++){
                   7119:     jj=0;
                   7120:     for(j=1; j <=nlstate+ndeath; j++){
                   7121:       if(j==i) continue;
                   7122:       jj++;
                   7123:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   7124:       printf("%1d%1d",i,j);
                   7125:       fprintf(ficparo,"%1d%1d",i,j);
                   7126:       for(k=1; k<=ncovmodel;k++){
                   7127:        /*        printf(" %lf",param[i][j][k]); */
                   7128:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   7129:        printf(" 0.");
                   7130:        fprintf(ficparo," 0.");
                   7131:       }
                   7132:       printf("\n");
                   7133:       fprintf(ficparo,"\n");
                   7134:     }
                   7135:   }
                   7136:   printf("# Scales (for hessian or gradient estimation)\n");
                   7137:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   7138:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   7139:   for(i=1; i <=nlstate; i++){
                   7140:     jj=0;
                   7141:     for(j=1; j <=nlstate+ndeath; j++){
                   7142:       if(j==i) continue;
                   7143:       jj++;
                   7144:       fprintf(ficparo,"%1d%1d",i,j);
                   7145:       printf("%1d%1d",i,j);
                   7146:       fflush(stdout);
                   7147:       for(k=1; k<=ncovmodel;k++){
                   7148:        /*      printf(" %le",delti3[i][j][k]); */
                   7149:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   7150:        printf(" 0.");
                   7151:        fprintf(ficparo," 0.");
                   7152:       }
                   7153:       numlinepar++;
                   7154:       printf("\n");
                   7155:       fprintf(ficparo,"\n");
                   7156:     }
                   7157:   }
                   7158:   printf("# Covariance matrix\n");
                   7159: /* # 121 Var(a12)\n\ */
                   7160: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   7161: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   7162: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   7163: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   7164: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   7165: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   7166: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   7167:   fflush(stdout);
                   7168:   fprintf(ficparo,"# Covariance matrix\n");
                   7169:   /* # 121 Var(a12)\n\ */
                   7170:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   7171:   /* #   ...\n\ */
                   7172:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   7173:   
                   7174:   for(itimes=1;itimes<=2;itimes++){
                   7175:     jj=0;
                   7176:     for(i=1; i <=nlstate; i++){
                   7177:       for(j=1; j <=nlstate+ndeath; j++){
                   7178:        if(j==i) continue;
                   7179:        for(k=1; k<=ncovmodel;k++){
                   7180:          jj++;
                   7181:          ca[0]= k+'a'-1;ca[1]='\0';
                   7182:          if(itimes==1){
                   7183:            printf("#%1d%1d%d",i,j,k);
                   7184:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   7185:          }else{
                   7186:            printf("%1d%1d%d",i,j,k);
                   7187:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   7188:            /*  printf(" %.5le",matcov[i][j]); */
                   7189:          }
                   7190:          ll=0;
                   7191:          for(li=1;li <=nlstate; li++){
                   7192:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   7193:              if(lj==li) continue;
                   7194:              for(lk=1;lk<=ncovmodel;lk++){
                   7195:                ll++;
                   7196:                if(ll<=jj){
                   7197:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   7198:                  if(ll<jj){
                   7199:                    if(itimes==1){
                   7200:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7201:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7202:                    }else{
                   7203:                      printf(" 0.");
                   7204:                      fprintf(ficparo," 0.");
                   7205:                    }
                   7206:                  }else{
                   7207:                    if(itimes==1){
                   7208:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   7209:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   7210:                    }else{
                   7211:                      printf(" 0.");
                   7212:                      fprintf(ficparo," 0.");
                   7213:                    }
                   7214:                  }
                   7215:                }
                   7216:              } /* end lk */
                   7217:            } /* end lj */
                   7218:          } /* end li */
                   7219:          printf("\n");
                   7220:          fprintf(ficparo,"\n");
                   7221:          numlinepar++;
                   7222:        } /* end k*/
                   7223:       } /*end j */
                   7224:     } /* end i */
                   7225:   } /* end itimes */
                   7226: 
                   7227: } /* end of prwizard */
                   7228: /******************* Gompertz Likelihood ******************************/
                   7229: double gompertz(double x[])
                   7230: { 
                   7231:   double A,B,L=0.0,sump=0.,num=0.;
                   7232:   int i,n=0; /* n is the size of the sample */
                   7233: 
1.220     brouard  7234:   for (i=1;i<=imx ; i++) {
1.126     brouard  7235:     sump=sump+weight[i];
                   7236:     /*    sump=sump+1;*/
                   7237:     num=num+1;
                   7238:   }
                   7239:  
                   7240:  
                   7241:   /* for (i=0; i<=imx; i++) 
                   7242:      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]);*/
                   7243: 
                   7244:   for (i=1;i<=imx ; i++)
                   7245:     {
                   7246:       if (cens[i] == 1 && wav[i]>1)
                   7247:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   7248:       
                   7249:       if (cens[i] == 0 && wav[i]>1)
                   7250:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   7251:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   7252:       
                   7253:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   7254:       if (wav[i] > 1 ) { /* ??? */
                   7255:        L=L+A*weight[i];
                   7256:        /*      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]);*/
                   7257:       }
                   7258:     }
                   7259: 
                   7260:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   7261:  
                   7262:   return -2*L*num/sump;
                   7263: }
                   7264: 
1.136     brouard  7265: #ifdef GSL
                   7266: /******************* Gompertz_f Likelihood ******************************/
                   7267: double gompertz_f(const gsl_vector *v, void *params)
                   7268: { 
                   7269:   double A,B,LL=0.0,sump=0.,num=0.;
                   7270:   double *x= (double *) v->data;
                   7271:   int i,n=0; /* n is the size of the sample */
                   7272: 
                   7273:   for (i=0;i<=imx-1 ; i++) {
                   7274:     sump=sump+weight[i];
                   7275:     /*    sump=sump+1;*/
                   7276:     num=num+1;
                   7277:   }
                   7278:  
                   7279:  
                   7280:   /* for (i=0; i<=imx; i++) 
                   7281:      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]);*/
                   7282:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   7283:   for (i=1;i<=imx ; i++)
                   7284:     {
                   7285:       if (cens[i] == 1 && wav[i]>1)
                   7286:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   7287:       
                   7288:       if (cens[i] == 0 && wav[i]>1)
                   7289:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   7290:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   7291:       
                   7292:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   7293:       if (wav[i] > 1 ) { /* ??? */
                   7294:        LL=LL+A*weight[i];
                   7295:        /*      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]);*/
                   7296:       }
                   7297:     }
                   7298: 
                   7299:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   7300:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   7301:  
                   7302:   return -2*LL*num/sump;
                   7303: }
                   7304: #endif
                   7305: 
1.126     brouard  7306: /******************* Printing html file ***********/
1.201     brouard  7307: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  7308:                  int lastpass, int stepm, int weightopt, char model[],\
                   7309:                  int imx,  double p[],double **matcov,double agemortsup){
                   7310:   int i,k;
                   7311: 
                   7312:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   7313:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   7314:   for (i=1;i<=2;i++) 
                   7315:     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  7316:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  7317:   fprintf(fichtm,"</ul>");
                   7318: 
                   7319: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   7320: 
                   7321:  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>");
                   7322: 
                   7323:  for (k=agegomp;k<(agemortsup-2);k++) 
                   7324:    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]);
                   7325: 
                   7326:  
                   7327:   fflush(fichtm);
                   7328: }
                   7329: 
                   7330: /******************* Gnuplot file **************/
1.201     brouard  7331: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  7332: 
                   7333:   char dirfileres[132],optfileres[132];
1.164     brouard  7334: 
1.126     brouard  7335:   int ng;
                   7336: 
                   7337: 
                   7338:   /*#ifdef windows */
                   7339:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   7340:     /*#endif */
                   7341: 
                   7342: 
                   7343:   strcpy(dirfileres,optionfilefiname);
                   7344:   strcpy(optfileres,"vpl");
1.199     brouard  7345:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  7346:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  7347:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  7348:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  7349:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   7350: 
                   7351: } 
                   7352: 
1.136     brouard  7353: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   7354: {
1.126     brouard  7355: 
1.136     brouard  7356:   /*-------- data file ----------*/
                   7357:   FILE *fic;
                   7358:   char dummy[]="                         ";
1.223     brouard  7359:   int i=0, j=0, n=0, iv=0;
                   7360:   int lstra;
1.136     brouard  7361:   int linei, month, year,iout;
                   7362:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  7363:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  7364:   char *stratrunc;
1.223     brouard  7365: 
1.126     brouard  7366: 
                   7367: 
1.136     brouard  7368:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  7369:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   7370:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  7371:   }
1.126     brouard  7372: 
1.136     brouard  7373:   i=1;
                   7374:   linei=0;
                   7375:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   7376:     linei=linei+1;
                   7377:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   7378:       if(line[j] == '\t')
                   7379:        line[j] = ' ';
                   7380:     }
                   7381:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   7382:       ;
                   7383:     };
                   7384:     line[j+1]=0;  /* Trims blanks at end of line */
                   7385:     if(line[0]=='#'){
                   7386:       fprintf(ficlog,"Comment line\n%s\n",line);
                   7387:       printf("Comment line\n%s\n",line);
                   7388:       continue;
                   7389:     }
                   7390:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  7391:     strcpy(line, linetmp);
1.223     brouard  7392:     
                   7393:     /* Loops on waves */
                   7394:     for (j=maxwav;j>=1;j--){
                   7395:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
                   7396:                                cutv(stra, strb, line, ' '); 
                   7397:                                if(strb[0]=='.') { /* Missing value */
                   7398:                                        lval=-1;
                   7399:                                }else{
                   7400:                                        errno=0;
                   7401:                                        /* what_kind_of_number(strb); */
                   7402:                                        dval=strtod(strb,&endptr); 
                   7403:                                        /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   7404:                                        /* if(strb != endptr && *endptr == '\0') */
                   7405:                                        /*    dval=dlval; */
                   7406:                                        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   7407:                                        if( strb[0]=='\0' || (*endptr != '\0')){
                   7408:                                                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);
                   7409:                                                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);
                   7410:                                                return 1;
                   7411:                                        }
                   7412:                                        cotqvar[j][iv][i]=dval; 
                   7413:                                }
                   7414:                                strcpy(line,stra);
                   7415:       }/* end loop ntqv */
                   7416:                        
                   7417:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
                   7418:                                cutv(stra, strb, line, ' '); 
                   7419:                                if(strb[0]=='.') { /* Missing value */
                   7420:                                        lval=-1;
                   7421:                                }else{
                   7422:                                        errno=0;
                   7423:                                        lval=strtol(strb,&endptr,10); 
                   7424:                                        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   7425:                                        if( strb[0]=='\0' || (*endptr != '\0')){
                   7426:                                                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);
                   7427:                                                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);
                   7428:                                                return 1;
                   7429:                                        }
                   7430:                                }
                   7431:                                if(lval <-1 || lval >1){
                   7432:                                        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
                   7433:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   7434:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   7435:  For example, for multinomial values like 1, 2 and 3,\n                                                                        \
                   7436:  build V1=0 V2=0 for the reference value (1),\n                                                                                                        \
                   7437:         V1=1 V2=0 for (2) \n                                                                                                                                                                           \
                   7438:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   7439:  output of IMaCh is often meaningless.\n                                                                                                                               \
                   7440:  Exiting.\n",lval,linei, i,line,j);
                   7441:                                        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
                   7442:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   7443:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   7444:  For example, for multinomial values like 1, 2 and 3,\n                                                                        \
                   7445:  build V1=0 V2=0 for the reference value (1),\n                                                                                                        \
                   7446:         V1=1 V2=0 for (2) \n                                                                                                                                                                           \
                   7447:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   7448:  output of IMaCh is often meaningless.\n                               \
                   7449:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
                   7450:                                        return 1;
                   7451:                                }
                   7452:                                cotvar[j][iv][i]=(double)(lval);
                   7453:                                strcpy(line,stra);
                   7454:       }/* end loop ntv */
1.126     brouard  7455: 
1.223     brouard  7456:       /* Statuses  at wave */
1.137     brouard  7457:       cutv(stra, strb, line, ' '); 
1.223     brouard  7458:       if(strb[0]=='.') { /* Missing value */
                   7459:                                lval=-1;
1.136     brouard  7460:       }else{
1.223     brouard  7461:                                errno=0;
                   7462:                                lval=strtol(strb,&endptr,10); 
                   7463:                                /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   7464:                                if( strb[0]=='\0' || (*endptr != '\0')){
                   7465:                                        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);
                   7466:                                        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);
                   7467:                                        return 1;
                   7468:                                }
1.136     brouard  7469:       }
1.223     brouard  7470:      
1.136     brouard  7471:       s[j][i]=lval;
1.223     brouard  7472: 
                   7473:       /* Date of Interview */
1.136     brouard  7474:       strcpy(line,stra);
                   7475:       cutv(stra, strb,line,' ');
1.169     brouard  7476:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  7477:       }
1.169     brouard  7478:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.223     brouard  7479:                                month=99;
                   7480:                                year=9999;
1.136     brouard  7481:       }else{
1.223     brouard  7482:                                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);
                   7483:                                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);
                   7484:                                return 1;
1.136     brouard  7485:       }
                   7486:       anint[j][i]= (double) year; 
                   7487:       mint[j][i]= (double)month; 
                   7488:       strcpy(line,stra);
1.223     brouard  7489:     } /* End loop on waves */
                   7490: 
                   7491:     /* Date of death */
1.136     brouard  7492:     cutv(stra, strb,line,' '); 
1.169     brouard  7493:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  7494:     }
1.169     brouard  7495:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  7496:       month=99;
                   7497:       year=9999;
                   7498:     }else{
1.141     brouard  7499:       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.223     brouard  7500:                        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);
                   7501:                        return 1;
1.136     brouard  7502:     }
                   7503:     andc[i]=(double) year; 
                   7504:     moisdc[i]=(double) month; 
                   7505:     strcpy(line,stra);
                   7506:     
1.223     brouard  7507:     /* Date of birth */
1.136     brouard  7508:     cutv(stra, strb,line,' '); 
1.169     brouard  7509:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  7510:     }
1.169     brouard  7511:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  7512:       month=99;
                   7513:       year=9999;
                   7514:     }else{
1.141     brouard  7515:       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);
                   7516:       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.223     brouard  7517:                        return 1;
1.136     brouard  7518:     }
                   7519:     if (year==9999) {
1.141     brouard  7520:       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);
                   7521:       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.223     brouard  7522:                        return 1;
1.126     brouard  7523: 
1.136     brouard  7524:     }
                   7525:     annais[i]=(double)(year);
                   7526:     moisnais[i]=(double)(month); 
                   7527:     strcpy(line,stra);
1.223     brouard  7528: 
                   7529:     /* Sample weight */
1.136     brouard  7530:     cutv(stra, strb,line,' '); 
                   7531:     errno=0;
                   7532:     dval=strtod(strb,&endptr); 
                   7533:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  7534:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   7535:       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  7536:       fflush(ficlog);
                   7537:       return 1;
                   7538:     }
                   7539:     weight[i]=dval; 
                   7540:     strcpy(line,stra);
1.223     brouard  7541: 
                   7542:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   7543:       cutv(stra, strb, line, ' '); 
                   7544:       if(strb[0]=='.') { /* Missing value */
                   7545:                                lval=-1;
                   7546:       }else{
                   7547:                                errno=0;
                   7548:                                /* what_kind_of_number(strb); */
                   7549:                                dval=strtod(strb,&endptr);
                   7550:                                /* if(strb != endptr && *endptr == '\0') */
                   7551:                                /*   dval=dlval; */
                   7552:                                /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   7553:                                if( strb[0]=='\0' || (*endptr != '\0')){
                   7554:                                        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);
                   7555:                                        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);
                   7556:                                        return 1;
                   7557:                                }
                   7558:                                coqvar[iv][i]=dval; 
                   7559:       }
                   7560:       strcpy(line,stra);
                   7561:     }/* end loop nqv */
1.136     brouard  7562:     
1.223     brouard  7563:     /* Covariate values */
1.136     brouard  7564:     for (j=ncovcol;j>=1;j--){
                   7565:       cutv(stra, strb,line,' '); 
1.223     brouard  7566:       if(strb[0]=='.') { /* Missing covariate value */
                   7567:                                lval=-1;
1.136     brouard  7568:       }else{
1.223     brouard  7569:                                errno=0;
                   7570:                                lval=strtol(strb,&endptr,10); 
                   7571:                                if( strb[0]=='\0' || (*endptr != '\0')){
                   7572:                                        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);
                   7573:                                        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);
                   7574:                                        return 1;
                   7575:                                }
1.136     brouard  7576:       }
                   7577:       if(lval <-1 || lval >1){
1.223     brouard  7578:                                printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  7579:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   7580:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   7581:  For example, for multinomial values like 1, 2 and 3,\n \
                   7582:  build V1=0 V2=0 for the reference value (1),\n \
                   7583:         V1=1 V2=0 for (2) \n \
                   7584:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   7585:  output of IMaCh is often meaningless.\n \
                   7586:  Exiting.\n",lval,linei, i,line,j);
1.223     brouard  7587:                                fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  7588:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   7589:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   7590:  For example, for multinomial values like 1, 2 and 3,\n \
                   7591:  build V1=0 V2=0 for the reference value (1),\n \
                   7592:         V1=1 V2=0 for (2) \n \
                   7593:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   7594:  output of IMaCh is often meaningless.\n \
                   7595:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.223     brouard  7596:                                return 1;
1.136     brouard  7597:       }
                   7598:       covar[j][i]=(double)(lval);
                   7599:       strcpy(line,stra);
                   7600:     }  
                   7601:     lstra=strlen(stra);
                   7602:      
                   7603:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   7604:       stratrunc = &(stra[lstra-9]);
                   7605:       num[i]=atol(stratrunc);
                   7606:     }
                   7607:     else
                   7608:       num[i]=atol(stra);
                   7609:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   7610:       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;}*/
                   7611:     
                   7612:     i=i+1;
                   7613:   } /* End loop reading  data */
1.126     brouard  7614: 
1.136     brouard  7615:   *imax=i-1; /* Number of individuals */
                   7616:   fclose(fic);
                   7617:  
                   7618:   return (0);
1.164     brouard  7619:   /* endread: */
1.223     brouard  7620:        printf("Exiting readdata: ");
                   7621:        fclose(fic);
                   7622:        return (1);
                   7623: }
1.126     brouard  7624: 
1.145     brouard  7625: void removespace(char *str) {
                   7626:   char *p1 = str, *p2 = str;
                   7627:   do
                   7628:     while (*p2 == ' ')
                   7629:       p2++;
1.169     brouard  7630:   while (*p1++ == *p2++);
1.145     brouard  7631: }
                   7632: 
1.224   ! brouard  7633: int decodemodel ( char model[], int lastobs)
        !          7634:  /**< This routine decode the model and returns:
        !          7635:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
        !          7636:        * - nagesqr = 1 if age*age in the model, otherwise 0.
        !          7637:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
        !          7638:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
        !          7639:        * - cptcovage number of covariates with age*products =2
        !          7640:        * - cptcovs number of simple covariates
        !          7641:        * - 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
        !          7642:        *     which is a new column after the 9 (ncovcol) variables. 
        !          7643:        * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
        !          7644:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
        !          7645:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
        !          7646:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
        !          7647:        */
1.136     brouard  7648: {
1.145     brouard  7649:   int i, j, k, ks;
1.164     brouard  7650:   int  j1, k1, k2;
1.136     brouard  7651:   char modelsav[80];
1.145     brouard  7652:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  7653:   char *strpt;
1.136     brouard  7654: 
1.145     brouard  7655:   /*removespace(model);*/
1.136     brouard  7656:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  7657:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  7658:     if (strstr(model,"AGE") !=0){
1.192     brouard  7659:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   7660:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  7661:       return 1;
                   7662:     }
1.141     brouard  7663:     if (strstr(model,"v") !=0){
                   7664:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   7665:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   7666:       return 1;
                   7667:     }
1.187     brouard  7668:     strcpy(modelsav,model); 
                   7669:     if ((strpt=strstr(model,"age*age")) !=0){
                   7670:       printf(" strpt=%s, model=%s\n",strpt, model);
                   7671:       if(strpt != model){
1.224   ! brouard  7672:                                printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  7673:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  7674:  corresponding column of parameters.\n",model);
1.224   ! brouard  7675:                                fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  7676:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  7677:  corresponding column of parameters.\n",model); fflush(ficlog);
1.224   ! brouard  7678:                                return 1;
        !          7679:                        }
1.187     brouard  7680: 
                   7681:       nagesqr=1;
                   7682:       if (strstr(model,"+age*age") !=0)
1.224   ! brouard  7683:                                substrchaine(modelsav, model, "+age*age");
1.187     brouard  7684:       else if (strstr(model,"age*age+") !=0)
1.224   ! brouard  7685:                                substrchaine(modelsav, model, "age*age+");
1.187     brouard  7686:       else 
1.224   ! brouard  7687:                                substrchaine(modelsav, model, "age*age");
1.187     brouard  7688:     }else
                   7689:       nagesqr=0;
                   7690:     if (strlen(modelsav) >1){
                   7691:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   7692:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.224   ! brouard  7693:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.187     brouard  7694:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.224   ! brouard  7695:                                                                                 * cst, age and age*age 
        !          7696:                                                                                 * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
        !          7697:                        /* including age products which are counted in cptcovage.
        !          7698:                         * but the covariates which are products must be treated 
        !          7699:                         * separately: ncovn=4- 2=2 (V1+V3). */
1.187     brouard  7700:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   7701:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
                   7702: 
                   7703:     
                   7704:       /*   Design
                   7705:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   7706:        *  <          ncovcol=8                >
                   7707:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   7708:        *   k=  1    2      3       4     5       6      7        8
                   7709:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   7710:        *  covar[k,i], value of kth covariate if not including age for individual i:
1.224   ! brouard  7711:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
        !          7712:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  7713:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   7714:        *  Tage[++cptcovage]=k
                   7715:        *       if products, new covar are created after ncovcol with k1
                   7716:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   7717:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   7718:        *  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
                   7719:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   7720:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   7721:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   7722:        *  <          ncovcol=8                >
                   7723:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   7724:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   7725:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   7726:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   7727:        * p Tprod[1]@2={                         6, 5}
                   7728:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   7729:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   7730:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   7731:        *How to reorganize?
                   7732:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   7733:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   7734:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   7735:        * Struct []
                   7736:        */
1.145     brouard  7737: 
1.187     brouard  7738:       /* This loop fills the array Tvar from the string 'model'.*/
                   7739:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   7740:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   7741:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   7742:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   7743:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   7744:       /*       k=1 Tvar[1]=2 (from V2) */
                   7745:       /*       k=5 Tvar[5] */
                   7746:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  7747:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  7748:       /*       } */
1.198     brouard  7749:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  7750:       /*
                   7751:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
                   7752:       for(k=cptcovt; k>=1;k--) /**< Number of covariates */
1.145     brouard  7753:         Tvar[k]=0;
1.187     brouard  7754:       cptcovage=0;
                   7755:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
1.223     brouard  7756:                                cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
                   7757:                                                                                                                                                                 modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
                   7758:                                if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
                   7759:                                /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   7760:                                /*scanf("%d",i);*/
                   7761:                                if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   7762:                                        cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   7763:                                        if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   7764:                                                /* covar is not filled and then is empty */
                   7765:                                                cptcovprod--;
                   7766:                                                cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   7767:                                                Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
                   7768:                                                cptcovage++; /* Sums the number of covariates which include age as a product */
                   7769:                                                Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   7770:                                                /*printf("stre=%s ", stre);*/
                   7771:                                        } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   7772:                                                cptcovprod--;
                   7773:                                                cutl(stre,strb,strc,'V');
                   7774:                                                Tvar[k]=atoi(stre);
                   7775:                                                cptcovage++;
                   7776:                                                Tage[cptcovage]=k;
                   7777:                                        } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   7778:                                                /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   7779:                                                cptcovn++;
                   7780:                                                cptcovprodnoage++;k1++;
                   7781:                                                cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   7782:                                                Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
                   7783:                                                                                                                                         because this model-covariate is a construction we invent a new column
                   7784:                                                                                                                                         ncovcol + k1
                   7785:                                                                                                                                         If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   7786:                                                                                                                                         Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
                   7787:                                                cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   7788:                                                Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
                   7789:                                                Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   7790:                                                Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   7791:                                                k2=k2+2;
                   7792:                                                Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
                   7793:                                                Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
                   7794:                                                for (i=1; i<=lastobs;i++){
                   7795:                                                        /* Computes the new covariate which is a product of
                   7796:                                                                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   7797:                                                        covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   7798:                                                }
                   7799:                                        } /* End age is not in the model */
                   7800:                                } /* End if model includes a product */
                   7801:                                else { /* no more sum */
                   7802:                                        /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   7803:                                        /*  scanf("%d",i);*/
                   7804:                                        cutl(strd,strc,strb,'V');
                   7805:                                        ks++; /**< Number of simple covariates */
                   7806:                                        cptcovn++;
                   7807:                                        Tvar[k]=atoi(strd);
                   7808:                                }
                   7809:                                strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
                   7810:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
                   7811:                                        scanf("%d",i);*/
1.187     brouard  7812:       } /* end of loop + on total covariates */
                   7813:     } /* end if strlen(modelsave == 0) age*age might exist */
                   7814:   } /* end if strlen(model == 0) */
1.136     brouard  7815:   
                   7816:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   7817:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
                   7818: 
                   7819:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.224   ! brouard  7820:                 printf("cptcovprod=%d ", cptcovprod);
        !          7821:                 fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
1.136     brouard  7822: 
1.224   ! brouard  7823:                 scanf("%d ",i);*/
        !          7824: /* Dispatching in quantitative and time varying covariates */
1.136     brouard  7825: 
1.224   ! brouard  7826:        for(k=1, ncoveff=0, nqveff=0, ntveff=0, nqtveff=0;k<=cptcovn; k++){ /* or cptocvt */
        !          7827:                if (Tvar[k] <=ncovcol){
        !          7828:                        ncoveff++;
        !          7829:                }else if( Tvar[k] <=ncovcol+nqv){
        !          7830:                        nqveff++;
        !          7831:                }else if( Tvar[k] <=ncovcol+nqv+ntv){
        !          7832:                        ntveff++;
        !          7833:                }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
        !          7834:                        nqtveff++;
        !          7835:                }else
        !          7836:                        printf("Error in effective covariates \n");
        !          7837:        }
1.136     brouard  7838: 
1.137     brouard  7839:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  7840:   /*endread:*/
1.224   ! brouard  7841:        printf("Exiting decodemodel: ");
        !          7842:        return (1);
1.136     brouard  7843: }
                   7844: 
1.169     brouard  7845: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136     brouard  7846: {
                   7847:   int i, m;
1.218     brouard  7848:   int firstone=0;
                   7849:   
1.136     brouard  7850:   for (i=1; i<=imx; i++) {
                   7851:     for(m=2; (m<= maxwav); m++) {
                   7852:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   7853:        anint[m][i]=9999;
1.216     brouard  7854:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   7855:          s[m][i]=-1;
1.136     brouard  7856:       }
                   7857:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169     brouard  7858:        *nberr = *nberr + 1;
1.218     brouard  7859:        if(firstone == 0){
                   7860:          firstone=1;
                   7861:        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);
                   7862:        }
                   7863:        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  7864:        s[m][i]=-1;
                   7865:       }
                   7866:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  7867:        (*nberr)++;
1.136     brouard  7868:        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]); 
                   7869:        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]); 
                   7870:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   7871:       }
                   7872:     }
                   7873:   }
                   7874: 
                   7875:   for (i=1; i<=imx; i++)  {
                   7876:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   7877:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  7878:       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  7879:        if (s[m][i] >= nlstate+1) {
1.169     brouard  7880:          if(agedc[i]>0){
                   7881:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  7882:              agev[m][i]=agedc[i];
1.214     brouard  7883:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  7884:            }else {
1.136     brouard  7885:              if ((int)andc[i]!=9999){
                   7886:                nbwarn++;
                   7887:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   7888:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   7889:                agev[m][i]=-1;
                   7890:              }
                   7891:            }
1.169     brouard  7892:          } /* agedc > 0 */
1.214     brouard  7893:        } /* end if */
1.136     brouard  7894:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   7895:                                 years but with the precision of a month */
                   7896:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   7897:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   7898:            agev[m][i]=1;
                   7899:          else if(agev[m][i] < *agemin){ 
                   7900:            *agemin=agev[m][i];
                   7901:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   7902:          }
                   7903:          else if(agev[m][i] >*agemax){
                   7904:            *agemax=agev[m][i];
1.156     brouard  7905:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  7906:          }
                   7907:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   7908:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  7909:        } /* en if 9*/
1.136     brouard  7910:        else { /* =9 */
1.214     brouard  7911:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  7912:          agev[m][i]=1;
                   7913:          s[m][i]=-1;
                   7914:        }
                   7915:       }
1.214     brouard  7916:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  7917:        agev[m][i]=1;
1.214     brouard  7918:       else{
                   7919:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   7920:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   7921:        agev[m][i]=0;
                   7922:       }
                   7923:     } /* End for lastpass */
                   7924:   }
1.136     brouard  7925:     
                   7926:   for (i=1; i<=imx; i++)  {
                   7927:     for(m=firstpass; (m<=lastpass); m++){
                   7928:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  7929:        (*nberr)++;
1.136     brouard  7930:        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);     
                   7931:        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);     
                   7932:        return 1;
                   7933:       }
                   7934:     }
                   7935:   }
                   7936: 
                   7937:   /*for (i=1; i<=imx; i++){
                   7938:   for (m=firstpass; (m<lastpass); m++){
                   7939:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   7940: }
                   7941: 
                   7942: }*/
                   7943: 
                   7944: 
1.139     brouard  7945:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   7946:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  7947: 
                   7948:   return (0);
1.164     brouard  7949:  /* endread:*/
1.136     brouard  7950:     printf("Exiting calandcheckages: ");
                   7951:     return (1);
                   7952: }
                   7953: 
1.172     brouard  7954: #if defined(_MSC_VER)
                   7955: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   7956: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   7957: //#include "stdafx.h"
                   7958: //#include <stdio.h>
                   7959: //#include <tchar.h>
                   7960: //#include <windows.h>
                   7961: //#include <iostream>
                   7962: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   7963: 
                   7964: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   7965: 
                   7966: BOOL IsWow64()
                   7967: {
                   7968:        BOOL bIsWow64 = FALSE;
                   7969: 
                   7970:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   7971:        //  (HANDLE, PBOOL);
                   7972: 
                   7973:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   7974: 
                   7975:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   7976:        const char funcName[] = "IsWow64Process";
                   7977:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   7978:                GetProcAddress(module, funcName);
                   7979: 
                   7980:        if (NULL != fnIsWow64Process)
                   7981:        {
                   7982:                if (!fnIsWow64Process(GetCurrentProcess(),
                   7983:                        &bIsWow64))
                   7984:                        //throw std::exception("Unknown error");
                   7985:                        printf("Unknown error\n");
                   7986:        }
                   7987:        return bIsWow64 != FALSE;
                   7988: }
                   7989: #endif
1.177     brouard  7990: 
1.191     brouard  7991: void syscompilerinfo(int logged)
1.167     brouard  7992:  {
                   7993:    /* #include "syscompilerinfo.h"*/
1.185     brouard  7994:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   7995:    /* /GS /W3 /Gy
                   7996:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   7997:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   7998:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  7999:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   8000:    */ 
                   8001:    /* 64 bits */
1.185     brouard  8002:    /*
                   8003:      /GS /W3 /Gy
                   8004:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   8005:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   8006:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   8007:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   8008:    /* Optimization are useless and O3 is slower than O2 */
                   8009:    /*
                   8010:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   8011:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   8012:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   8013:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   8014:    */
1.186     brouard  8015:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  8016:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   8017:       /PDB:"visual studio
                   8018:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   8019:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   8020:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   8021:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   8022:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   8023:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   8024:       uiAccess='false'"
                   8025:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   8026:       /NOLOGO /TLBID:1
                   8027:    */
1.177     brouard  8028: #if defined __INTEL_COMPILER
1.178     brouard  8029: #if defined(__GNUC__)
                   8030:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   8031: #endif
1.177     brouard  8032: #elif defined(__GNUC__) 
1.179     brouard  8033: #ifndef  __APPLE__
1.174     brouard  8034: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  8035: #endif
1.177     brouard  8036:    struct utsname sysInfo;
1.178     brouard  8037:    int cross = CROSS;
                   8038:    if (cross){
                   8039:           printf("Cross-");
1.191     brouard  8040:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  8041:    }
1.174     brouard  8042: #endif
                   8043: 
1.171     brouard  8044: #include <stdint.h>
1.178     brouard  8045: 
1.191     brouard  8046:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  8047: #if defined(__clang__)
1.191     brouard  8048:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  8049: #endif
                   8050: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  8051:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  8052: #endif
                   8053: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  8054:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  8055: #endif
                   8056: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  8057:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  8058: #endif
                   8059: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  8060:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  8061: #endif
                   8062: #if defined(_MSC_VER)
1.191     brouard  8063:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  8064: #endif
                   8065: #if defined(__PGI)
1.191     brouard  8066:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  8067: #endif
                   8068: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  8069:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  8070: #endif
1.191     brouard  8071:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  8072:    
1.167     brouard  8073: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   8074: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   8075:     // Windows (x64 and x86)
1.191     brouard  8076:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  8077: #elif __unix__ // all unices, not all compilers
                   8078:     // Unix
1.191     brouard  8079:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  8080: #elif __linux__
                   8081:     // linux
1.191     brouard  8082:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  8083: #elif __APPLE__
1.174     brouard  8084:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  8085:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  8086: #endif
                   8087: 
                   8088: /*  __MINGW32__          */
                   8089: /*  __CYGWIN__  */
                   8090: /* __MINGW64__  */
                   8091: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   8092: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   8093: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   8094: /* _WIN64  // Defined for applications for Win64. */
                   8095: /* _M_X64 // Defined for compilations that target x64 processors. */
                   8096: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  8097: 
1.167     brouard  8098: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  8099:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  8100: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  8101:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  8102: #else
1.191     brouard  8103:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  8104: #endif
                   8105: 
1.169     brouard  8106: #if defined(__GNUC__)
                   8107: # if defined(__GNUC_PATCHLEVEL__)
                   8108: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   8109:                             + __GNUC_MINOR__ * 100 \
                   8110:                             + __GNUC_PATCHLEVEL__)
                   8111: # else
                   8112: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   8113:                             + __GNUC_MINOR__ * 100)
                   8114: # endif
1.174     brouard  8115:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  8116:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  8117: 
                   8118:    if (uname(&sysInfo) != -1) {
                   8119:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  8120:         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  8121:    }
                   8122:    else
                   8123:       perror("uname() error");
1.179     brouard  8124:    //#ifndef __INTEL_COMPILER 
                   8125: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  8126:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  8127:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  8128: #endif
1.169     brouard  8129: #endif
1.172     brouard  8130: 
                   8131:    //   void main()
                   8132:    //   {
1.169     brouard  8133: #if defined(_MSC_VER)
1.174     brouard  8134:    if (IsWow64()){
1.191     brouard  8135:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   8136:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  8137:    }
                   8138:    else{
1.191     brouard  8139:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   8140:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  8141:    }
1.172     brouard  8142:    //     printf("\nPress Enter to continue...");
                   8143:    //     getchar();
                   8144:    //   }
                   8145: 
1.169     brouard  8146: #endif
                   8147:    
1.167     brouard  8148: 
1.219     brouard  8149: }
1.136     brouard  8150: 
1.219     brouard  8151: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.180     brouard  8152:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
                   8153:   int i, j, k, i1 ;
1.202     brouard  8154:   /* double ftolpl = 1.e-10; */
1.180     brouard  8155:   double age, agebase, agelim;
1.203     brouard  8156:   double tot;
1.180     brouard  8157: 
1.202     brouard  8158:   strcpy(filerespl,"PL_");
                   8159:   strcat(filerespl,fileresu);
                   8160:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
                   8161:     printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   8162:     fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   8163:   }
                   8164:   printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   8165:   fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   8166:   pstamp(ficrespl);
1.203     brouard  8167:   fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  8168:   fprintf(ficrespl,"#Age ");
                   8169:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   8170:   fprintf(ficrespl,"\n");
1.180     brouard  8171:   
1.219     brouard  8172:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  8173: 
1.219     brouard  8174:   agebase=ageminpar;
                   8175:   agelim=agemaxpar;
1.180     brouard  8176: 
1.224   ! brouard  8177:   i1=pow(2,ncoveff);
1.219     brouard  8178:   if (cptcovn < 1){i1=1;}
1.180     brouard  8179: 
1.220     brouard  8180:   for(k=1; k<=i1;k++){
                   8181:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
1.180     brouard  8182:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
1.219     brouard  8183:     //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
1.220     brouard  8184:     /* k=k+1; */
1.219     brouard  8185:     /* to clean */
                   8186:     //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   8187:     fprintf(ficrespl,"#******");
                   8188:     printf("#******");
                   8189:     fprintf(ficlog,"#******");
1.224   ! brouard  8190:     for(j=1;j<=nqveff;j++) {
1.219     brouard  8191:       fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8192:       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8193:       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8194:     }
                   8195:     fprintf(ficrespl,"******\n");
                   8196:     printf("******\n");
                   8197:     fprintf(ficlog,"******\n");
1.220     brouard  8198:                if(invalidvarcomb[k]){
                   8199:                                                printf("\nCombination (%d) ignored because no cases \n",k); 
                   8200:                                                fprintf(ficrespl,"#Combination (%d) ignored because no cases \n",k); 
                   8201:                                                fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   8202:                                                continue;
                   8203:                }
1.219     brouard  8204: 
                   8205:     fprintf(ficrespl,"#Age ");
1.224   ! brouard  8206:     for(j=1;j<=nqveff;j++) {
1.219     brouard  8207:       fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8208:     }
                   8209:     for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   8210:     fprintf(ficrespl,"Total Years_to_converge\n");
                   8211:        
                   8212:     for (age=agebase; age<=agelim; age++){
                   8213:       /* for (age=agebase; age<=agebase; age++){ */
                   8214:       prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k);
                   8215:       fprintf(ficrespl,"%.0f ",age );
1.224   ! brouard  8216:       for(j=1;j<=nqveff;j++)
1.220     brouard  8217:                                                        fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.219     brouard  8218:       tot=0.;
                   8219:       for(i=1; i<=nlstate;i++){
1.220     brouard  8220:                                                        tot +=  prlim[i][i];
                   8221:                                                        fprintf(ficrespl," %.5f", prlim[i][i]);
1.219     brouard  8222:       }
                   8223:       fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   8224:     } /* Age */
                   8225:     /* was end of cptcod */
                   8226:   } /* cptcov */
                   8227:   return 0;
1.180     brouard  8228: }
                   8229: 
1.218     brouard  8230: 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){
                   8231:        /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   8232:        
                   8233:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   8234:    * at any age between ageminpar and agemaxpar
                   8235:         */
1.217     brouard  8236:   int i, j, k, i1 ;
                   8237:   /* double ftolpl = 1.e-10; */
                   8238:   double age, agebase, agelim;
                   8239:   double tot;
1.218     brouard  8240:   /* double ***mobaverage; */
                   8241:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  8242: 
                   8243:   strcpy(fileresplb,"PLB_");
                   8244:   strcat(fileresplb,fileresu);
                   8245:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
                   8246:     printf("Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
                   8247:     fprintf(ficlog,"Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
                   8248:   }
                   8249:   printf("Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
                   8250:   fprintf(ficlog,"Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
                   8251:   pstamp(ficresplb);
                   8252:   fprintf(ficresplb,"# Period (stable) back prevalence. Precision given by ftolpl=%g \n", ftolpl);
                   8253:   fprintf(ficresplb,"#Age ");
                   8254:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   8255:   fprintf(ficresplb,"\n");
                   8256:   
1.218     brouard  8257:   
                   8258:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   8259:   
                   8260:   agebase=ageminpar;
                   8261:   agelim=agemaxpar;
                   8262:   
                   8263:   
1.224   ! brouard  8264:   i1=pow(2,nqveff);
1.218     brouard  8265:   if (cptcovn < 1){i1=1;}
1.220     brouard  8266: 
                   8267:        for(k=1; k<=i1;k++){ 
                   8268:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
1.217     brouard  8269:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
1.218     brouard  8270:     //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
1.220     brouard  8271:     /* k=k+1; */
1.218     brouard  8272:     /* to clean */
                   8273:     //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   8274:     fprintf(ficresplb,"#******");
                   8275:     printf("#******");
                   8276:     fprintf(ficlog,"#******");
1.224   ! brouard  8277:     for(j=1;j<=nqveff;j++) {
1.218     brouard  8278:       fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8279:       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8280:       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8281:     }
                   8282:     fprintf(ficresplb,"******\n");
                   8283:     printf("******\n");
                   8284:     fprintf(ficlog,"******\n");
1.220     brouard  8285:                if(invalidvarcomb[k]){
                   8286:                                                printf("\nCombination (%d) ignored because no cases \n",k); 
                   8287:                                                fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   8288:                                                fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   8289:                                                continue;
                   8290:                }
1.218     brouard  8291:     
                   8292:     fprintf(ficresplb,"#Age ");
1.224   ! brouard  8293:     for(j=1;j<=nqveff;j++) {
1.218     brouard  8294:       fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8295:     }
                   8296:     for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   8297:     fprintf(ficresplb,"Total Years_to_converge\n");
                   8298:     
                   8299:     
                   8300:     for (age=agebase; age<=agelim; age++){
                   8301:       /* for (age=agebase; age<=agebase; age++){ */
                   8302:       if(mobilavproj > 0){
                   8303:        /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   8304:        /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.219     brouard  8305:                                bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k);
1.218     brouard  8306:       }else if (mobilavproj == 0){
1.219     brouard  8307:                                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);
                   8308:                                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);
                   8309:                                exit(1);
1.218     brouard  8310:       }else{
1.219     brouard  8311:                                /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   8312:                                bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k);
1.218     brouard  8313:       }
                   8314:       fprintf(ficresplb,"%.0f ",age );
1.224   ! brouard  8315:       for(j=1;j<=nqveff;j++)
1.219     brouard  8316:                                fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.218     brouard  8317:       tot=0.;
                   8318:       for(i=1; i<=nlstate;i++){
1.219     brouard  8319:                                tot +=  bprlim[i][i];
                   8320:                                fprintf(ficresplb," %.5f", bprlim[i][i]);
1.218     brouard  8321:       }
                   8322:       fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   8323:     } /* Age */
                   8324:     /* was end of cptcod */
                   8325:   } /* cptcov */
                   8326:   
                   8327:   /* hBijx(p, bage, fage); */
                   8328:   /* fclose(ficrespijb); */
                   8329:   
                   8330:   return 0;
1.217     brouard  8331: }
1.218     brouard  8332:  
1.180     brouard  8333: int hPijx(double *p, int bage, int fage){
                   8334:     /*------------- h Pij x at various ages ------------*/
                   8335: 
                   8336:   int stepsize;
                   8337:   int agelim;
                   8338:   int hstepm;
                   8339:   int nhstepm;
                   8340:   int h, i, i1, j, k;
                   8341: 
                   8342:   double agedeb;
                   8343:   double ***p3mat;
                   8344: 
1.201     brouard  8345:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  8346:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   8347:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   8348:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   8349:     }
                   8350:     printf("Computing pij: result on file '%s' \n", filerespij);
                   8351:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   8352:   
                   8353:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   8354:     /*if (stepm<=24) stepsize=2;*/
                   8355: 
                   8356:     agelim=AGESUP;
                   8357:     hstepm=stepsize*YEARM; /* Every year of age */
                   8358:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
1.218     brouard  8359:                
1.180     brouard  8360:     /* hstepm=1;   aff par mois*/
                   8361:     pstamp(ficrespij);
                   8362:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
1.224   ! brouard  8363:     i1= pow(2,nqveff);
1.218     brouard  8364:                /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   8365:                /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   8366:                /*      k=k+1;  */
1.224   ! brouard  8367:     for (k=1; k <= (int) pow(2,nqveff); k++){
1.183     brouard  8368:       fprintf(ficrespij,"\n#****** ");
1.224   ! brouard  8369:       for(j=1;j<=nqveff;j++) 
1.198     brouard  8370:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.183     brouard  8371:       fprintf(ficrespij,"******\n");
                   8372:       
                   8373:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   8374:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   8375:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   8376:        
                   8377:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  8378:        
1.183     brouard  8379:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8380:        oldm=oldms;savm=savms;
                   8381:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   8382:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   8383:        for(i=1; i<=nlstate;i++)
                   8384:          for(j=1; j<=nlstate+ndeath;j++)
                   8385:            fprintf(ficrespij," %1d-%1d",i,j);
                   8386:        fprintf(ficrespij,"\n");
                   8387:        for (h=0; h<=nhstepm; h++){
                   8388:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   8389:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  8390:          for(i=1; i<=nlstate;i++)
                   8391:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  8392:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  8393:          fprintf(ficrespij,"\n");
                   8394:        }
1.183     brouard  8395:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8396:        fprintf(ficrespij,"\n");
                   8397:       }
1.180     brouard  8398:       /*}*/
                   8399:     }
1.218     brouard  8400:     return 0;
1.180     brouard  8401: }
1.218     brouard  8402:  
                   8403:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  8404:     /*------------- h Bij x at various ages ------------*/
                   8405: 
                   8406:   int stepsize;
1.218     brouard  8407:   /* int agelim; */
                   8408:        int ageminl;
1.217     brouard  8409:   int hstepm;
                   8410:   int nhstepm;
                   8411:   int h, i, i1, j, k;
1.218     brouard  8412:        
1.217     brouard  8413:   double agedeb;
                   8414:   double ***p3mat;
1.218     brouard  8415:        
                   8416:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   8417:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   8418:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   8419:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   8420:   }
                   8421:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   8422:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   8423:   
                   8424:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   8425:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  8426:   
1.218     brouard  8427:   /* agelim=AGESUP; */
                   8428:   ageminl=30;
                   8429:   hstepm=stepsize*YEARM; /* Every year of age */
                   8430:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   8431:   
                   8432:   /* hstepm=1;   aff par mois*/
                   8433:   pstamp(ficrespijb);
                   8434:   fprintf(ficrespijb,"#****** h Pij x Back Probability to be in state i at age x-h being in j at x ");
1.224   ! brouard  8435:   i1= pow(2,nqveff);
1.218     brouard  8436:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   8437:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   8438:   /*   k=k+1;  */
1.224   ! brouard  8439:   for (k=1; k <= (int) pow(2,nqveff); k++){
1.218     brouard  8440:     fprintf(ficrespijb,"\n#****** ");
1.224   ! brouard  8441:     for(j=1;j<=nqveff;j++)
1.218     brouard  8442:       fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8443:     fprintf(ficrespijb,"******\n");
1.222     brouard  8444:     if(invalidvarcomb[k]){
                   8445:       fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   8446:       continue;
                   8447:     }
1.218     brouard  8448:     
                   8449:     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   8450:     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   8451:       /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   8452:       nhstepm=(int) rint((agedeb-ageminl)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
                   8453:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 */
                   8454:       
                   8455:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   8456:       
                   8457:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8458:       /* oldm=oldms;savm=savms; */
                   8459:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   8460:       hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k);
                   8461:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
                   8462:       fprintf(ficrespijb,"# Cov Agex agex-h hpijx with i,j=");
                   8463:       for(i=1; i<=nlstate;i++)
                   8464:        for(j=1; j<=nlstate+ndeath;j++)
                   8465:          fprintf(ficrespijb," %1d-%1d",i,j);
                   8466:       fprintf(ficrespijb,"\n");
                   8467:       for (h=0; h<=nhstepm; h++){
                   8468:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   8469:        fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   8470:        /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
1.217     brouard  8471:        for(i=1; i<=nlstate;i++)
                   8472:          for(j=1; j<=nlstate+ndeath;j++)
1.218     brouard  8473:            fprintf(ficrespijb," %.5f", p3mat[i][j][h]);
1.217     brouard  8474:        fprintf(ficrespijb,"\n");
                   8475:       }
1.218     brouard  8476:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8477:       fprintf(ficrespijb,"\n");
1.217     brouard  8478:     }
1.218     brouard  8479:     /*}*/
                   8480:   }
                   8481:   return 0;
                   8482:  } /*  hBijx */
1.217     brouard  8483: 
1.180     brouard  8484: 
1.136     brouard  8485: /***********************************************/
                   8486: /**************** Main Program *****************/
                   8487: /***********************************************/
                   8488: 
                   8489: int main(int argc, char *argv[])
                   8490: {
                   8491: #ifdef GSL
                   8492:   const gsl_multimin_fminimizer_type *T;
                   8493:   size_t iteri = 0, it;
                   8494:   int rval = GSL_CONTINUE;
                   8495:   int status = GSL_SUCCESS;
                   8496:   double ssval;
                   8497: #endif
                   8498:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164     brouard  8499:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
1.209     brouard  8500:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  8501:   int jj, ll, li, lj, lk;
1.136     brouard  8502:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  8503:   int num_filled;
1.136     brouard  8504:   int itimes;
                   8505:   int NDIM=2;
                   8506:   int vpopbased=0;
                   8507: 
1.164     brouard  8508:   char ca[32], cb[32];
1.136     brouard  8509:   /*  FILE *fichtm; *//* Html File */
                   8510:   /* FILE *ficgp;*/ /*Gnuplot File */
                   8511:   struct stat info;
1.191     brouard  8512:   double agedeb=0.;
1.194     brouard  8513: 
                   8514:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  8515:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  8516: 
1.165     brouard  8517:   double fret;
1.191     brouard  8518:   double dum=0.; /* Dummy variable */
1.136     brouard  8519:   double ***p3mat;
1.218     brouard  8520:   /* double ***mobaverage; */
1.164     brouard  8521: 
                   8522:   char line[MAXLINE];
1.197     brouard  8523:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   8524: 
                   8525:   char model[MAXLINE], modeltemp[MAXLINE];
1.136     brouard  8526:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  8527:   char *tok, *val; /* pathtot */
1.136     brouard  8528:   int firstobs=1, lastobs=10;
1.195     brouard  8529:   int c,  h , cpt, c2;
1.191     brouard  8530:   int jl=0;
                   8531:   int i1, j1, jk, stepsize=0;
1.194     brouard  8532:   int count=0;
                   8533: 
1.164     brouard  8534:   int *tab; 
1.136     brouard  8535:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.217     brouard  8536:   int backcast=0;
1.136     brouard  8537:   int mobilav=0,popforecast=0;
1.191     brouard  8538:   int hstepm=0, nhstepm=0;
1.136     brouard  8539:   int agemortsup;
                   8540:   float  sumlpop=0.;
                   8541:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   8542:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   8543: 
1.191     brouard  8544:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  8545:   double ftolpl=FTOL;
                   8546:   double **prlim;
1.217     brouard  8547:   double **bprlim;
1.136     brouard  8548:   double ***param; /* Matrix of parameters */
                   8549:   double  *p;
                   8550:   double **matcov; /* Matrix of covariance */
1.203     brouard  8551:   double **hess; /* Hessian matrix */
1.136     brouard  8552:   double ***delti3; /* Scale */
                   8553:   double *delti; /* Scale */
                   8554:   double ***eij, ***vareij;
                   8555:   double **varpl; /* Variances of prevalence limits by age */
                   8556:   double *epj, vepp;
1.164     brouard  8557: 
1.136     brouard  8558:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
1.217     brouard  8559:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000;
                   8560: 
1.136     brouard  8561:   double **ximort;
1.145     brouard  8562:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  8563:   int *dcwave;
                   8564: 
1.164     brouard  8565:   char z[1]="c";
1.136     brouard  8566: 
                   8567:   /*char  *strt;*/
                   8568:   char strtend[80];
1.126     brouard  8569: 
1.164     brouard  8570: 
1.126     brouard  8571: /*   setlocale (LC_ALL, ""); */
                   8572: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   8573: /*   textdomain (PACKAGE); */
                   8574: /*   setlocale (LC_CTYPE, ""); */
                   8575: /*   setlocale (LC_MESSAGES, ""); */
                   8576: 
                   8577:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  8578:   rstart_time = time(NULL);  
                   8579:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   8580:   start_time = *localtime(&rstart_time);
1.126     brouard  8581:   curr_time=start_time;
1.157     brouard  8582:   /*tml = *localtime(&start_time.tm_sec);*/
                   8583:   /* strcpy(strstart,asctime(&tml)); */
                   8584:   strcpy(strstart,asctime(&start_time));
1.126     brouard  8585: 
                   8586: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  8587: /*  tp.tm_sec = tp.tm_sec +86400; */
                   8588: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  8589: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   8590: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   8591: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  8592: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  8593: /*   strt=asctime(&tmg); */
                   8594: /*   printf("Time(after) =%s",strstart);  */
                   8595: /*  (void) time (&time_value);
                   8596: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   8597: *  tm = *localtime(&time_value);
                   8598: *  strstart=asctime(&tm);
                   8599: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   8600: */
                   8601: 
                   8602:   nberr=0; /* Number of errors and warnings */
                   8603:   nbwarn=0;
1.184     brouard  8604: #ifdef WIN32
                   8605:   _getcwd(pathcd, size);
                   8606: #else
1.126     brouard  8607:   getcwd(pathcd, size);
1.184     brouard  8608: #endif
1.191     brouard  8609:   syscompilerinfo(0);
1.196     brouard  8610:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  8611:   if(argc <=1){
                   8612:     printf("\nEnter the parameter file name: ");
1.205     brouard  8613:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   8614:       printf("ERROR Empty parameter file name\n");
                   8615:       goto end;
                   8616:     }
1.126     brouard  8617:     i=strlen(pathr);
                   8618:     if(pathr[i-1]=='\n')
                   8619:       pathr[i-1]='\0';
1.156     brouard  8620:     i=strlen(pathr);
1.205     brouard  8621:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  8622:       pathr[i-1]='\0';
1.205     brouard  8623:     }
                   8624:     i=strlen(pathr);
                   8625:     if( i==0 ){
                   8626:       printf("ERROR Empty parameter file name\n");
                   8627:       goto end;
                   8628:     }
                   8629:     for (tok = pathr; tok != NULL; ){
1.126     brouard  8630:       printf("Pathr |%s|\n",pathr);
                   8631:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   8632:       printf("val= |%s| pathr=%s\n",val,pathr);
                   8633:       strcpy (pathtot, val);
                   8634:       if(pathr[0] == '\0') break; /* Dirty */
                   8635:     }
                   8636:   }
                   8637:   else{
                   8638:     strcpy(pathtot,argv[1]);
                   8639:   }
                   8640:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   8641:   /*cygwin_split_path(pathtot,path,optionfile);
                   8642:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   8643:   /* cutv(path,optionfile,pathtot,'\\');*/
                   8644: 
                   8645:   /* Split argv[0], imach program to get pathimach */
                   8646:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   8647:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   8648:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   8649:  /*   strcpy(pathimach,argv[0]); */
                   8650:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   8651:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   8652:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  8653: #ifdef WIN32
                   8654:   _chdir(path); /* Can be a relative path */
                   8655:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   8656: #else
1.126     brouard  8657:   chdir(path); /* Can be a relative path */
1.184     brouard  8658:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   8659: #endif
                   8660:   printf("Current directory %s!\n",pathcd);
1.126     brouard  8661:   strcpy(command,"mkdir ");
                   8662:   strcat(command,optionfilefiname);
                   8663:   if((outcmd=system(command)) != 0){
1.169     brouard  8664:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  8665:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   8666:     /* fclose(ficlog); */
                   8667: /*     exit(1); */
                   8668:   }
                   8669: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   8670: /*     perror("mkdir"); */
                   8671: /*   } */
                   8672: 
                   8673:   /*-------- arguments in the command line --------*/
                   8674: 
1.186     brouard  8675:   /* Main Log file */
1.126     brouard  8676:   strcat(filelog, optionfilefiname);
                   8677:   strcat(filelog,".log");    /* */
                   8678:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   8679:     printf("Problem with logfile %s\n",filelog);
                   8680:     goto end;
                   8681:   }
                   8682:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  8683:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  8684:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   8685:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   8686:  path=%s \n\
                   8687:  optionfile=%s\n\
                   8688:  optionfilext=%s\n\
1.156     brouard  8689:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  8690: 
1.197     brouard  8691:   syscompilerinfo(1);
1.167     brouard  8692: 
1.126     brouard  8693:   printf("Local time (at start):%s",strstart);
                   8694:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   8695:   fflush(ficlog);
                   8696: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  8697: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  8698: 
                   8699:   /* */
                   8700:   strcpy(fileres,"r");
                   8701:   strcat(fileres, optionfilefiname);
1.201     brouard  8702:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  8703:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  8704:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  8705: 
1.186     brouard  8706:   /* Main ---------arguments file --------*/
1.126     brouard  8707: 
                   8708:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  8709:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   8710:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  8711:     fflush(ficlog);
1.149     brouard  8712:     /* goto end; */
                   8713:     exit(70); 
1.126     brouard  8714:   }
                   8715: 
                   8716: 
                   8717: 
                   8718:   strcpy(filereso,"o");
1.201     brouard  8719:   strcat(filereso,fileresu);
1.126     brouard  8720:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   8721:     printf("Problem with Output resultfile: %s\n", filereso);
                   8722:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   8723:     fflush(ficlog);
                   8724:     goto end;
                   8725:   }
                   8726: 
                   8727:   /* Reads comments: lines beginning with '#' */
                   8728:   numlinepar=0;
1.197     brouard  8729: 
                   8730:     /* First parameter line */
                   8731:   while(fgets(line, MAXLINE, ficpar)) {
                   8732:     /* If line starts with a # it is a comment */
                   8733:     if (line[0] == '#') {
                   8734:       numlinepar++;
                   8735:       fputs(line,stdout);
                   8736:       fputs(line,ficparo);
                   8737:       fputs(line,ficlog);
                   8738:       continue;
                   8739:     }else
                   8740:       break;
                   8741:   }
                   8742:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   8743:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   8744:     if (num_filled != 5) {
                   8745:       printf("Should be 5 parameters\n");
                   8746:     }
1.126     brouard  8747:     numlinepar++;
1.197     brouard  8748:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   8749:   }
                   8750:   /* Second parameter line */
                   8751:   while(fgets(line, MAXLINE, ficpar)) {
                   8752:     /* If line starts with a # it is a comment */
                   8753:     if (line[0] == '#') {
                   8754:       numlinepar++;
                   8755:       fputs(line,stdout);
                   8756:       fputs(line,ficparo);
                   8757:       fputs(line,ficlog);
                   8758:       continue;
                   8759:     }else
                   8760:       break;
                   8761:   }
1.223     brouard  8762:   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", \
                   8763:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   8764:     if (num_filled != 11) {
                   8765:       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  8766:       printf("but line=%s\n",line);
1.197     brouard  8767:     }
1.223     brouard  8768:     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  8769:   }
1.203     brouard  8770:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  8771:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  8772:   /* Third parameter line */
                   8773:   while(fgets(line, MAXLINE, ficpar)) {
                   8774:     /* If line starts with a # it is a comment */
                   8775:     if (line[0] == '#') {
                   8776:       numlinepar++;
                   8777:       fputs(line,stdout);
                   8778:       fputs(line,ficparo);
                   8779:       fputs(line,ficlog);
                   8780:       continue;
                   8781:     }else
                   8782:       break;
                   8783:   }
1.201     brouard  8784:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
                   8785:     if (num_filled == 0)
                   8786:             model[0]='\0';
                   8787:     else if (num_filled != 1){
1.197     brouard  8788:       printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   8789:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   8790:       model[0]='\0';
                   8791:       goto end;
                   8792:     }
                   8793:     else{
                   8794:       if (model[0]=='+'){
                   8795:        for(i=1; i<=strlen(model);i++)
                   8796:          modeltemp[i-1]=model[i];
1.201     brouard  8797:        strcpy(model,modeltemp); 
1.197     brouard  8798:       }
                   8799:     }
1.199     brouard  8800:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  8801:     printf("model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  8802:   }
                   8803:   /* 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); */
                   8804:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   8805:   /* 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  8806:   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);
                   8807:   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  8808:   fflush(ficlog);
1.190     brouard  8809:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   8810:   if(model[0]=='#'){
1.187     brouard  8811:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
                   8812:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
                   8813:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");         \
                   8814:     if(mle != -1){
                   8815:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
                   8816:       exit(1);
                   8817:     }
                   8818:   }
1.126     brouard  8819:   while((c=getc(ficpar))=='#' && c!= EOF){
                   8820:     ungetc(c,ficpar);
                   8821:     fgets(line, MAXLINE, ficpar);
                   8822:     numlinepar++;
1.195     brouard  8823:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   8824:       z[0]=line[1];
                   8825:     }
                   8826:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  8827:     fputs(line, stdout);
                   8828:     //puts(line);
1.126     brouard  8829:     fputs(line,ficparo);
                   8830:     fputs(line,ficlog);
                   8831:   }
                   8832:   ungetc(c,ficpar);
                   8833: 
                   8834:    
1.145     brouard  8835:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
1.223     brouard  8836:   coqvar=matrix(1,nqv,1,n);  /**< used in readdata */
                   8837:   cotvar=ma3x(1,maxwav,1,ntv,1,n);  /**< used in readdata */
1.224   ! brouard  8838:   cotqvar=ma3x(1,maxwav,1,nqtv,1,n);  /**< used in readdata */
1.136     brouard  8839:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   8840:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   8841:      v1+v2*age+v2*v3 makes cptcovn = 3
                   8842:   */
                   8843:   if (strlen(model)>1) 
1.187     brouard  8844:     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  8845:   else
1.187     brouard  8846:     ncovmodel=2; /* Constant and age */
1.133     brouard  8847:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   8848:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  8849:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   8850:     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);
                   8851:     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);
                   8852:     fflush(stdout);
                   8853:     fclose (ficlog);
                   8854:     goto end;
                   8855:   }
1.126     brouard  8856:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   8857:   delti=delti3[1][1];
                   8858:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   8859:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   8860:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  8861:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   8862:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  8863:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   8864:     fclose (ficparo);
                   8865:     fclose (ficlog);
                   8866:     goto end;
                   8867:     exit(0);
1.220     brouard  8868:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  8869:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  8870:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   8871:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  8872:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   8873:     matcov=matrix(1,npar,1,npar);
1.203     brouard  8874:     hess=matrix(1,npar,1,npar);
1.220     brouard  8875:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  8876:     /* Read guessed parameters */
1.126     brouard  8877:     /* Reads comments: lines beginning with '#' */
                   8878:     while((c=getc(ficpar))=='#' && c!= EOF){
                   8879:       ungetc(c,ficpar);
                   8880:       fgets(line, MAXLINE, ficpar);
                   8881:       numlinepar++;
1.141     brouard  8882:       fputs(line,stdout);
1.126     brouard  8883:       fputs(line,ficparo);
                   8884:       fputs(line,ficlog);
                   8885:     }
                   8886:     ungetc(c,ficpar);
                   8887:     
                   8888:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   8889:     for(i=1; i <=nlstate; i++){
1.220     brouard  8890:                        j=0;
1.126     brouard  8891:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.220     brouard  8892:                                if(jj==i) continue;
                   8893:                                j++;
                   8894:                                fscanf(ficpar,"%1d%1d",&i1,&j1);
                   8895:                                if ((i1 != i) || (j1 != jj)){
                   8896:                                        printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  8897: It might be a problem of design; if ncovcol and the model are correct\n \
                   8898: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.220     brouard  8899:                                        exit(1);
                   8900:                                }
                   8901:                                fprintf(ficparo,"%1d%1d",i1,j1);
                   8902:                                if(mle==1)
                   8903:                                        printf("%1d%1d",i,jj);
                   8904:                                fprintf(ficlog,"%1d%1d",i,jj);
                   8905:                                for(k=1; k<=ncovmodel;k++){
                   8906:                                        fscanf(ficpar," %lf",&param[i][j][k]);
                   8907:                                        if(mle==1){
                   8908:                                                printf(" %lf",param[i][j][k]);
                   8909:                                                fprintf(ficlog," %lf",param[i][j][k]);
                   8910:                                        }
                   8911:                                        else
                   8912:                                                fprintf(ficlog," %lf",param[i][j][k]);
                   8913:                                        fprintf(ficparo," %lf",param[i][j][k]);
                   8914:                                }
                   8915:                                fscanf(ficpar,"\n");
                   8916:                                numlinepar++;
                   8917:                                if(mle==1)
                   8918:                                        printf("\n");
                   8919:                                fprintf(ficlog,"\n");
                   8920:                                fprintf(ficparo,"\n");
1.126     brouard  8921:       }
                   8922:     }  
                   8923:     fflush(ficlog);
                   8924: 
1.145     brouard  8925:     /* Reads scales values */
1.126     brouard  8926:     p=param[1][1];
                   8927:     
                   8928:     /* Reads comments: lines beginning with '#' */
                   8929:     while((c=getc(ficpar))=='#' && c!= EOF){
                   8930:       ungetc(c,ficpar);
                   8931:       fgets(line, MAXLINE, ficpar);
                   8932:       numlinepar++;
1.141     brouard  8933:       fputs(line,stdout);
1.126     brouard  8934:       fputs(line,ficparo);
                   8935:       fputs(line,ficlog);
                   8936:     }
                   8937:     ungetc(c,ficpar);
                   8938: 
                   8939:     for(i=1; i <=nlstate; i++){
                   8940:       for(j=1; j <=nlstate+ndeath-1; j++){
1.220     brouard  8941:                                fscanf(ficpar,"%1d%1d",&i1,&j1);
                   8942:                                if ( (i1-i) * (j1-j) != 0){
                   8943:                                        printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   8944:                                        exit(1);
                   8945:                                }
                   8946:                                printf("%1d%1d",i,j);
                   8947:                                fprintf(ficparo,"%1d%1d",i1,j1);
                   8948:                                fprintf(ficlog,"%1d%1d",i1,j1);
                   8949:                                for(k=1; k<=ncovmodel;k++){
                   8950:                                        fscanf(ficpar,"%le",&delti3[i][j][k]);
                   8951:                                        printf(" %le",delti3[i][j][k]);
                   8952:                                        fprintf(ficparo," %le",delti3[i][j][k]);
                   8953:                                        fprintf(ficlog," %le",delti3[i][j][k]);
                   8954:                                }
                   8955:                                fscanf(ficpar,"\n");
                   8956:                                numlinepar++;
                   8957:                                printf("\n");
                   8958:                                fprintf(ficparo,"\n");
                   8959:                                fprintf(ficlog,"\n");
1.126     brouard  8960:       }
                   8961:     }
                   8962:     fflush(ficlog);
1.220     brouard  8963:                
1.145     brouard  8964:     /* Reads covariance matrix */
1.126     brouard  8965:     delti=delti3[1][1];
1.220     brouard  8966:                
                   8967:                
1.126     brouard  8968:     /* 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  8969:                
1.126     brouard  8970:     /* Reads comments: lines beginning with '#' */
                   8971:     while((c=getc(ficpar))=='#' && c!= EOF){
                   8972:       ungetc(c,ficpar);
                   8973:       fgets(line, MAXLINE, ficpar);
                   8974:       numlinepar++;
1.141     brouard  8975:       fputs(line,stdout);
1.126     brouard  8976:       fputs(line,ficparo);
                   8977:       fputs(line,ficlog);
                   8978:     }
                   8979:     ungetc(c,ficpar);
1.220     brouard  8980:                
1.126     brouard  8981:     matcov=matrix(1,npar,1,npar);
1.203     brouard  8982:     hess=matrix(1,npar,1,npar);
1.131     brouard  8983:     for(i=1; i <=npar; i++)
                   8984:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  8985:                
1.194     brouard  8986:     /* Scans npar lines */
1.126     brouard  8987:     for(i=1; i <=npar; i++){
1.194     brouard  8988:       count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);
                   8989:       if(count != 3){
1.220     brouard  8990:                                printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  8991: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   8992: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.220     brouard  8993:                                fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  8994: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   8995: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.220     brouard  8996:                                exit(1);
                   8997:       }else{
                   8998:                                if(mle==1)
                   8999:                                        printf("%1d%1d%1d",i1,j1,jk);
                   9000:                        }
1.194     brouard  9001:       fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);
                   9002:       fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);
1.126     brouard  9003:       for(j=1; j <=i; j++){
1.220     brouard  9004:                                fscanf(ficpar," %le",&matcov[i][j]);
                   9005:                                if(mle==1){
                   9006:                                        printf(" %.5le",matcov[i][j]);
                   9007:                                }
                   9008:                                fprintf(ficlog," %.5le",matcov[i][j]);
                   9009:                                fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  9010:       }
                   9011:       fscanf(ficpar,"\n");
                   9012:       numlinepar++;
                   9013:       if(mle==1)
1.220     brouard  9014:                                printf("\n");
1.126     brouard  9015:       fprintf(ficlog,"\n");
                   9016:       fprintf(ficparo,"\n");
                   9017:     }
1.194     brouard  9018:     /* End of read covariance matrix npar lines */
1.126     brouard  9019:     for(i=1; i <=npar; i++)
                   9020:       for(j=i+1;j<=npar;j++)
1.220     brouard  9021:                                matcov[i][j]=matcov[j][i];
1.126     brouard  9022:     
                   9023:     if(mle==1)
                   9024:       printf("\n");
                   9025:     fprintf(ficlog,"\n");
                   9026:     
                   9027:     fflush(ficlog);
                   9028:     
                   9029:     /*-------- Rewriting parameter file ----------*/
                   9030:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   9031:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   9032:     strcat(rfileres,".");    /* */
                   9033:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   9034:     if((ficres =fopen(rfileres,"w"))==NULL) {
1.201     brouard  9035:       printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   9036:       fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
1.126     brouard  9037:     }
                   9038:     fprintf(ficres,"#%s\n",version);
                   9039:   }    /* End of mle != -3 */
1.218     brouard  9040:   
1.186     brouard  9041:   /*  Main data
                   9042:    */
1.126     brouard  9043:   n= lastobs;
                   9044:   num=lvector(1,n);
                   9045:   moisnais=vector(1,n);
                   9046:   annais=vector(1,n);
                   9047:   moisdc=vector(1,n);
                   9048:   andc=vector(1,n);
1.220     brouard  9049:   weight=vector(1,n);
1.126     brouard  9050:   agedc=vector(1,n);
                   9051:   cod=ivector(1,n);
1.220     brouard  9052:   for(i=1;i<=n;i++){
                   9053:                num[i]=0;
                   9054:                moisnais[i]=0;
                   9055:                annais[i]=0;
                   9056:                moisdc[i]=0;
                   9057:                andc[i]=0;
                   9058:                agedc[i]=0;
                   9059:                cod[i]=0;
                   9060:                weight[i]=1.0; /* Equal weights, 1 by default */
                   9061:        }
1.126     brouard  9062:   mint=matrix(1,maxwav,1,n);
                   9063:   anint=matrix(1,maxwav,1,n);
1.131     brouard  9064:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  9065:   tab=ivector(1,NCOVMAX);
1.144     brouard  9066:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  9067:   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  9068: 
1.136     brouard  9069:   /* Reads data from file datafile */
                   9070:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   9071:     goto end;
                   9072: 
                   9073:   /* Calculation of the number of parameters from char model */
1.137     brouard  9074:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
                   9075:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   9076:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   9077:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   9078:        k=1 Tvar[1]=2 (from V2)
                   9079:     */
                   9080:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   9081:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   9082:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   9083:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   9084:   */
                   9085:   /* For model-covariate k tells which data-covariate to use but
                   9086:     because this model-covariate is a construction we invent a new column
                   9087:     ncovcol + k1
                   9088:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   9089:     Tvar[3=V1*V4]=4+1 etc */
1.145     brouard  9090:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137     brouard  9091:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   9092:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
                   9093:   */
1.145     brouard  9094:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   9095:   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  9096:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   9097:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  9098:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  9099:                         4 covariates (3 plus signs)
                   9100:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   9101:                      */  
1.136     brouard  9102: 
1.186     brouard  9103: /* Main decodemodel */
                   9104: 
1.187     brouard  9105: 
1.223     brouard  9106:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  9107:     goto end;
                   9108: 
1.137     brouard  9109:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   9110:     nbwarn++;
                   9111:     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); 
                   9112:     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); 
                   9113:   }
1.136     brouard  9114:     /*  if(mle==1){*/
1.137     brouard  9115:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   9116:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  9117:   }
                   9118: 
                   9119:     /*-calculation of age at interview from date of interview and age at death -*/
                   9120:   agev=matrix(1,maxwav,1,imx);
                   9121: 
                   9122:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   9123:     goto end;
                   9124: 
1.126     brouard  9125: 
1.136     brouard  9126:   agegomp=(int)agemin;
                   9127:   free_vector(moisnais,1,n);
                   9128:   free_vector(annais,1,n);
1.126     brouard  9129:   /* free_matrix(mint,1,maxwav,1,n);
                   9130:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  9131:   /* free_vector(moisdc,1,n); */
                   9132:   /* free_vector(andc,1,n); */
1.145     brouard  9133:   /* */
                   9134:   
1.126     brouard  9135:   wav=ivector(1,imx);
1.214     brouard  9136:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   9137:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   9138:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   9139:   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.*/
                   9140:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   9141:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  9142:    
                   9143:   /* Concatenates waves */
1.214     brouard  9144:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   9145:      Death is a valid wave (if date is known).
                   9146:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   9147:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   9148:      and mw[mi+1][i]. dh depends on stepm.
                   9149:   */
                   9150: 
1.126     brouard  9151:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.145     brouard  9152:   /* */
                   9153:  
1.215     brouard  9154:   free_vector(moisdc,1,n);
                   9155:   free_vector(andc,1,n);
                   9156: 
1.126     brouard  9157:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   9158:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   9159:   ncodemax[1]=1;
1.145     brouard  9160:   Ndum =ivector(-1,NCOVMAX);  
1.220     brouard  9161:        cptcoveff=0;
                   9162:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
                   9163:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
                   9164:        }
                   9165:        
                   9166:        ncovcombmax=pow(2,cptcoveff);
                   9167:        invalidvarcomb=ivector(1, ncovcombmax); 
                   9168:        for(i=1;i<ncovcombmax;i++)
                   9169:                invalidvarcomb[i]=0;
                   9170: 
1.211     brouard  9171:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  9172:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  9173:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.145     brouard  9174: 
1.200     brouard  9175:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  9176:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  9177:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  9178:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   9179:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   9180:    * (currently 0 or 1) in the data.
                   9181:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   9182:    * corresponding modality (h,j).
                   9183:    */
                   9184: 
1.145     brouard  9185:   h=0;
                   9186:   /*if (cptcovn > 0) */
1.126     brouard  9187:   m=pow(2,cptcoveff);
                   9188:  
1.144     brouard  9189:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  9190:           * For k=4 covariates, h goes from 1 to m=2**k
                   9191:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   9192:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.186     brouard  9193:           *     h\k   1     2     3     4
1.143     brouard  9194:           *______________________________  
                   9195:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   9196:           *     2     2     1     1     1
                   9197:           *     3 i=2 1     2     1     1
                   9198:           *     4     2     2     1     1
                   9199:           *     5 i=3 1 i=2 1     2     1
                   9200:           *     6     2     1     2     1
                   9201:           *     7 i=4 1     2     2     1
                   9202:           *     8     2     2     2     1
1.197     brouard  9203:           *     9 i=5 1 i=3 1 i=2 1     2
                   9204:           *    10     2     1     1     2
                   9205:           *    11 i=6 1     2     1     2
                   9206:           *    12     2     2     1     2
                   9207:           *    13 i=7 1 i=4 1     2     2    
                   9208:           *    14     2     1     2     2
                   9209:           *    15 i=8 1     2     2     2
                   9210:           *    16     2     2     2     2
1.143     brouard  9211:           */
1.212     brouard  9212:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  9213:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   9214:      * and the value of each covariate?
                   9215:      * V1=1, V2=1, V3=2, V4=1 ?
                   9216:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   9217:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   9218:      * In order to get the real value in the data, we use nbcode
                   9219:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   9220:      * We are keeping this crazy system in order to be able (in the future?) 
                   9221:      * to have more than 2 values (0 or 1) for a covariate.
                   9222:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   9223:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   9224:      *              bbbbbbbb
                   9225:      *              76543210     
                   9226:      *   h-1        00000101 (6-1=5)
1.219     brouard  9227:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  9228:      *           &
                   9229:      *     1        00000001 (1)
1.219     brouard  9230:      *              00000000        = 1 & ((h-1) >> (k-1))
                   9231:      *          +1= 00000001 =1 
1.211     brouard  9232:      *
                   9233:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   9234:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   9235:      *    >>k'            11
                   9236:      *          &   00000001
                   9237:      *            = 00000001
                   9238:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   9239:      * Reverse h=6 and m=16?
                   9240:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   9241:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   9242:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   9243:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   9244:      * V3=decodtabm(14,3,2**4)=2
                   9245:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   9246:      *(h-1) >> (j-1)    0011 =13 >> 2
                   9247:      *          &1 000000001
                   9248:      *           = 000000001
                   9249:      *         +1= 000000010 =2
                   9250:      *                  2211
                   9251:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   9252:      *                  V3=2
1.220     brouard  9253:                 * codtabm and decodtabm are identical
1.211     brouard  9254:      */
                   9255: 
1.145     brouard  9256: 
                   9257:  free_ivector(Ndum,-1,NCOVMAX);
                   9258: 
                   9259: 
1.126     brouard  9260:     
1.186     brouard  9261:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  9262:   strcpy(optionfilegnuplot,optionfilefiname);
                   9263:   if(mle==-3)
1.201     brouard  9264:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  9265:   strcat(optionfilegnuplot,".gp");
                   9266: 
                   9267:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   9268:     printf("Problem with file %s",optionfilegnuplot);
                   9269:   }
                   9270:   else{
1.204     brouard  9271:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  9272:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  9273:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   9274:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  9275:   }
                   9276:   /*  fclose(ficgp);*/
1.186     brouard  9277: 
                   9278: 
                   9279:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  9280: 
                   9281:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   9282:   if(mle==-3)
1.201     brouard  9283:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  9284:   strcat(optionfilehtm,".htm");
                   9285:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  9286:     printf("Problem with %s \n",optionfilehtm);
                   9287:     exit(0);
1.126     brouard  9288:   }
                   9289: 
                   9290:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   9291:   strcat(optionfilehtmcov,"-cov.htm");
                   9292:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   9293:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   9294:   }
                   9295:   else{
                   9296:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   9297: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  9298: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  9299:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   9300:   }
                   9301: 
1.213     brouard  9302:   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  9303: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   9304: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  9305: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  9306: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  9307: \n\
                   9308: <hr  size=\"2\" color=\"#EC5E5E\">\
                   9309:  <ul><li><h4>Parameter files</h4>\n\
                   9310:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   9311:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   9312:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   9313:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   9314:  - Date and time at start: %s</ul>\n",\
                   9315:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   9316:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   9317:          fileres,fileres,\
                   9318:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   9319:   fflush(fichtm);
                   9320: 
                   9321:   strcpy(pathr,path);
                   9322:   strcat(pathr,optionfilefiname);
1.184     brouard  9323: #ifdef WIN32
                   9324:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   9325: #else
1.126     brouard  9326:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  9327: #endif
                   9328:          
1.126     brouard  9329:   
1.220     brouard  9330:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   9331:                 and for any valid combination of covariates
1.126     brouard  9332:      and prints on file fileres'p'. */
1.220     brouard  9333:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart,   \
1.223     brouard  9334:                                                        firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  9335: 
                   9336:   fprintf(fichtm,"\n");
                   9337:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   9338: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   9339: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   9340:          imx,agemin,agemax,jmin,jmax,jmean);
                   9341:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.220     brouard  9342:        oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   9343:        newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   9344:        savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   9345:        oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  9346: 
1.126     brouard  9347:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   9348:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   9349:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   9350: 
                   9351:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  9352:   /* For mortality only */
1.126     brouard  9353:   if (mle==-3){
1.136     brouard  9354:     ximort=matrix(1,NDIM,1,NDIM); 
1.220     brouard  9355:                for(i=1;i<=NDIM;i++)
                   9356:                        for(j=1;j<=NDIM;j++)
                   9357:                                ximort[i][j]=0.;
1.186     brouard  9358:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  9359:     cens=ivector(1,n);
                   9360:     ageexmed=vector(1,n);
                   9361:     agecens=vector(1,n);
                   9362:     dcwave=ivector(1,n);
1.223     brouard  9363:                
1.126     brouard  9364:     for (i=1; i<=imx; i++){
                   9365:       dcwave[i]=-1;
                   9366:       for (m=firstpass; m<=lastpass; m++)
1.218     brouard  9367:                                if (s[m][i]>nlstate) {
                   9368:                                        dcwave[i]=m;
                   9369:                                        /*      printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   9370:                                        break;
                   9371:                                }
1.126     brouard  9372:     }
1.218     brouard  9373:                
1.126     brouard  9374:     for (i=1; i<=imx; i++) {
                   9375:       if (wav[i]>0){
1.218     brouard  9376:                                ageexmed[i]=agev[mw[1][i]][i];
                   9377:                                j=wav[i];
                   9378:                                agecens[i]=1.; 
                   9379:                                
                   9380:                                if (ageexmed[i]> 1 && wav[i] > 0){
                   9381:                                        agecens[i]=agev[mw[j][i]][i];
                   9382:                                        cens[i]= 1;
                   9383:                                }else if (ageexmed[i]< 1) 
                   9384:                                        cens[i]= -1;
                   9385:                                if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   9386:                                        cens[i]=0 ;
1.126     brouard  9387:       }
                   9388:       else cens[i]=-1;
                   9389:     }
                   9390:     
                   9391:     for (i=1;i<=NDIM;i++) {
                   9392:       for (j=1;j<=NDIM;j++)
1.218     brouard  9393:                                ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  9394:     }
                   9395:     
1.145     brouard  9396:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  9397:     /*printf("%lf %lf", p[1], p[2]);*/
                   9398:     
                   9399:     
1.136     brouard  9400: #ifdef GSL
                   9401:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  9402: #else
1.126     brouard  9403:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  9404: #endif
1.201     brouard  9405:     strcpy(filerespow,"POW-MORT_"); 
                   9406:     strcat(filerespow,fileresu);
1.126     brouard  9407:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   9408:       printf("Problem with resultfile: %s\n", filerespow);
                   9409:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   9410:     }
1.136     brouard  9411: #ifdef GSL
                   9412:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  9413: #else
1.126     brouard  9414:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  9415: #endif
1.126     brouard  9416:     /*  for (i=1;i<=nlstate;i++)
                   9417:        for(j=1;j<=nlstate+ndeath;j++)
                   9418:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   9419:     */
                   9420:     fprintf(ficrespow,"\n");
1.136     brouard  9421: #ifdef GSL
                   9422:     /* gsl starts here */ 
                   9423:     T = gsl_multimin_fminimizer_nmsimplex;
                   9424:     gsl_multimin_fminimizer *sfm = NULL;
                   9425:     gsl_vector *ss, *x;
                   9426:     gsl_multimin_function minex_func;
                   9427: 
                   9428:     /* Initial vertex size vector */
                   9429:     ss = gsl_vector_alloc (NDIM);
                   9430:     
                   9431:     if (ss == NULL){
                   9432:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   9433:     }
                   9434:     /* Set all step sizes to 1 */
                   9435:     gsl_vector_set_all (ss, 0.001);
                   9436: 
                   9437:     /* Starting point */
1.126     brouard  9438:     
1.136     brouard  9439:     x = gsl_vector_alloc (NDIM);
                   9440:     
                   9441:     if (x == NULL){
                   9442:       gsl_vector_free(ss);
                   9443:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   9444:     }
                   9445:   
                   9446:     /* Initialize method and iterate */
                   9447:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  9448:     /*     gsl_vector_set(x, 0, 0.0268); */
                   9449:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  9450:     gsl_vector_set(x, 0, p[1]);
                   9451:     gsl_vector_set(x, 1, p[2]);
                   9452: 
                   9453:     minex_func.f = &gompertz_f;
                   9454:     minex_func.n = NDIM;
                   9455:     minex_func.params = (void *)&p; /* ??? */
                   9456:     
                   9457:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   9458:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   9459:     
                   9460:     printf("Iterations beginning .....\n\n");
                   9461:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   9462: 
                   9463:     iteri=0;
                   9464:     while (rval == GSL_CONTINUE){
                   9465:       iteri++;
                   9466:       status = gsl_multimin_fminimizer_iterate(sfm);
                   9467:       
                   9468:       if (status) printf("error: %s\n", gsl_strerror (status));
                   9469:       fflush(0);
                   9470:       
                   9471:       if (status) 
                   9472:         break;
                   9473:       
                   9474:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   9475:       ssval = gsl_multimin_fminimizer_size (sfm);
                   9476:       
                   9477:       if (rval == GSL_SUCCESS)
                   9478:         printf ("converged to a local maximum at\n");
                   9479:       
                   9480:       printf("%5d ", iteri);
                   9481:       for (it = 0; it < NDIM; it++){
                   9482:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   9483:       }
                   9484:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   9485:     }
                   9486:     
                   9487:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   9488:     
                   9489:     gsl_vector_free(x); /* initial values */
                   9490:     gsl_vector_free(ss); /* inital step size */
                   9491:     for (it=0; it<NDIM; it++){
                   9492:       p[it+1]=gsl_vector_get(sfm->x,it);
                   9493:       fprintf(ficrespow," %.12lf", p[it]);
                   9494:     }
                   9495:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   9496: #endif
                   9497: #ifdef POWELL
                   9498:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   9499: #endif  
1.126     brouard  9500:     fclose(ficrespow);
                   9501:     
1.203     brouard  9502:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  9503: 
                   9504:     for(i=1; i <=NDIM; i++)
                   9505:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  9506:                                matcov[i][j]=matcov[j][i];
1.126     brouard  9507:     
                   9508:     printf("\nCovariance matrix\n ");
1.203     brouard  9509:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  9510:     for(i=1; i <=NDIM; i++) {
                   9511:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  9512:                                printf("%f ",matcov[i][j]);
                   9513:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  9514:       }
1.203     brouard  9515:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  9516:     }
                   9517:     
                   9518:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  9519:     for (i=1;i<=NDIM;i++) {
1.126     brouard  9520:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  9521:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   9522:     }
1.126     brouard  9523:     lsurv=vector(1,AGESUP);
                   9524:     lpop=vector(1,AGESUP);
                   9525:     tpop=vector(1,AGESUP);
                   9526:     lsurv[agegomp]=100000;
                   9527:     
                   9528:     for (k=agegomp;k<=AGESUP;k++) {
                   9529:       agemortsup=k;
                   9530:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   9531:     }
                   9532:     
                   9533:     for (k=agegomp;k<agemortsup;k++)
                   9534:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   9535:     
                   9536:     for (k=agegomp;k<agemortsup;k++){
                   9537:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   9538:       sumlpop=sumlpop+lpop[k];
                   9539:     }
                   9540:     
                   9541:     tpop[agegomp]=sumlpop;
                   9542:     for (k=agegomp;k<(agemortsup-3);k++){
                   9543:       /*  tpop[k+1]=2;*/
                   9544:       tpop[k+1]=tpop[k]-lpop[k];
                   9545:     }
                   9546:     
                   9547:     
                   9548:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   9549:     for (k=agegomp;k<(agemortsup-2);k++) 
                   9550:       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]);
                   9551:     
                   9552:     
                   9553:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  9554:                ageminpar=50;
                   9555:                agemaxpar=100;
1.194     brouard  9556:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   9557:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   9558: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   9559: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   9560:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   9561: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   9562: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  9563:     }else{
                   9564:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   9565:                        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  9566:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  9567:                }
1.201     brouard  9568:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  9569:                     stepm, weightopt,\
                   9570:                     model,imx,p,matcov,agemortsup);
                   9571:     
                   9572:     free_vector(lsurv,1,AGESUP);
                   9573:     free_vector(lpop,1,AGESUP);
                   9574:     free_vector(tpop,1,AGESUP);
1.220     brouard  9575:     free_matrix(ximort,1,NDIM,1,NDIM);
1.136     brouard  9576:     free_ivector(cens,1,n);
                   9577:     free_vector(agecens,1,n);
                   9578:     free_ivector(dcwave,1,n);
1.220     brouard  9579: #ifdef GSL
1.136     brouard  9580: #endif
1.186     brouard  9581:   } /* Endof if mle==-3 mortality only */
1.205     brouard  9582:   /* Standard  */
                   9583:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   9584:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   9585:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  9586:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  9587:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   9588:     for (k=1; k<=npar;k++)
                   9589:       printf(" %d %8.5f",k,p[k]);
                   9590:     printf("\n");
1.205     brouard  9591:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   9592:       /* mlikeli uses func not funcone */
                   9593:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   9594:     }
                   9595:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   9596:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   9597:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   9598:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   9599:     }
                   9600:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  9601:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   9602:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   9603:     for (k=1; k<=npar;k++)
                   9604:       printf(" %d %8.5f",k,p[k]);
                   9605:     printf("\n");
                   9606:     
                   9607:     /*--------- results files --------------*/
1.224   ! brouard  9608:     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  9609:     
                   9610:     
                   9611:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9612:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9613:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9614:     for(i=1,jk=1; i <=nlstate; i++){
                   9615:       for(k=1; k <=(nlstate+ndeath); k++){
1.220     brouard  9616:                                if (k != i) {
                   9617:                                        printf("%d%d ",i,k);
                   9618:                                        fprintf(ficlog,"%d%d ",i,k);
                   9619:                                        fprintf(ficres,"%1d%1d ",i,k);
                   9620:                                        for(j=1; j <=ncovmodel; j++){
                   9621:                                                printf("%12.7f ",p[jk]);
                   9622:                                                fprintf(ficlog,"%12.7f ",p[jk]);
                   9623:                                                fprintf(ficres,"%12.7f ",p[jk]);
                   9624:                                                jk++; 
                   9625:                                        }
                   9626:                                        printf("\n");
                   9627:                                        fprintf(ficlog,"\n");
                   9628:                                        fprintf(ficres,"\n");
                   9629:                                }
1.126     brouard  9630:       }
                   9631:     }
1.203     brouard  9632:     if(mle != 0){
                   9633:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  9634:       ftolhess=ftol; /* Usually correct */
1.203     brouard  9635:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   9636:       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");
                   9637:       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");
                   9638:       for(i=1,jk=1; i <=nlstate; i++){
1.220     brouard  9639:                                for(k=1; k <=(nlstate+ndeath); k++){
                   9640:                                        if (k != i) {
                   9641:                                                printf("%d%d ",i,k);
                   9642:                                                fprintf(ficlog,"%d%d ",i,k);
                   9643:                                                for(j=1; j <=ncovmodel; j++){
                   9644:                                                        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]));
                   9645:                                                        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]));
                   9646:                                                        jk++; 
                   9647:                                                }
                   9648:                                                printf("\n");
                   9649:                                                fprintf(ficlog,"\n");
                   9650:                                        }
                   9651:                                }
1.193     brouard  9652:       }
1.203     brouard  9653:     } /* end of hesscov and Wald tests */
1.220     brouard  9654:                
1.203     brouard  9655:     /*  */
1.126     brouard  9656:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   9657:     printf("# Scales (for hessian or gradient estimation)\n");
                   9658:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   9659:     for(i=1,jk=1; i <=nlstate; i++){
                   9660:       for(j=1; j <=nlstate+ndeath; j++){
1.220     brouard  9661:                                if (j!=i) {
                   9662:                                        fprintf(ficres,"%1d%1d",i,j);
                   9663:                                        printf("%1d%1d",i,j);
                   9664:                                        fprintf(ficlog,"%1d%1d",i,j);
                   9665:                                        for(k=1; k<=ncovmodel;k++){
                   9666:                                                printf(" %.5e",delti[jk]);
                   9667:                                                fprintf(ficlog," %.5e",delti[jk]);
                   9668:                                                fprintf(ficres," %.5e",delti[jk]);
                   9669:                                                jk++;
                   9670:                                        }
                   9671:                                        printf("\n");
                   9672:                                        fprintf(ficlog,"\n");
                   9673:                                        fprintf(ficres,"\n");
                   9674:                                }
1.126     brouard  9675:       }
                   9676:     }
                   9677:     
                   9678:     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  9679:     if(mle >= 1) /* To big for the screen */
1.126     brouard  9680:       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");
                   9681:     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");
                   9682:     /* # 121 Var(a12)\n\ */
                   9683:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   9684:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   9685:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   9686:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   9687:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   9688:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   9689:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   9690:     
                   9691:     
                   9692:     /* Just to have a covariance matrix which will be more understandable
                   9693:        even is we still don't want to manage dictionary of variables
                   9694:     */
                   9695:     for(itimes=1;itimes<=2;itimes++){
                   9696:       jj=0;
                   9697:       for(i=1; i <=nlstate; i++){
1.220     brouard  9698:                                for(j=1; j <=nlstate+ndeath; j++){
                   9699:                                        if(j==i) continue;
                   9700:                                        for(k=1; k<=ncovmodel;k++){
                   9701:                                                jj++;
                   9702:                                                ca[0]= k+'a'-1;ca[1]='\0';
                   9703:                                                if(itimes==1){
                   9704:                                                        if(mle>=1)
                   9705:                                                                printf("#%1d%1d%d",i,j,k);
                   9706:                                                        fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   9707:                                                        fprintf(ficres,"#%1d%1d%d",i,j,k);
                   9708:                                                }else{
                   9709:                                                        if(mle>=1)
                   9710:                                                                printf("%1d%1d%d",i,j,k);
                   9711:                                                        fprintf(ficlog,"%1d%1d%d",i,j,k);
                   9712:                                                        fprintf(ficres,"%1d%1d%d",i,j,k);
                   9713:                                                }
                   9714:                                                ll=0;
                   9715:                                                for(li=1;li <=nlstate; li++){
                   9716:                                                        for(lj=1;lj <=nlstate+ndeath; lj++){
                   9717:                                                                if(lj==li) continue;
                   9718:                                                                for(lk=1;lk<=ncovmodel;lk++){
                   9719:                                                                        ll++;
                   9720:                                                                        if(ll<=jj){
                   9721:                                                                                cb[0]= lk +'a'-1;cb[1]='\0';
                   9722:                                                                                if(ll<jj){
                   9723:                                                                                        if(itimes==1){
                   9724:                                                                                                if(mle>=1)
                   9725:                                                                                                        printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9726:                                                                                                fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9727:                                                                                                fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9728:                                                                                        }else{
                   9729:                                                                                                if(mle>=1)
                   9730:                                                                                                        printf(" %.5e",matcov[jj][ll]); 
                   9731:                                                                                                fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   9732:                                                                                                fprintf(ficres," %.5e",matcov[jj][ll]); 
                   9733:                                                                                        }
                   9734:                                                                                }else{
                   9735:                                                                                        if(itimes==1){
                   9736:                                                                                                if(mle>=1)
                   9737:                                                                                                        printf(" Var(%s%1d%1d)",ca,i,j);
                   9738:                                                                                                fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   9739:                                                                                                fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   9740:                                                                                        }else{
                   9741:                                                                                                if(mle>=1)
                   9742:                                                                                                        printf(" %.7e",matcov[jj][ll]); 
                   9743:                                                                                                fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   9744:                                                                                                fprintf(ficres," %.7e",matcov[jj][ll]); 
                   9745:                                                                                        }
                   9746:                                                                                }
                   9747:                                                                        }
                   9748:                                                                } /* end lk */
                   9749:                                                        } /* end lj */
                   9750:                                                } /* end li */
                   9751:                                                if(mle>=1)
                   9752:                                                        printf("\n");
                   9753:                                                fprintf(ficlog,"\n");
                   9754:                                                fprintf(ficres,"\n");
                   9755:                                                numlinepar++;
                   9756:                                        } /* end k*/
                   9757:                                } /*end j */
1.126     brouard  9758:       } /* end i */
                   9759:     } /* end itimes */
                   9760:     
                   9761:     fflush(ficlog);
                   9762:     fflush(ficres);
1.220     brouard  9763:                while(fgets(line, MAXLINE, ficpar)) {
                   9764:                        /* If line starts with a # it is a comment */
                   9765:                        if (line[0] == '#') {
                   9766:                                numlinepar++;
                   9767:                                fputs(line,stdout);
                   9768:                                fputs(line,ficparo);
                   9769:                                fputs(line,ficlog);
                   9770:                                continue;
                   9771:                        }else
                   9772:                                break;
                   9773:                }
                   9774:                
1.209     brouard  9775:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   9776:     /*   ungetc(c,ficpar); */
                   9777:     /*   fgets(line, MAXLINE, ficpar); */
                   9778:     /*   fputs(line,stdout); */
                   9779:     /*   fputs(line,ficparo); */
                   9780:     /* } */
                   9781:     /* ungetc(c,ficpar); */
1.126     brouard  9782:     
                   9783:     estepm=0;
1.209     brouard  9784:     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.220     brouard  9785:                        
                   9786:                        if (num_filled != 6) {
                   9787:                                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);
                   9788:                                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);
                   9789:                                goto end;
                   9790:                        }
                   9791:                        printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   9792:                }
                   9793:                /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   9794:                /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   9795:                
1.209     brouard  9796:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  9797:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   9798:     if (fage <= 2) {
                   9799:       bage = ageminpar;
                   9800:       fage = agemaxpar;
                   9801:     }
                   9802:     
                   9803:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  9804:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   9805:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  9806:                
1.186     brouard  9807:     /* Other stuffs, more or less useful */    
1.126     brouard  9808:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9809:       ungetc(c,ficpar);
                   9810:       fgets(line, MAXLINE, ficpar);
1.141     brouard  9811:       fputs(line,stdout);
1.126     brouard  9812:       fputs(line,ficparo);
                   9813:     }
                   9814:     ungetc(c,ficpar);
                   9815:     
                   9816:     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);
                   9817:     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);
                   9818:     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);
                   9819:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   9820:     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);
                   9821:     
                   9822:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9823:       ungetc(c,ficpar);
                   9824:       fgets(line, MAXLINE, ficpar);
1.141     brouard  9825:       fputs(line,stdout);
1.126     brouard  9826:       fputs(line,ficparo);
                   9827:     }
                   9828:     ungetc(c,ficpar);
                   9829:     
                   9830:     
                   9831:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   9832:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   9833:     
                   9834:     fscanf(ficpar,"pop_based=%d\n",&popbased);
1.193     brouard  9835:     fprintf(ficlog,"pop_based=%d\n",popbased);
1.126     brouard  9836:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   9837:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   9838:     
                   9839:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9840:       ungetc(c,ficpar);
                   9841:       fgets(line, MAXLINE, ficpar);
1.141     brouard  9842:       fputs(line,stdout);
1.126     brouard  9843:       fputs(line,ficparo);
                   9844:     }
                   9845:     ungetc(c,ficpar);
                   9846:     
                   9847:     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);
                   9848:     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);
                   9849:     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);
                   9850:     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);
                   9851:     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);
                   9852:     /* day and month of proj2 are not used but only year anproj2.*/
                   9853:     
1.217     brouard  9854:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9855:       ungetc(c,ficpar);
                   9856:       fgets(line, MAXLINE, ficpar);
                   9857:       fputs(line,stdout);
                   9858:       fputs(line,ficparo);
                   9859:     }
                   9860:     ungetc(c,ficpar);
                   9861:     
                   9862:     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  9863:     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);
                   9864:     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);
                   9865:     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  9866:     /* day and month of proj2 are not used but only year anproj2.*/
1.126     brouard  9867:     
                   9868:     
1.220     brouard  9869:                /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  9870:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  9871:     
                   9872:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  9873:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.220     brouard  9874:                        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  9875: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   9876: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  9877:                        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  9878: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   9879: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  9880:     }else{
1.218     brouard  9881:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p);
1.220     brouard  9882:     }
                   9883:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
                   9884:                                                                 model,imx,jmin,jmax,jmean,rfileres,popforecast,prevfcast,backcast, estepm, \
                   9885:                                                                 jprev1,mprev1,anprev1,dateprev1,jprev2,mprev2,anprev2,dateprev2);
                   9886:                
                   9887:                /*------------ free_vector  -------------*/
                   9888:                /*  chdir(path); */
                   9889:                
1.215     brouard  9890:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   9891:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   9892:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   9893:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.126     brouard  9894:     free_lvector(num,1,n);
                   9895:     free_vector(agedc,1,n);
                   9896:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   9897:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   9898:     fclose(ficparo);
                   9899:     fclose(ficres);
1.220     brouard  9900:                
                   9901:                
1.186     brouard  9902:     /* Other results (useful)*/
1.220     brouard  9903:                
                   9904:                
1.126     brouard  9905:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  9906:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   9907:     prlim=matrix(1,nlstate,1,nlstate);
1.209     brouard  9908:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  9909:     fclose(ficrespl);
                   9910: 
                   9911:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  9912:     /*#include "hpijx.h"*/
                   9913:     hPijx(p, bage, fage);
1.145     brouard  9914:     fclose(ficrespij);
1.126     brouard  9915: 
1.220     brouard  9916:     /* ncovcombmax=  pow(2,cptcoveff); */
1.219     brouard  9917:     /*-------------- Variance of one-step probabilities---*/
1.145     brouard  9918:     k=1;
1.126     brouard  9919:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
                   9920: 
1.219     brouard  9921:     /* Prevalence for each covariates in probs[age][status][cov] */
1.218     brouard  9922:     probs= ma3x(1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.126     brouard  9923:     for(i=1;i<=AGESUP;i++)
1.219     brouard  9924:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.218     brouard  9925:                                for(k=1;k<=ncovcombmax;k++)
                   9926:                                        probs[i][j][k]=0.;
1.219     brouard  9927:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   9928:     if (mobilav!=0 ||mobilavproj !=0 ) {
                   9929:       mobaverages= ma3x(1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   9930:                        for(i=1;i<=AGESUP;i++)
                   9931:                                for(j=1;j<=nlstate;j++)
                   9932:                                        for(k=1;k<=ncovcombmax;k++)
                   9933:                                                mobaverages[i][j][k]=0.;
                   9934:       mobaverage=mobaverages;
                   9935:       if (mobilav!=0) {
1.218     brouard  9936:                                if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   9937:                                        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   9938:                                        printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   9939:                                }
1.219     brouard  9940:       }
                   9941:       /* /\* Prevalence for each covariates in probs[age][status][cov] *\/ */
                   9942:       /* prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   9943:       else if (mobilavproj !=0) {
1.218     brouard  9944:                                if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   9945:                                        fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   9946:                                        printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   9947:                                }
1.219     brouard  9948:       }
                   9949:     }/* end if moving average */
                   9950:                
1.126     brouard  9951:     /*---------- Forecasting ------------------*/
                   9952:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   9953:     if(prevfcast==1){
                   9954:       /*    if(stepm ==1){*/
1.224   ! brouard  9955:       prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, nqveff);
1.126     brouard  9956:     }
1.217     brouard  9957:     if(backcast==1){
1.219     brouard  9958:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   9959:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   9960:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   9961: 
                   9962:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   9963: 
                   9964:       bprlim=matrix(1,nlstate,1,nlstate);
                   9965:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   9966:       fclose(ficresplb);
                   9967: 
1.222     brouard  9968:       hBijx(p, bage, fage, mobaverage);
                   9969:       fclose(ficrespijb);
1.219     brouard  9970:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   9971: 
                   9972:       /* prevbackforecast(fileresu, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, mobilavproj,
1.224   ! brouard  9973:         bage, fage, firstpass, lastpass, anback2, p, nqveff); */
1.219     brouard  9974:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   9975:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   9976:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   9977:     }
1.217     brouard  9978:     
1.186     brouard  9979:  
                   9980:     /* ------ Other prevalence ratios------------ */
1.126     brouard  9981: 
1.215     brouard  9982:     free_ivector(wav,1,imx);
                   9983:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   9984:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   9985:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  9986:                
                   9987:                
1.127     brouard  9988:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  9989:                
1.201     brouard  9990:     strcpy(filerese,"E_");
                   9991:     strcat(filerese,fileresu);
1.126     brouard  9992:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   9993:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   9994:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   9995:     }
1.208     brouard  9996:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   9997:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.219     brouard  9998:                
1.224   ! brouard  9999:     for (k=1; k <= (int) pow(2,nqveff); k++){
1.219     brouard  10000:       fprintf(ficreseij,"\n#****** ");
1.224   ! brouard  10001:       for(j=1;j<=nqveff;j++) {
1.220     brouard  10002:                                fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.219     brouard  10003:       }
                   10004:       fprintf(ficreseij,"******\n");
                   10005:       
                   10006:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   10007:       oldm=oldms;savm=savms;
                   10008:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
1.127     brouard  10009:       
1.219     brouard  10010:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  10011:     }
                   10012:     fclose(ficreseij);
1.208     brouard  10013:     printf("done evsij\n");fflush(stdout);
                   10014:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.218     brouard  10015:                
1.127     brouard  10016:     /*---------- Health expectancies and variances ------------*/
1.218     brouard  10017:                
                   10018:                
1.201     brouard  10019:     strcpy(filerest,"T_");
                   10020:     strcat(filerest,fileresu);
1.127     brouard  10021:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   10022:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   10023:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   10024:     }
1.208     brouard  10025:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   10026:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.218     brouard  10027:                
1.126     brouard  10028: 
1.201     brouard  10029:     strcpy(fileresstde,"STDE_");
                   10030:     strcat(fileresstde,fileresu);
1.126     brouard  10031:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
                   10032:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   10033:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   10034:     }
1.208     brouard  10035:     printf("  Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   10036:     fprintf(ficlog,"  Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  10037: 
1.201     brouard  10038:     strcpy(filerescve,"CVE_");
                   10039:     strcat(filerescve,fileresu);
1.126     brouard  10040:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
                   10041:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   10042:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   10043:     }
1.208     brouard  10044:     printf("    Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   10045:     fprintf(ficlog,"    Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  10046: 
1.201     brouard  10047:     strcpy(fileresv,"V_");
                   10048:     strcat(fileresv,fileresu);
1.126     brouard  10049:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   10050:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   10051:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   10052:     }
1.208     brouard  10053:     printf("      Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(stdout);
                   10054:     fprintf(ficlog,"      Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  10055: 
1.145     brouard  10056:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   10057:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   10058:           
1.224   ! brouard  10059:     for (k=1; k <= (int) pow(2,nqveff); k++){
1.208     brouard  10060:       fprintf(ficrest,"\n#****** ");
1.224   ! brouard  10061:       for(j=1;j<=nqveff;j++) 
1.218     brouard  10062:                                fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.208     brouard  10063:       fprintf(ficrest,"******\n");
                   10064:       
                   10065:       fprintf(ficresstdeij,"\n#****** ");
                   10066:       fprintf(ficrescveij,"\n#****** ");
1.224   ! brouard  10067:       for(j=1;j<=nqveff;j++) {
1.218     brouard  10068:                                fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10069:                                fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.208     brouard  10070:       }
                   10071:       fprintf(ficresstdeij,"******\n");
                   10072:       fprintf(ficrescveij,"******\n");
                   10073:       
                   10074:       fprintf(ficresvij,"\n#****** ");
1.224   ! brouard  10075:       for(j=1;j<=nqveff;j++) 
1.218     brouard  10076:                                fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.208     brouard  10077:       fprintf(ficresvij,"******\n");
                   10078:       
                   10079:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   10080:       oldm=oldms;savm=savms;
                   10081:       printf(" cvevsij %d, ",k);
                   10082:       fprintf(ficlog, " cvevsij %d, ",k);
                   10083:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
                   10084:       printf(" end cvevsij \n ");
                   10085:       fprintf(ficlog, " end cvevsij \n ");
                   10086:       
                   10087:       /*
                   10088:        */
                   10089:       /* goto endfree; */
                   10090:       
                   10091:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   10092:       pstamp(ficrest);
                   10093:       
                   10094:       
                   10095:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.220     brouard  10096:                                oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   10097:                                cptcod= 0; /* To be deleted */
                   10098:                                printf("varevsij %d \n",vpopbased);
                   10099:                                fprintf(ficlog, "varevsij %d \n",vpopbased);
                   10100:                                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 */
                   10101:                                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 ");
                   10102:                                if(vpopbased==1)
                   10103:                                        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);
                   10104:                                else
                   10105:                                        fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
                   10106:                                fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
                   10107:                                for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   10108:                                fprintf(ficrest,"\n");
                   10109:                                /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
                   10110:                                epj=vector(1,nlstate+1);
                   10111:                                printf("Computing age specific period (stable) prevalences in each health state \n");
                   10112:                                fprintf(ficlog,"Computing age specific period (stable) prevalences in each health state \n");
                   10113:                                for(age=bage; age <=fage ;age++){
                   10114:                                        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k); /*ZZ Is it the correct prevalim */
                   10115:                                        if (vpopbased==1) {
                   10116:                                                if(mobilav ==0){
                   10117:                                                        for(i=1; i<=nlstate;i++)
                   10118:                                                                prlim[i][i]=probs[(int)age][i][k];
                   10119:                                                }else{ /* mobilav */ 
                   10120:                                                        for(i=1; i<=nlstate;i++)
                   10121:                                                                prlim[i][i]=mobaverage[(int)age][i][k];
                   10122:                                                }
                   10123:                                        }
1.219     brouard  10124:          
1.220     brouard  10125:                                        fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   10126:                                        /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   10127:                                        /* printf(" age %4.0f ",age); */
                   10128:                                        for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   10129:                                                for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   10130:                                                        epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   10131:                                                        /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   10132:                                                        /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   10133:                                                }
                   10134:                                                epj[nlstate+1] +=epj[j];
                   10135:                                        }
                   10136:                                        /* printf(" age %4.0f \n",age); */
1.219     brouard  10137:          
1.220     brouard  10138:                                        for(i=1, vepp=0.;i <=nlstate;i++)
                   10139:                                                for(j=1;j <=nlstate;j++)
                   10140:                                                        vepp += vareij[i][j][(int)age];
                   10141:                                        fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   10142:                                        for(j=1;j <=nlstate;j++){
                   10143:                                                fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   10144:                                        }
                   10145:                                        fprintf(ficrest,"\n");
                   10146:                                }
1.208     brouard  10147:       } /* End vpopbased */
                   10148:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   10149:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   10150:       free_vector(epj,1,nlstate+1);
                   10151:       printf("done \n");fflush(stdout);
                   10152:       fprintf(ficlog,"done\n");fflush(ficlog);
                   10153:       
1.145     brouard  10154:       /*}*/
1.208     brouard  10155:     } /* End k */
1.126     brouard  10156:     free_vector(weight,1,n);
1.145     brouard  10157:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126     brouard  10158:     free_imatrix(s,1,maxwav+1,1,n);
                   10159:     free_matrix(anint,1,maxwav,1,n); 
                   10160:     free_matrix(mint,1,maxwav,1,n);
                   10161:     free_ivector(cod,1,n);
                   10162:     free_ivector(tab,1,NCOVMAX);
                   10163:     fclose(ficresstdeij);
                   10164:     fclose(ficrescveij);
                   10165:     fclose(ficresvij);
                   10166:     fclose(ficrest);
1.208     brouard  10167:     printf("done Health expectancies\n");fflush(stdout);
                   10168:     fprintf(ficlog,"done Health expectancies\n");fflush(ficlog);
1.126     brouard  10169:     fclose(ficpar);
                   10170:   
                   10171:     /*------- Variance of period (stable) prevalence------*/   
                   10172: 
1.201     brouard  10173:     strcpy(fileresvpl,"VPL_");
                   10174:     strcat(fileresvpl,fileresu);
1.126     brouard  10175:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   10176:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   10177:       exit(0);
                   10178:     }
1.208     brouard  10179:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   10180:     fprintf(ficlog, "Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.126     brouard  10181: 
1.145     brouard  10182:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   10183:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   10184:           
1.224   ! brouard  10185:     for (k=1; k <= (int) pow(2,nqveff); k++){
1.145     brouard  10186:        fprintf(ficresvpl,"\n#****** ");
1.224   ! brouard  10187:                        for(j=1;j<=nqveff;j++) 
1.218     brouard  10188:                                fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10189:                        fprintf(ficresvpl,"******\n");
                   10190:       
                   10191:                        varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   10192:                        oldm=oldms;savm=savms;
                   10193:                        varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, strstart);
                   10194:                        free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145     brouard  10195:       /*}*/
1.126     brouard  10196:     }
1.218     brouard  10197:                
1.126     brouard  10198:     fclose(ficresvpl);
1.208     brouard  10199:     printf("done variance-covariance of period prevalence\n");fflush(stdout);
                   10200:     fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
1.126     brouard  10201: 
                   10202:     /*---------- End : free ----------------*/
1.219     brouard  10203:     if (mobilav!=0 ||mobilavproj !=0)
                   10204:       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  10205:     free_ma3x(probs,1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  10206:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   10207:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  10208:   }  /* mle==-3 arrives here for freeing */
1.164     brouard  10209:  /* endfree:*/
1.126     brouard  10210:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   10211:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   10212:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.224   ! brouard  10213:     free_ma3x(cotqvar,1,maxwav,1,nqtv,1,n);
1.223     brouard  10214:     free_ma3x(cotvar,1,maxwav,1,ntv,1,n);
                   10215:     free_matrix(coqvar,1,maxwav,1,n);
1.126     brouard  10216:     free_matrix(covar,0,NCOVMAX,1,n);
                   10217:     free_matrix(matcov,1,npar,1,npar);
1.203     brouard  10218:     free_matrix(hess,1,npar,1,npar);
1.126     brouard  10219:     /*free_vector(delti,1,npar);*/
                   10220:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   10221:     free_matrix(agev,1,maxwav,1,imx);
                   10222:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   10223: 
1.145     brouard  10224:     free_ivector(ncodemax,1,NCOVMAX);
1.192     brouard  10225:     free_ivector(ncodemaxwundef,1,NCOVMAX);
1.145     brouard  10226:     free_ivector(Tvar,1,NCOVMAX);
                   10227:     free_ivector(Tprod,1,NCOVMAX);
                   10228:     free_ivector(Tvaraff,1,NCOVMAX);
1.220     brouard  10229:     free_ivector(invalidvarcomb,1,ncovcombmax);
1.145     brouard  10230:     free_ivector(Tage,1,NCOVMAX);
1.126     brouard  10231: 
                   10232:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
1.200     brouard  10233:     /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  10234:   fflush(fichtm);
                   10235:   fflush(ficgp);
                   10236:   
                   10237: 
                   10238:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  10239:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   10240:     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  10241:   }else{
                   10242:     printf("End of Imach\n");
                   10243:     fprintf(ficlog,"End of Imach\n");
                   10244:   }
                   10245:   printf("See log file on %s\n",filelog);
                   10246:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  10247:   /*(void) gettimeofday(&end_time,&tzp);*/
                   10248:   rend_time = time(NULL);  
                   10249:   end_time = *localtime(&rend_time);
                   10250:   /* tml = *localtime(&end_time.tm_sec); */
                   10251:   strcpy(strtend,asctime(&end_time));
1.126     brouard  10252:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   10253:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  10254:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126     brouard  10255: 
1.157     brouard  10256:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   10257:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   10258:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  10259:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   10260: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   10261:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   10262:   fclose(fichtm);
                   10263:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   10264:   fclose(fichtmcov);
                   10265:   fclose(ficgp);
                   10266:   fclose(ficlog);
                   10267:   /*------ End -----------*/
                   10268: 
                   10269: 
                   10270:    printf("Before Current directory %s!\n",pathcd);
1.184     brouard  10271: #ifdef WIN32
                   10272:    if (_chdir(pathcd) != 0)
                   10273:           printf("Can't move to directory %s!\n",path);
                   10274:    if(_getcwd(pathcd,MAXLINE) > 0)
                   10275: #else
1.126     brouard  10276:    if(chdir(pathcd) != 0)
1.184     brouard  10277:           printf("Can't move to directory %s!\n", path);
                   10278:    if (getcwd(pathcd, MAXLINE) > 0)
                   10279: #endif 
1.126     brouard  10280:     printf("Current directory %s!\n",pathcd);
                   10281:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   10282:   sprintf(plotcmd,"gnuplot");
1.157     brouard  10283: #ifdef _WIN32
1.126     brouard  10284:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   10285: #endif
                   10286:   if(!stat(plotcmd,&info)){
1.158     brouard  10287:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  10288:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  10289:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  10290:     }else
                   10291:       strcpy(pplotcmd,plotcmd);
1.157     brouard  10292: #ifdef __unix
1.126     brouard  10293:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   10294:     if(!stat(plotcmd,&info)){
1.158     brouard  10295:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  10296:     }else
                   10297:       strcpy(pplotcmd,plotcmd);
                   10298: #endif
                   10299:   }else
                   10300:     strcpy(pplotcmd,plotcmd);
                   10301:   
                   10302:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  10303:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  10304: 
                   10305:   if((outcmd=system(plotcmd)) != 0){
1.158     brouard  10306:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  10307:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  10308:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150     brouard  10309:     if((outcmd=system(plotcmd)) != 0)
1.153     brouard  10310:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126     brouard  10311:   }
1.158     brouard  10312:   printf(" Successful, please wait...");
1.126     brouard  10313:   while (z[0] != 'q') {
                   10314:     /* chdir(path); */
1.154     brouard  10315:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  10316:     scanf("%s",z);
                   10317: /*     if (z[0] == 'c') system("./imach"); */
                   10318:     if (z[0] == 'e') {
1.158     brouard  10319: #ifdef __APPLE__
1.152     brouard  10320:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  10321: #elif __linux
                   10322:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  10323: #else
1.152     brouard  10324:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  10325: #endif
                   10326:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   10327:       system(pplotcmd);
1.126     brouard  10328:     }
                   10329:     else if (z[0] == 'g') system(plotcmd);
                   10330:     else if (z[0] == 'q') exit(0);
                   10331:   }
                   10332:   end:
                   10333:   while (z[0] != 'q') {
1.195     brouard  10334:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  10335:     scanf("%s",z);
                   10336:   }
                   10337: }

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