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

1.223   ! brouard     1: /* $Id: imach.c,v 1.222 2016/02/17 08:14:50 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.223   ! brouard     4:   Revision 1.222  2016/02/17 08:14:50  brouard
        !             5:   Summary: Probably last 0.98 stable version 0.98r6
        !             6: 
1.222     brouard     7:   Revision 1.221  2016/02/15 23:35:36  brouard
                      8:   Summary: minor bug
                      9: 
1.220     brouard    10:   Revision 1.219  2016/02/15 00:48:12  brouard
                     11:   *** empty log message ***
                     12: 
1.219     brouard    13:   Revision 1.218  2016/02/12 11:29:23  brouard
                     14:   Summary: 0.99 Back projections
                     15: 
1.218     brouard    16:   Revision 1.217  2015/12/23 17:18:31  brouard
                     17:   Summary: Experimental backcast
                     18: 
1.217     brouard    19:   Revision 1.216  2015/12/18 17:32:11  brouard
                     20:   Summary: 0.98r4 Warning and status=-2
                     21: 
                     22:   Version 0.98r4 is now:
                     23:    - displaying an error when status is -1, date of interview unknown and date of death known;
                     24:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                     25:   Older changes concerning s=-2, dating from 2005 have been supersed.
                     26: 
1.216     brouard    27:   Revision 1.215  2015/12/16 08:52:24  brouard
                     28:   Summary: 0.98r4 working
                     29: 
1.215     brouard    30:   Revision 1.214  2015/12/16 06:57:54  brouard
                     31:   Summary: temporary not working
                     32: 
1.214     brouard    33:   Revision 1.213  2015/12/11 18:22:17  brouard
                     34:   Summary: 0.98r4
                     35: 
1.213     brouard    36:   Revision 1.212  2015/11/21 12:47:24  brouard
                     37:   Summary: minor typo
                     38: 
1.212     brouard    39:   Revision 1.211  2015/11/21 12:41:11  brouard
                     40:   Summary: 0.98r3 with some graph of projected cross-sectional
                     41: 
                     42:   Author: Nicolas Brouard
                     43: 
1.211     brouard    44:   Revision 1.210  2015/11/18 17:41:20  brouard
                     45:   Summary: Start working on projected prevalences
                     46: 
1.210     brouard    47:   Revision 1.209  2015/11/17 22:12:03  brouard
                     48:   Summary: Adding ftolpl parameter
                     49:   Author: N Brouard
                     50: 
                     51:   We had difficulties to get smoothed confidence intervals. It was due
                     52:   to the period prevalence which wasn't computed accurately. The inner
                     53:   parameter ftolpl is now an outer parameter of the .imach parameter
                     54:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                     55:   computation are long.
                     56: 
1.209     brouard    57:   Revision 1.208  2015/11/17 14:31:57  brouard
                     58:   Summary: temporary
                     59: 
1.208     brouard    60:   Revision 1.207  2015/10/27 17:36:57  brouard
                     61:   *** empty log message ***
                     62: 
1.207     brouard    63:   Revision 1.206  2015/10/24 07:14:11  brouard
                     64:   *** empty log message ***
                     65: 
1.206     brouard    66:   Revision 1.205  2015/10/23 15:50:53  brouard
                     67:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                     68: 
1.205     brouard    69:   Revision 1.204  2015/10/01 16:20:26  brouard
                     70:   Summary: Some new graphs of contribution to likelihood
                     71: 
1.204     brouard    72:   Revision 1.203  2015/09/30 17:45:14  brouard
                     73:   Summary: looking at better estimation of the hessian
                     74: 
                     75:   Also a better criteria for convergence to the period prevalence And
                     76:   therefore adding the number of years needed to converge. (The
                     77:   prevalence in any alive state shold sum to one
                     78: 
1.203     brouard    79:   Revision 1.202  2015/09/22 19:45:16  brouard
                     80:   Summary: Adding some overall graph on contribution to likelihood. Might change
                     81: 
1.202     brouard    82:   Revision 1.201  2015/09/15 17:34:58  brouard
                     83:   Summary: 0.98r0
                     84: 
                     85:   - Some new graphs like suvival functions
                     86:   - Some bugs fixed like model=1+age+V2.
                     87: 
1.201     brouard    88:   Revision 1.200  2015/09/09 16:53:55  brouard
                     89:   Summary: Big bug thanks to Flavia
                     90: 
                     91:   Even model=1+age+V2. did not work anymore
                     92: 
1.200     brouard    93:   Revision 1.199  2015/09/07 14:09:23  brouard
                     94:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                     95: 
1.199     brouard    96:   Revision 1.198  2015/09/03 07:14:39  brouard
                     97:   Summary: 0.98q5 Flavia
                     98: 
1.198     brouard    99:   Revision 1.197  2015/09/01 18:24:39  brouard
                    100:   *** empty log message ***
                    101: 
1.197     brouard   102:   Revision 1.196  2015/08/18 23:17:52  brouard
                    103:   Summary: 0.98q5
                    104: 
1.196     brouard   105:   Revision 1.195  2015/08/18 16:28:39  brouard
                    106:   Summary: Adding a hack for testing purpose
                    107: 
                    108:   After reading the title, ftol and model lines, if the comment line has
                    109:   a q, starting with #q, the answer at the end of the run is quit. It
                    110:   permits to run test files in batch with ctest. The former workaround was
                    111:   $ echo q | imach foo.imach
                    112: 
1.195     brouard   113:   Revision 1.194  2015/08/18 13:32:00  brouard
                    114:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    115: 
1.194     brouard   116:   Revision 1.193  2015/08/04 07:17:42  brouard
                    117:   Summary: 0.98q4
                    118: 
1.193     brouard   119:   Revision 1.192  2015/07/16 16:49:02  brouard
                    120:   Summary: Fixing some outputs
                    121: 
1.192     brouard   122:   Revision 1.191  2015/07/14 10:00:33  brouard
                    123:   Summary: Some fixes
                    124: 
1.191     brouard   125:   Revision 1.190  2015/05/05 08:51:13  brouard
                    126:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    127: 
                    128:   Fix 1+age+.
                    129: 
1.190     brouard   130:   Revision 1.189  2015/04/30 14:45:16  brouard
                    131:   Summary: 0.98q2
                    132: 
1.189     brouard   133:   Revision 1.188  2015/04/30 08:27:53  brouard
                    134:   *** empty log message ***
                    135: 
1.188     brouard   136:   Revision 1.187  2015/04/29 09:11:15  brouard
                    137:   *** empty log message ***
                    138: 
1.187     brouard   139:   Revision 1.186  2015/04/23 12:01:52  brouard
                    140:   Summary: V1*age is working now, version 0.98q1
                    141: 
                    142:   Some codes had been disabled in order to simplify and Vn*age was
                    143:   working in the optimization phase, ie, giving correct MLE parameters,
                    144:   but, as usual, outputs were not correct and program core dumped.
                    145: 
1.186     brouard   146:   Revision 1.185  2015/03/11 13:26:42  brouard
                    147:   Summary: Inclusion of compile and links command line for Intel Compiler
                    148: 
1.185     brouard   149:   Revision 1.184  2015/03/11 11:52:39  brouard
                    150:   Summary: Back from Windows 8. Intel Compiler
                    151: 
1.184     brouard   152:   Revision 1.183  2015/03/10 20:34:32  brouard
                    153:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    154: 
                    155:   We use directest instead of original Powell test; probably no
                    156:   incidence on the results, but better justifications;
                    157:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    158:   wrong results.
                    159: 
1.183     brouard   160:   Revision 1.182  2015/02/12 08:19:57  brouard
                    161:   Summary: Trying to keep directest which seems simpler and more general
                    162:   Author: Nicolas Brouard
                    163: 
1.182     brouard   164:   Revision 1.181  2015/02/11 23:22:24  brouard
                    165:   Summary: Comments on Powell added
                    166: 
                    167:   Author:
                    168: 
1.181     brouard   169:   Revision 1.180  2015/02/11 17:33:45  brouard
                    170:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    171: 
1.180     brouard   172:   Revision 1.179  2015/01/04 09:57:06  brouard
                    173:   Summary: back to OS/X
                    174: 
1.179     brouard   175:   Revision 1.178  2015/01/04 09:35:48  brouard
                    176:   *** empty log message ***
                    177: 
1.178     brouard   178:   Revision 1.177  2015/01/03 18:40:56  brouard
                    179:   Summary: Still testing ilc32 on OSX
                    180: 
1.177     brouard   181:   Revision 1.176  2015/01/03 16:45:04  brouard
                    182:   *** empty log message ***
                    183: 
1.176     brouard   184:   Revision 1.175  2015/01/03 16:33:42  brouard
                    185:   *** empty log message ***
                    186: 
1.175     brouard   187:   Revision 1.174  2015/01/03 16:15:49  brouard
                    188:   Summary: Still in cross-compilation
                    189: 
1.174     brouard   190:   Revision 1.173  2015/01/03 12:06:26  brouard
                    191:   Summary: trying to detect cross-compilation
                    192: 
1.173     brouard   193:   Revision 1.172  2014/12/27 12:07:47  brouard
                    194:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    195: 
1.172     brouard   196:   Revision 1.171  2014/12/23 13:26:59  brouard
                    197:   Summary: Back from Visual C
                    198: 
                    199:   Still problem with utsname.h on Windows
                    200: 
1.171     brouard   201:   Revision 1.170  2014/12/23 11:17:12  brouard
                    202:   Summary: Cleaning some \%% back to %%
                    203: 
                    204:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    205: 
1.170     brouard   206:   Revision 1.169  2014/12/22 23:08:31  brouard
                    207:   Summary: 0.98p
                    208: 
                    209:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    210: 
1.169     brouard   211:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   212:   Summary: update
1.169     brouard   213: 
1.168     brouard   214:   Revision 1.167  2014/12/22 13:50:56  brouard
                    215:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    216: 
                    217:   Testing on Linux 64
                    218: 
1.167     brouard   219:   Revision 1.166  2014/12/22 11:40:47  brouard
                    220:   *** empty log message ***
                    221: 
1.166     brouard   222:   Revision 1.165  2014/12/16 11:20:36  brouard
                    223:   Summary: After compiling on Visual C
                    224: 
                    225:   * imach.c (Module): Merging 1.61 to 1.162
                    226: 
1.165     brouard   227:   Revision 1.164  2014/12/16 10:52:11  brouard
                    228:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    229: 
                    230:   * imach.c (Module): Merging 1.61 to 1.162
                    231: 
1.164     brouard   232:   Revision 1.163  2014/12/16 10:30:11  brouard
                    233:   * imach.c (Module): Merging 1.61 to 1.162
                    234: 
1.163     brouard   235:   Revision 1.162  2014/09/25 11:43:39  brouard
                    236:   Summary: temporary backup 0.99!
                    237: 
1.162     brouard   238:   Revision 1.1  2014/09/16 11:06:58  brouard
                    239:   Summary: With some code (wrong) for nlopt
                    240: 
                    241:   Author:
                    242: 
                    243:   Revision 1.161  2014/09/15 20:41:41  brouard
                    244:   Summary: Problem with macro SQR on Intel compiler
                    245: 
1.161     brouard   246:   Revision 1.160  2014/09/02 09:24:05  brouard
                    247:   *** empty log message ***
                    248: 
1.160     brouard   249:   Revision 1.159  2014/09/01 10:34:10  brouard
                    250:   Summary: WIN32
                    251:   Author: Brouard
                    252: 
1.159     brouard   253:   Revision 1.158  2014/08/27 17:11:51  brouard
                    254:   *** empty log message ***
                    255: 
1.158     brouard   256:   Revision 1.157  2014/08/27 16:26:55  brouard
                    257:   Summary: Preparing windows Visual studio version
                    258:   Author: Brouard
                    259: 
                    260:   In order to compile on Visual studio, time.h is now correct and time_t
                    261:   and tm struct should be used. difftime should be used but sometimes I
                    262:   just make the differences in raw time format (time(&now).
                    263:   Trying to suppress #ifdef LINUX
                    264:   Add xdg-open for __linux in order to open default browser.
                    265: 
1.157     brouard   266:   Revision 1.156  2014/08/25 20:10:10  brouard
                    267:   *** empty log message ***
                    268: 
1.156     brouard   269:   Revision 1.155  2014/08/25 18:32:34  brouard
                    270:   Summary: New compile, minor changes
                    271:   Author: Brouard
                    272: 
1.155     brouard   273:   Revision 1.154  2014/06/20 17:32:08  brouard
                    274:   Summary: Outputs now all graphs of convergence to period prevalence
                    275: 
1.154     brouard   276:   Revision 1.153  2014/06/20 16:45:46  brouard
                    277:   Summary: If 3 live state, convergence to period prevalence on same graph
                    278:   Author: Brouard
                    279: 
1.153     brouard   280:   Revision 1.152  2014/06/18 17:54:09  brouard
                    281:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    282: 
1.152     brouard   283:   Revision 1.151  2014/06/18 16:43:30  brouard
                    284:   *** empty log message ***
                    285: 
1.151     brouard   286:   Revision 1.150  2014/06/18 16:42:35  brouard
                    287:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    288:   Author: brouard
                    289: 
1.150     brouard   290:   Revision 1.149  2014/06/18 15:51:14  brouard
                    291:   Summary: Some fixes in parameter files errors
                    292:   Author: Nicolas Brouard
                    293: 
1.149     brouard   294:   Revision 1.148  2014/06/17 17:38:48  brouard
                    295:   Summary: Nothing new
                    296:   Author: Brouard
                    297: 
                    298:   Just a new packaging for OS/X version 0.98nS
                    299: 
1.148     brouard   300:   Revision 1.147  2014/06/16 10:33:11  brouard
                    301:   *** empty log message ***
                    302: 
1.147     brouard   303:   Revision 1.146  2014/06/16 10:20:28  brouard
                    304:   Summary: Merge
                    305:   Author: Brouard
                    306: 
                    307:   Merge, before building revised version.
                    308: 
1.146     brouard   309:   Revision 1.145  2014/06/10 21:23:15  brouard
                    310:   Summary: Debugging with valgrind
                    311:   Author: Nicolas Brouard
                    312: 
                    313:   Lot of changes in order to output the results with some covariates
                    314:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    315:   improve the code.
                    316:   No more memory valgrind error but a lot has to be done in order to
                    317:   continue the work of splitting the code into subroutines.
                    318:   Also, decodemodel has been improved. Tricode is still not
                    319:   optimal. nbcode should be improved. Documentation has been added in
                    320:   the source code.
                    321: 
1.144     brouard   322:   Revision 1.143  2014/01/26 09:45:38  brouard
                    323:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    324: 
                    325:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    326:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    327: 
1.143     brouard   328:   Revision 1.142  2014/01/26 03:57:36  brouard
                    329:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    330: 
                    331:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    332: 
1.142     brouard   333:   Revision 1.141  2014/01/26 02:42:01  brouard
                    334:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    335: 
1.141     brouard   336:   Revision 1.140  2011/09/02 10:37:54  brouard
                    337:   Summary: times.h is ok with mingw32 now.
                    338: 
1.140     brouard   339:   Revision 1.139  2010/06/14 07:50:17  brouard
                    340:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    341:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    342: 
1.139     brouard   343:   Revision 1.138  2010/04/30 18:19:40  brouard
                    344:   *** empty log message ***
                    345: 
1.138     brouard   346:   Revision 1.137  2010/04/29 18:11:38  brouard
                    347:   (Module): Checking covariates for more complex models
                    348:   than V1+V2. A lot of change to be done. Unstable.
                    349: 
1.137     brouard   350:   Revision 1.136  2010/04/26 20:30:53  brouard
                    351:   (Module): merging some libgsl code. Fixing computation
                    352:   of likelione (using inter/intrapolation if mle = 0) in order to
                    353:   get same likelihood as if mle=1.
                    354:   Some cleaning of code and comments added.
                    355: 
1.136     brouard   356:   Revision 1.135  2009/10/29 15:33:14  brouard
                    357:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    358: 
1.135     brouard   359:   Revision 1.134  2009/10/29 13:18:53  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.134     brouard   362:   Revision 1.133  2009/07/06 10:21:25  brouard
                    363:   just nforces
                    364: 
1.133     brouard   365:   Revision 1.132  2009/07/06 08:22:05  brouard
                    366:   Many tings
                    367: 
1.132     brouard   368:   Revision 1.131  2009/06/20 16:22:47  brouard
                    369:   Some dimensions resccaled
                    370: 
1.131     brouard   371:   Revision 1.130  2009/05/26 06:44:34  brouard
                    372:   (Module): Max Covariate is now set to 20 instead of 8. A
                    373:   lot of cleaning with variables initialized to 0. Trying to make
                    374:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    375: 
1.130     brouard   376:   Revision 1.129  2007/08/31 13:49:27  lievre
                    377:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    378: 
1.129     lievre    379:   Revision 1.128  2006/06/30 13:02:05  brouard
                    380:   (Module): Clarifications on computing e.j
                    381: 
1.128     brouard   382:   Revision 1.127  2006/04/28 18:11:50  brouard
                    383:   (Module): Yes the sum of survivors was wrong since
                    384:   imach-114 because nhstepm was no more computed in the age
                    385:   loop. Now we define nhstepma in the age loop.
                    386:   (Module): In order to speed up (in case of numerous covariates) we
                    387:   compute health expectancies (without variances) in a first step
                    388:   and then all the health expectancies with variances or standard
                    389:   deviation (needs data from the Hessian matrices) which slows the
                    390:   computation.
                    391:   In the future we should be able to stop the program is only health
                    392:   expectancies and graph are needed without standard deviations.
                    393: 
1.127     brouard   394:   Revision 1.126  2006/04/28 17:23:28  brouard
                    395:   (Module): Yes the sum of survivors was wrong since
                    396:   imach-114 because nhstepm was no more computed in the age
                    397:   loop. Now we define nhstepma in the age loop.
                    398:   Version 0.98h
                    399: 
1.126     brouard   400:   Revision 1.125  2006/04/04 15:20:31  lievre
                    401:   Errors in calculation of health expectancies. Age was not initialized.
                    402:   Forecasting file added.
                    403: 
                    404:   Revision 1.124  2006/03/22 17:13:53  lievre
                    405:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    406:   The log-likelihood is printed in the log file
                    407: 
                    408:   Revision 1.123  2006/03/20 10:52:43  brouard
                    409:   * imach.c (Module): <title> changed, corresponds to .htm file
                    410:   name. <head> headers where missing.
                    411: 
                    412:   * imach.c (Module): Weights can have a decimal point as for
                    413:   English (a comma might work with a correct LC_NUMERIC environment,
                    414:   otherwise the weight is truncated).
                    415:   Modification of warning when the covariates values are not 0 or
                    416:   1.
                    417:   Version 0.98g
                    418: 
                    419:   Revision 1.122  2006/03/20 09:45:41  brouard
                    420:   (Module): Weights can have a decimal point as for
                    421:   English (a comma might work with a correct LC_NUMERIC environment,
                    422:   otherwise the weight is truncated).
                    423:   Modification of warning when the covariates values are not 0 or
                    424:   1.
                    425:   Version 0.98g
                    426: 
                    427:   Revision 1.121  2006/03/16 17:45:01  lievre
                    428:   * imach.c (Module): Comments concerning covariates added
                    429: 
                    430:   * imach.c (Module): refinements in the computation of lli if
                    431:   status=-2 in order to have more reliable computation if stepm is
                    432:   not 1 month. Version 0.98f
                    433: 
                    434:   Revision 1.120  2006/03/16 15:10:38  lievre
                    435:   (Module): refinements in the computation of lli if
                    436:   status=-2 in order to have more reliable computation if stepm is
                    437:   not 1 month. Version 0.98f
                    438: 
                    439:   Revision 1.119  2006/03/15 17:42:26  brouard
                    440:   (Module): Bug if status = -2, the loglikelihood was
                    441:   computed as likelihood omitting the logarithm. Version O.98e
                    442: 
                    443:   Revision 1.118  2006/03/14 18:20:07  brouard
                    444:   (Module): varevsij Comments added explaining the second
                    445:   table of variances if popbased=1 .
                    446:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    447:   (Module): Function pstamp added
                    448:   (Module): Version 0.98d
                    449: 
                    450:   Revision 1.117  2006/03/14 17:16:22  brouard
                    451:   (Module): varevsij Comments added explaining the second
                    452:   table of variances if popbased=1 .
                    453:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    454:   (Module): Function pstamp added
                    455:   (Module): Version 0.98d
                    456: 
                    457:   Revision 1.116  2006/03/06 10:29:27  brouard
                    458:   (Module): Variance-covariance wrong links and
                    459:   varian-covariance of ej. is needed (Saito).
                    460: 
                    461:   Revision 1.115  2006/02/27 12:17:45  brouard
                    462:   (Module): One freematrix added in mlikeli! 0.98c
                    463: 
                    464:   Revision 1.114  2006/02/26 12:57:58  brouard
                    465:   (Module): Some improvements in processing parameter
                    466:   filename with strsep.
                    467: 
                    468:   Revision 1.113  2006/02/24 14:20:24  brouard
                    469:   (Module): Memory leaks checks with valgrind and:
                    470:   datafile was not closed, some imatrix were not freed and on matrix
                    471:   allocation too.
                    472: 
                    473:   Revision 1.112  2006/01/30 09:55:26  brouard
                    474:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    475: 
                    476:   Revision 1.111  2006/01/25 20:38:18  brouard
                    477:   (Module): Lots of cleaning and bugs added (Gompertz)
                    478:   (Module): Comments can be added in data file. Missing date values
                    479:   can be a simple dot '.'.
                    480: 
                    481:   Revision 1.110  2006/01/25 00:51:50  brouard
                    482:   (Module): Lots of cleaning and bugs added (Gompertz)
                    483: 
                    484:   Revision 1.109  2006/01/24 19:37:15  brouard
                    485:   (Module): Comments (lines starting with a #) are allowed in data.
                    486: 
                    487:   Revision 1.108  2006/01/19 18:05:42  lievre
                    488:   Gnuplot problem appeared...
                    489:   To be fixed
                    490: 
                    491:   Revision 1.107  2006/01/19 16:20:37  brouard
                    492:   Test existence of gnuplot in imach path
                    493: 
                    494:   Revision 1.106  2006/01/19 13:24:36  brouard
                    495:   Some cleaning and links added in html output
                    496: 
                    497:   Revision 1.105  2006/01/05 20:23:19  lievre
                    498:   *** empty log message ***
                    499: 
                    500:   Revision 1.104  2005/09/30 16:11:43  lievre
                    501:   (Module): sump fixed, loop imx fixed, and simplifications.
                    502:   (Module): If the status is missing at the last wave but we know
                    503:   that the person is alive, then we can code his/her status as -2
                    504:   (instead of missing=-1 in earlier versions) and his/her
                    505:   contributions to the likelihood is 1 - Prob of dying from last
                    506:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    507:   the healthy state at last known wave). Version is 0.98
                    508: 
                    509:   Revision 1.103  2005/09/30 15:54:49  lievre
                    510:   (Module): sump fixed, loop imx fixed, and simplifications.
                    511: 
                    512:   Revision 1.102  2004/09/15 17:31:30  brouard
                    513:   Add the possibility to read data file including tab characters.
                    514: 
                    515:   Revision 1.101  2004/09/15 10:38:38  brouard
                    516:   Fix on curr_time
                    517: 
                    518:   Revision 1.100  2004/07/12 18:29:06  brouard
                    519:   Add version for Mac OS X. Just define UNIX in Makefile
                    520: 
                    521:   Revision 1.99  2004/06/05 08:57:40  brouard
                    522:   *** empty log message ***
                    523: 
                    524:   Revision 1.98  2004/05/16 15:05:56  brouard
                    525:   New version 0.97 . First attempt to estimate force of mortality
                    526:   directly from the data i.e. without the need of knowing the health
                    527:   state at each age, but using a Gompertz model: log u =a + b*age .
                    528:   This is the basic analysis of mortality and should be done before any
                    529:   other analysis, in order to test if the mortality estimated from the
                    530:   cross-longitudinal survey is different from the mortality estimated
                    531:   from other sources like vital statistic data.
                    532: 
                    533:   The same imach parameter file can be used but the option for mle should be -3.
                    534: 
1.133     brouard   535:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   536:   former routines in order to include the new code within the former code.
                    537: 
                    538:   The output is very simple: only an estimate of the intercept and of
                    539:   the slope with 95% confident intervals.
                    540: 
                    541:   Current limitations:
                    542:   A) Even if you enter covariates, i.e. with the
                    543:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    544:   B) There is no computation of Life Expectancy nor Life Table.
                    545: 
                    546:   Revision 1.97  2004/02/20 13:25:42  lievre
                    547:   Version 0.96d. Population forecasting command line is (temporarily)
                    548:   suppressed.
                    549: 
                    550:   Revision 1.96  2003/07/15 15:38:55  brouard
                    551:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    552:   rewritten within the same printf. Workaround: many printfs.
                    553: 
                    554:   Revision 1.95  2003/07/08 07:54:34  brouard
                    555:   * imach.c (Repository):
                    556:   (Repository): Using imachwizard code to output a more meaningful covariance
                    557:   matrix (cov(a12,c31) instead of numbers.
                    558: 
                    559:   Revision 1.94  2003/06/27 13:00:02  brouard
                    560:   Just cleaning
                    561: 
                    562:   Revision 1.93  2003/06/25 16:33:55  brouard
                    563:   (Module): On windows (cygwin) function asctime_r doesn't
                    564:   exist so I changed back to asctime which exists.
                    565:   (Module): Version 0.96b
                    566: 
                    567:   Revision 1.92  2003/06/25 16:30:45  brouard
                    568:   (Module): On windows (cygwin) function asctime_r doesn't
                    569:   exist so I changed back to asctime which exists.
                    570: 
                    571:   Revision 1.91  2003/06/25 15:30:29  brouard
                    572:   * imach.c (Repository): Duplicated warning errors corrected.
                    573:   (Repository): Elapsed time after each iteration is now output. It
                    574:   helps to forecast when convergence will be reached. Elapsed time
                    575:   is stamped in powell.  We created a new html file for the graphs
                    576:   concerning matrix of covariance. It has extension -cov.htm.
                    577: 
                    578:   Revision 1.90  2003/06/24 12:34:15  brouard
                    579:   (Module): Some bugs corrected for windows. Also, when
                    580:   mle=-1 a template is output in file "or"mypar.txt with the design
                    581:   of the covariance matrix to be input.
                    582: 
                    583:   Revision 1.89  2003/06/24 12:30:52  brouard
                    584:   (Module): Some bugs corrected for windows. Also, when
                    585:   mle=-1 a template is output in file "or"mypar.txt with the design
                    586:   of the covariance matrix to be input.
                    587: 
                    588:   Revision 1.88  2003/06/23 17:54:56  brouard
                    589:   * 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.
                    590: 
                    591:   Revision 1.87  2003/06/18 12:26:01  brouard
                    592:   Version 0.96
                    593: 
                    594:   Revision 1.86  2003/06/17 20:04:08  brouard
                    595:   (Module): Change position of html and gnuplot routines and added
                    596:   routine fileappend.
                    597: 
                    598:   Revision 1.85  2003/06/17 13:12:43  brouard
                    599:   * imach.c (Repository): Check when date of death was earlier that
                    600:   current date of interview. It may happen when the death was just
                    601:   prior to the death. In this case, dh was negative and likelihood
                    602:   was wrong (infinity). We still send an "Error" but patch by
                    603:   assuming that the date of death was just one stepm after the
                    604:   interview.
                    605:   (Repository): Because some people have very long ID (first column)
                    606:   we changed int to long in num[] and we added a new lvector for
                    607:   memory allocation. But we also truncated to 8 characters (left
                    608:   truncation)
                    609:   (Repository): No more line truncation errors.
                    610: 
                    611:   Revision 1.84  2003/06/13 21:44:43  brouard
                    612:   * imach.c (Repository): Replace "freqsummary" at a correct
                    613:   place. It differs from routine "prevalence" which may be called
                    614:   many times. Probs is memory consuming and must be used with
                    615:   parcimony.
                    616:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    617: 
                    618:   Revision 1.83  2003/06/10 13:39:11  lievre
                    619:   *** empty log message ***
                    620: 
                    621:   Revision 1.82  2003/06/05 15:57:20  brouard
                    622:   Add log in  imach.c and  fullversion number is now printed.
                    623: 
                    624: */
                    625: /*
                    626:    Interpolated Markov Chain
                    627: 
                    628:   Short summary of the programme:
                    629:   
                    630:   This program computes Healthy Life Expectancies from
                    631:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
                    632:   first survey ("cross") where individuals from different ages are
                    633:   interviewed on their health status or degree of disability (in the
                    634:   case of a health survey which is our main interest) -2- at least a
                    635:   second wave of interviews ("longitudinal") which measure each change
                    636:   (if any) in individual health status.  Health expectancies are
                    637:   computed from the time spent in each health state according to a
                    638:   model. More health states you consider, more time is necessary to reach the
                    639:   Maximum Likelihood of the parameters involved in the model.  The
                    640:   simplest model is the multinomial logistic model where pij is the
                    641:   probability to be observed in state j at the second wave
                    642:   conditional to be observed in state i at the first wave. Therefore
                    643:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
                    644:   'age' is age and 'sex' is a covariate. If you want to have a more
                    645:   complex model than "constant and age", you should modify the program
                    646:   where the markup *Covariates have to be included here again* invites
                    647:   you to do it.  More covariates you add, slower the
                    648:   convergence.
                    649: 
                    650:   The advantage of this computer programme, compared to a simple
                    651:   multinomial logistic model, is clear when the delay between waves is not
                    652:   identical for each individual. Also, if a individual missed an
                    653:   intermediate interview, the information is lost, but taken into
                    654:   account using an interpolation or extrapolation.  
                    655: 
                    656:   hPijx is the probability to be observed in state i at age x+h
                    657:   conditional to the observed state i at age x. The delay 'h' can be
                    658:   split into an exact number (nh*stepm) of unobserved intermediate
                    659:   states. This elementary transition (by month, quarter,
                    660:   semester or year) is modelled as a multinomial logistic.  The hPx
                    661:   matrix is simply the matrix product of nh*stepm elementary matrices
                    662:   and the contribution of each individual to the likelihood is simply
                    663:   hPijx.
                    664: 
                    665:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard   666:   of the life expectancies. It also computes the period (stable) prevalence.
                    667: 
                    668: Back prevalence and projections:
                    669:  - 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)
                    670:     Computes the back prevalence limit  for any combination    of covariate values k
                    671:     at any age between ageminpar and agemaxpar and returns it in **bprlim. In the loops,
                    672:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm, **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                    673:  - hBijx Back Probability to be in state i at age x-h being in j at x
                    674:    Computes for any combination of covariates k and any age between bage and fage 
                    675:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                    676:                        oldm=oldms;savm=savms;
                    677:         - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
                    678:      Computes the transition matrix starting at age 'age' over
                    679:      'nhstepm*hstepm*stepm' months (i.e. until
                    680:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                    681:      nhstepm*hstepm matrices. Returns p3mat[i][j][h] after calling 
                    682:      p3mat[i][j][h]=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\
                    683:                                                                         1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
                    684: 
1.133     brouard   685:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    686:            Institut national d'études démographiques, Paris.
1.126     brouard   687:   This software have been partly granted by Euro-REVES, a concerted action
                    688:   from the European Union.
                    689:   It is copyrighted identically to a GNU software product, ie programme and
                    690:   software can be distributed freely for non commercial use. Latest version
                    691:   can be accessed at http://euroreves.ined.fr/imach .
                    692: 
                    693:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    694:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    695:   
                    696:   **********************************************************************/
                    697: /*
                    698:   main
                    699:   read parameterfile
                    700:   read datafile
                    701:   concatwav
                    702:   freqsummary
                    703:   if (mle >= 1)
                    704:     mlikeli
                    705:   print results files
                    706:   if mle==1 
                    707:      computes hessian
                    708:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    709:       begin-prev-date,...
                    710:   open gnuplot file
                    711:   open html file
1.145     brouard   712:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    713:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    714:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    715:     freexexit2 possible for memory heap.
                    716: 
                    717:   h Pij x                         | pij_nom  ficrestpij
                    718:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    719:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    720:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    721: 
                    722:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    723:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    724:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    725:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    726:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    727: 
1.126     brouard   728:   forecasting if prevfcast==1 prevforecast call prevalence()
                    729:   health expectancies
                    730:   Variance-covariance of DFLE
                    731:   prevalence()
                    732:    movingaverage()
                    733:   varevsij() 
                    734:   if popbased==1 varevsij(,popbased)
                    735:   total life expectancies
                    736:   Variance of period (stable) prevalence
                    737:  end
                    738: */
                    739: 
1.187     brouard   740: /* #define DEBUG */
                    741: /* #define DEBUGBRENT */
1.203     brouard   742: /* #define DEBUGLINMIN */
                    743: /* #define DEBUGHESS */
                    744: #define DEBUGHESSIJ
1.223   ! brouard   745: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan)*\/ */
1.165     brouard   746: #define POWELL /* Instead of NLOPT */
1.192     brouard   747: #define POWELLF1F3 /* Skip test */
1.186     brouard   748: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                    749: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard   750: 
                    751: #include <math.h>
                    752: #include <stdio.h>
                    753: #include <stdlib.h>
                    754: #include <string.h>
1.159     brouard   755: 
                    756: #ifdef _WIN32
                    757: #include <io.h>
1.172     brouard   758: #include <windows.h>
                    759: #include <tchar.h>
1.159     brouard   760: #else
1.126     brouard   761: #include <unistd.h>
1.159     brouard   762: #endif
1.126     brouard   763: 
                    764: #include <limits.h>
                    765: #include <sys/types.h>
1.171     brouard   766: 
                    767: #if defined(__GNUC__)
                    768: #include <sys/utsname.h> /* Doesn't work on Windows */
                    769: #endif
                    770: 
1.126     brouard   771: #include <sys/stat.h>
                    772: #include <errno.h>
1.159     brouard   773: /* extern int errno; */
1.126     brouard   774: 
1.157     brouard   775: /* #ifdef LINUX */
                    776: /* #include <time.h> */
                    777: /* #include "timeval.h" */
                    778: /* #else */
                    779: /* #include <sys/time.h> */
                    780: /* #endif */
                    781: 
1.126     brouard   782: #include <time.h>
                    783: 
1.136     brouard   784: #ifdef GSL
                    785: #include <gsl/gsl_errno.h>
                    786: #include <gsl/gsl_multimin.h>
                    787: #endif
                    788: 
1.167     brouard   789: 
1.162     brouard   790: #ifdef NLOPT
                    791: #include <nlopt.h>
                    792: typedef struct {
                    793:   double (* function)(double [] );
                    794: } myfunc_data ;
                    795: #endif
                    796: 
1.126     brouard   797: /* #include <libintl.h> */
                    798: /* #define _(String) gettext (String) */
                    799: 
1.141     brouard   800: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   801: 
                    802: #define GNUPLOTPROGRAM "gnuplot"
                    803: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    804: #define FILENAMELENGTH 132
                    805: 
                    806: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    807: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    808: 
1.144     brouard   809: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    810: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   811: 
                    812: #define NINTERVMAX 8
1.144     brouard   813: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    814: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    815: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197     brouard   816: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard   817: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                    818: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.126     brouard   819: #define MAXN 20000
1.144     brouard   820: #define YEARM 12. /**< Number of months per year */
1.218     brouard   821: /* #define AGESUP 130 */
                    822: #define AGESUP 150
                    823: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard   824: #define AGEBASE 40
1.194     brouard   825: #define AGEOVERFLOW 1.e20
1.164     brouard   826: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard   827: #ifdef _WIN32
                    828: #define DIRSEPARATOR '\\'
                    829: #define CHARSEPARATOR "\\"
                    830: #define ODIRSEPARATOR '/'
                    831: #else
1.126     brouard   832: #define DIRSEPARATOR '/'
                    833: #define CHARSEPARATOR "/"
                    834: #define ODIRSEPARATOR '\\'
                    835: #endif
                    836: 
1.223   ! brouard   837: /* $Id: imach.c,v 1.222 2016/02/17 08:14:50 brouard Exp $ */
1.126     brouard   838: /* $State: Exp $ */
1.196     brouard   839: #include "version.h"
                    840: char version[]=__IMACH_VERSION__;
1.204     brouard   841: char copyright[]="October 2015,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015";
1.223   ! brouard   842: char fullversion[]="$Revision: 1.222 $ $Date: 2016/02/17 08:14:50 $"; 
1.126     brouard   843: char strstart[80];
                    844: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   845: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard   846: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard   847: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    848: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    849: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
                    850: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
                    851: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    852: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    853: int cptcoveff=0; /* Total number of covariates to vary for printing results */
                    854: int cptcov=0; /* Working variable */
1.218     brouard   855: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.126     brouard   856: int npar=NPARMAX;
                    857: int nlstate=2; /* Number of live states */
                    858: int ndeath=1; /* Number of dead states */
1.130     brouard   859: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.223   ! brouard   860: int  nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable */ 
1.126     brouard   861: int popbased=0;
                    862: 
                    863: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard   864: int maxwav=0; /* Maxim number of waves */
                    865: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    866: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    867: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard   868:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard   869: int mle=1, weightopt=0;
1.126     brouard   870: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    871: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    872: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    873:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard   874: int countcallfunc=0;  /* Count the number of calls to func */
1.130     brouard   875: double jmean=1; /* Mean space between 2 waves */
1.145     brouard   876: double **matprod2(); /* test */
1.126     brouard   877: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    878: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard   879: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                    880: 
1.136     brouard   881: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard   882: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard   883: FILE *ficlog, *ficrespow;
1.130     brouard   884: int globpr=0; /* Global variable for printing or not */
1.126     brouard   885: double fretone; /* Only one call to likelihood */
1.130     brouard   886: long ipmx=0; /* Number of contributions */
1.126     brouard   887: double sw; /* Sum of weights */
                    888: char filerespow[FILENAMELENGTH];
                    889: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                    890: FILE *ficresilk;
                    891: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                    892: FILE *ficresprobmorprev;
                    893: FILE *fichtm, *fichtmcov; /* Html File */
                    894: FILE *ficreseij;
                    895: char filerese[FILENAMELENGTH];
                    896: FILE *ficresstdeij;
                    897: char fileresstde[FILENAMELENGTH];
                    898: FILE *ficrescveij;
                    899: char filerescve[FILENAMELENGTH];
                    900: FILE  *ficresvij;
                    901: char fileresv[FILENAMELENGTH];
                    902: FILE  *ficresvpl;
                    903: char fileresvpl[FILENAMELENGTH];
                    904: char title[MAXLINE];
1.217     brouard   905: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard   906: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                    907: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                    908: char command[FILENAMELENGTH];
                    909: int  outcmd=0;
                    910: 
1.217     brouard   911: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard   912: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard   913: char filelog[FILENAMELENGTH]; /* Log file */
                    914: char filerest[FILENAMELENGTH];
                    915: char fileregp[FILENAMELENGTH];
                    916: char popfile[FILENAMELENGTH];
                    917: 
                    918: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                    919: 
1.157     brouard   920: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                    921: /* struct timezone tzp; */
                    922: /* extern int gettimeofday(); */
                    923: struct tm tml, *gmtime(), *localtime();
                    924: 
                    925: extern time_t time();
                    926: 
                    927: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                    928: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                    929: struct tm tm;
                    930: 
1.126     brouard   931: char strcurr[80], strfor[80];
                    932: 
                    933: char *endptr;
                    934: long lval;
                    935: double dval;
                    936: 
                    937: #define NR_END 1
                    938: #define FREE_ARG char*
                    939: #define FTOL 1.0e-10
                    940: 
                    941: #define NRANSI 
                    942: #define ITMAX 200 
                    943: 
                    944: #define TOL 2.0e-4 
                    945: 
                    946: #define CGOLD 0.3819660 
                    947: #define ZEPS 1.0e-10 
                    948: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                    949: 
                    950: #define GOLD 1.618034 
                    951: #define GLIMIT 100.0 
                    952: #define TINY 1.0e-20 
                    953: 
                    954: static double maxarg1,maxarg2;
                    955: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                    956: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                    957:   
                    958: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                    959: #define rint(a) floor(a+0.5)
1.166     brouard   960: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard   961: #define mytinydouble 1.0e-16
1.166     brouard   962: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                    963: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                    964: /* static double dsqrarg; */
                    965: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard   966: static double sqrarg;
                    967: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                    968: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                    969: int agegomp= AGEGOMP;
                    970: 
                    971: int imx; 
                    972: int stepm=1;
                    973: /* Stepm, step in month: minimum step interpolation*/
                    974: 
                    975: int estepm;
                    976: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                    977: 
                    978: int m,nb;
                    979: long *num;
1.197     brouard   980: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard   981: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                    982:                   covariate for which somebody answered excluding 
                    983:                   undefined. Usually 2: 0 and 1. */
                    984: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                    985:                             covariate for which somebody answered including 
                    986:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard   987: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard   988: double **pmmij, ***probs; /* Global pointer */
1.219     brouard   989: double ***mobaverage, ***mobaverages; /* New global variable */
1.126     brouard   990: double *ageexmed,*agecens;
                    991: double dateintmean=0;
                    992: 
                    993: double *weight;
                    994: int **s; /* Status */
1.141     brouard   995: double *agedc;
1.145     brouard   996: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard   997:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard   998:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.223   ! brouard   999: double ***cotvar; /* Time varying covariate */
        !          1000: double ***cotqvar; /* Time varying quantitative covariate */
        !          1001: double **coqvar; /* Fixed quantitative covariate */
1.141     brouard  1002: double  idx; 
                   1003: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.197     brouard  1004: int *Tage;
1.145     brouard  1005: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1006: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.220     brouard  1007: int **Tvard, *Tprod, cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1008: double *lsurv, *lpop, *tpop;
                   1009: 
1.143     brouard  1010: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1011: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1012: 
                   1013: /**************** split *************************/
                   1014: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1015: {
                   1016:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1017:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1018:   */ 
                   1019:   char *ss;                            /* pointer */
1.186     brouard  1020:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1021: 
                   1022:   l1 = strlen(path );                  /* length of path */
                   1023:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1024:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1025:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1026:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1027:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1028:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1029:     /* get current working directory */
                   1030:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1031: #ifdef WIN32
                   1032:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1033: #else
                   1034:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1035: #endif
1.126     brouard  1036:       return( GLOCK_ERROR_GETCWD );
                   1037:     }
                   1038:     /* got dirc from getcwd*/
                   1039:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1040:   } else {                             /* strip directory from path */
1.126     brouard  1041:     ss++;                              /* after this, the filename */
                   1042:     l2 = strlen( ss );                 /* length of filename */
                   1043:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1044:     strcpy( name, ss );                /* save file name */
                   1045:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1046:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1047:     printf(" DIRC2 = %s \n",dirc);
                   1048:   }
                   1049:   /* We add a separator at the end of dirc if not exists */
                   1050:   l1 = strlen( dirc );                 /* length of directory */
                   1051:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1052:     dirc[l1] =  DIRSEPARATOR;
                   1053:     dirc[l1+1] = 0; 
                   1054:     printf(" DIRC3 = %s \n",dirc);
                   1055:   }
                   1056:   ss = strrchr( name, '.' );           /* find last / */
                   1057:   if (ss >0){
                   1058:     ss++;
                   1059:     strcpy(ext,ss);                    /* save extension */
                   1060:     l1= strlen( name);
                   1061:     l2= strlen(ss)+1;
                   1062:     strncpy( finame, name, l1-l2);
                   1063:     finame[l1-l2]= 0;
                   1064:   }
                   1065: 
                   1066:   return( 0 );                         /* we're done */
                   1067: }
                   1068: 
                   1069: 
                   1070: /******************************************/
                   1071: 
                   1072: void replace_back_to_slash(char *s, char*t)
                   1073: {
                   1074:   int i;
                   1075:   int lg=0;
                   1076:   i=0;
                   1077:   lg=strlen(t);
                   1078:   for(i=0; i<= lg; i++) {
                   1079:     (s[i] = t[i]);
                   1080:     if (t[i]== '\\') s[i]='/';
                   1081:   }
                   1082: }
                   1083: 
1.132     brouard  1084: char *trimbb(char *out, char *in)
1.137     brouard  1085: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1086:   char *s;
                   1087:   s=out;
                   1088:   while (*in != '\0'){
1.137     brouard  1089:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1090:       in++;
                   1091:     }
                   1092:     *out++ = *in++;
                   1093:   }
                   1094:   *out='\0';
                   1095:   return s;
                   1096: }
                   1097: 
1.187     brouard  1098: /* char *substrchaine(char *out, char *in, char *chain) */
                   1099: /* { */
                   1100: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1101: /*   char *s, *t; */
                   1102: /*   t=in;s=out; */
                   1103: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1104: /*     *out++ = *in++; */
                   1105: /*   } */
                   1106: 
                   1107: /*   /\* *in matches *chain *\/ */
                   1108: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1109: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1110: /*   } */
                   1111: /*   in--; chain--; */
                   1112: /*   while ( (*in != '\0')){ */
                   1113: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1114: /*     *out++ = *in++; */
                   1115: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1116: /*   } */
                   1117: /*   *out='\0'; */
                   1118: /*   out=s; */
                   1119: /*   return out; */
                   1120: /* } */
                   1121: char *substrchaine(char *out, char *in, char *chain)
                   1122: {
                   1123:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1124:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1125: 
                   1126:   char *strloc;
                   1127: 
                   1128:   strcpy (out, in); 
                   1129:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1130:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1131:   if(strloc != NULL){ 
                   1132:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1133:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1134:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1135:   }
                   1136:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1137:   return out;
                   1138: }
                   1139: 
                   1140: 
1.145     brouard  1141: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1142: {
1.187     brouard  1143:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1144:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187     brouard  1145:      gives blocc="abcdef" and alocc="ghi2j".
1.145     brouard  1146:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1147:   */
1.160     brouard  1148:   char *s, *t;
1.145     brouard  1149:   t=in;s=in;
                   1150:   while ((*in != occ) && (*in != '\0')){
                   1151:     *alocc++ = *in++;
                   1152:   }
                   1153:   if( *in == occ){
                   1154:     *(alocc)='\0';
                   1155:     s=++in;
                   1156:   }
                   1157:  
                   1158:   if (s == t) {/* occ not found */
                   1159:     *(alocc-(in-s))='\0';
                   1160:     in=s;
                   1161:   }
                   1162:   while ( *in != '\0'){
                   1163:     *blocc++ = *in++;
                   1164:   }
                   1165: 
                   1166:   *blocc='\0';
                   1167:   return t;
                   1168: }
1.137     brouard  1169: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1170: {
1.187     brouard  1171:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1172:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1173:      gives blocc="abcdef2ghi" and alocc="j".
                   1174:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1175:   */
                   1176:   char *s, *t;
                   1177:   t=in;s=in;
                   1178:   while (*in != '\0'){
                   1179:     while( *in == occ){
                   1180:       *blocc++ = *in++;
                   1181:       s=in;
                   1182:     }
                   1183:     *blocc++ = *in++;
                   1184:   }
                   1185:   if (s == t) /* occ not found */
                   1186:     *(blocc-(in-s))='\0';
                   1187:   else
                   1188:     *(blocc-(in-s)-1)='\0';
                   1189:   in=s;
                   1190:   while ( *in != '\0'){
                   1191:     *alocc++ = *in++;
                   1192:   }
                   1193: 
                   1194:   *alocc='\0';
                   1195:   return s;
                   1196: }
                   1197: 
1.126     brouard  1198: int nbocc(char *s, char occ)
                   1199: {
                   1200:   int i,j=0;
                   1201:   int lg=20;
                   1202:   i=0;
                   1203:   lg=strlen(s);
                   1204:   for(i=0; i<= lg; i++) {
                   1205:   if  (s[i] == occ ) j++;
                   1206:   }
                   1207:   return j;
                   1208: }
                   1209: 
1.137     brouard  1210: /* void cutv(char *u,char *v, char*t, char occ) */
                   1211: /* { */
                   1212: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1213: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1214: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1215: /*   int i,lg,j,p=0; */
                   1216: /*   i=0; */
                   1217: /*   lg=strlen(t); */
                   1218: /*   for(j=0; j<=lg-1; j++) { */
                   1219: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1220: /*   } */
1.126     brouard  1221: 
1.137     brouard  1222: /*   for(j=0; j<p; j++) { */
                   1223: /*     (u[j] = t[j]); */
                   1224: /*   } */
                   1225: /*      u[p]='\0'; */
1.126     brouard  1226: 
1.137     brouard  1227: /*    for(j=0; j<= lg; j++) { */
                   1228: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1229: /*   } */
                   1230: /* } */
1.126     brouard  1231: 
1.160     brouard  1232: #ifdef _WIN32
                   1233: char * strsep(char **pp, const char *delim)
                   1234: {
                   1235:   char *p, *q;
                   1236:          
                   1237:   if ((p = *pp) == NULL)
                   1238:     return 0;
                   1239:   if ((q = strpbrk (p, delim)) != NULL)
                   1240:   {
                   1241:     *pp = q + 1;
                   1242:     *q = '\0';
                   1243:   }
                   1244:   else
                   1245:     *pp = 0;
                   1246:   return p;
                   1247: }
                   1248: #endif
                   1249: 
1.126     brouard  1250: /********************** nrerror ********************/
                   1251: 
                   1252: void nrerror(char error_text[])
                   1253: {
                   1254:   fprintf(stderr,"ERREUR ...\n");
                   1255:   fprintf(stderr,"%s\n",error_text);
                   1256:   exit(EXIT_FAILURE);
                   1257: }
                   1258: /*********************** vector *******************/
                   1259: double *vector(int nl, int nh)
                   1260: {
                   1261:   double *v;
                   1262:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1263:   if (!v) nrerror("allocation failure in vector");
                   1264:   return v-nl+NR_END;
                   1265: }
                   1266: 
                   1267: /************************ free vector ******************/
                   1268: void free_vector(double*v, int nl, int nh)
                   1269: {
                   1270:   free((FREE_ARG)(v+nl-NR_END));
                   1271: }
                   1272: 
                   1273: /************************ivector *******************************/
                   1274: int *ivector(long nl,long nh)
                   1275: {
                   1276:   int *v;
                   1277:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1278:   if (!v) nrerror("allocation failure in ivector");
                   1279:   return v-nl+NR_END;
                   1280: }
                   1281: 
                   1282: /******************free ivector **************************/
                   1283: void free_ivector(int *v, long nl, long nh)
                   1284: {
                   1285:   free((FREE_ARG)(v+nl-NR_END));
                   1286: }
                   1287: 
                   1288: /************************lvector *******************************/
                   1289: long *lvector(long nl,long nh)
                   1290: {
                   1291:   long *v;
                   1292:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1293:   if (!v) nrerror("allocation failure in ivector");
                   1294:   return v-nl+NR_END;
                   1295: }
                   1296: 
                   1297: /******************free lvector **************************/
                   1298: void free_lvector(long *v, long nl, long nh)
                   1299: {
                   1300:   free((FREE_ARG)(v+nl-NR_END));
                   1301: }
                   1302: 
                   1303: /******************* imatrix *******************************/
                   1304: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1305:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1306: { 
                   1307:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1308:   int **m; 
                   1309:   
                   1310:   /* allocate pointers to rows */ 
                   1311:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1312:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1313:   m += NR_END; 
                   1314:   m -= nrl; 
                   1315:   
                   1316:   
                   1317:   /* allocate rows and set pointers to them */ 
                   1318:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1319:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1320:   m[nrl] += NR_END; 
                   1321:   m[nrl] -= ncl; 
                   1322:   
                   1323:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1324:   
                   1325:   /* return pointer to array of pointers to rows */ 
                   1326:   return m; 
                   1327: } 
                   1328: 
                   1329: /****************** free_imatrix *************************/
                   1330: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1331:       int **m;
                   1332:       long nch,ncl,nrh,nrl; 
                   1333:      /* free an int matrix allocated by imatrix() */ 
                   1334: { 
                   1335:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1336:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1337: } 
                   1338: 
                   1339: /******************* matrix *******************************/
                   1340: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1341: {
                   1342:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1343:   double **m;
                   1344: 
                   1345:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1346:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1347:   m += NR_END;
                   1348:   m -= nrl;
                   1349: 
                   1350:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1351:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1352:   m[nrl] += NR_END;
                   1353:   m[nrl] -= ncl;
                   1354: 
                   1355:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1356:   return m;
1.145     brouard  1357:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1358: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1359: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1360:    */
                   1361: }
                   1362: 
                   1363: /*************************free matrix ************************/
                   1364: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1365: {
                   1366:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1367:   free((FREE_ARG)(m+nrl-NR_END));
                   1368: }
                   1369: 
                   1370: /******************* ma3x *******************************/
                   1371: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1372: {
                   1373:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1374:   double ***m;
                   1375: 
                   1376:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1377:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1378:   m += NR_END;
                   1379:   m -= nrl;
                   1380: 
                   1381:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1382:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1383:   m[nrl] += NR_END;
                   1384:   m[nrl] -= ncl;
                   1385: 
                   1386:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1387: 
                   1388:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1389:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1390:   m[nrl][ncl] += NR_END;
                   1391:   m[nrl][ncl] -= nll;
                   1392:   for (j=ncl+1; j<=nch; j++) 
                   1393:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1394:   
                   1395:   for (i=nrl+1; i<=nrh; i++) {
                   1396:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1397:     for (j=ncl+1; j<=nch; j++) 
                   1398:       m[i][j]=m[i][j-1]+nlay;
                   1399:   }
                   1400:   return m; 
                   1401:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1402:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1403:   */
                   1404: }
                   1405: 
                   1406: /*************************free ma3x ************************/
                   1407: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1408: {
                   1409:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1410:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1411:   free((FREE_ARG)(m+nrl-NR_END));
                   1412: }
                   1413: 
                   1414: /*************** function subdirf ***********/
                   1415: char *subdirf(char fileres[])
                   1416: {
                   1417:   /* Caution optionfilefiname is hidden */
                   1418:   strcpy(tmpout,optionfilefiname);
                   1419:   strcat(tmpout,"/"); /* Add to the right */
                   1420:   strcat(tmpout,fileres);
                   1421:   return tmpout;
                   1422: }
                   1423: 
                   1424: /*************** function subdirf2 ***********/
                   1425: char *subdirf2(char fileres[], char *preop)
                   1426: {
                   1427:   
                   1428:   /* Caution optionfilefiname is hidden */
                   1429:   strcpy(tmpout,optionfilefiname);
                   1430:   strcat(tmpout,"/");
                   1431:   strcat(tmpout,preop);
                   1432:   strcat(tmpout,fileres);
                   1433:   return tmpout;
                   1434: }
                   1435: 
                   1436: /*************** function subdirf3 ***********/
                   1437: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1438: {
                   1439:   
                   1440:   /* Caution optionfilefiname is hidden */
                   1441:   strcpy(tmpout,optionfilefiname);
                   1442:   strcat(tmpout,"/");
                   1443:   strcat(tmpout,preop);
                   1444:   strcat(tmpout,preop2);
                   1445:   strcat(tmpout,fileres);
                   1446:   return tmpout;
                   1447: }
1.213     brouard  1448:  
                   1449: /*************** function subdirfext ***********/
                   1450: char *subdirfext(char fileres[], char *preop, char *postop)
                   1451: {
                   1452:   
                   1453:   strcpy(tmpout,preop);
                   1454:   strcat(tmpout,fileres);
                   1455:   strcat(tmpout,postop);
                   1456:   return tmpout;
                   1457: }
1.126     brouard  1458: 
1.213     brouard  1459: /*************** function subdirfext3 ***********/
                   1460: char *subdirfext3(char fileres[], char *preop, char *postop)
                   1461: {
                   1462:   
                   1463:   /* Caution optionfilefiname is hidden */
                   1464:   strcpy(tmpout,optionfilefiname);
                   1465:   strcat(tmpout,"/");
                   1466:   strcat(tmpout,preop);
                   1467:   strcat(tmpout,fileres);
                   1468:   strcat(tmpout,postop);
                   1469:   return tmpout;
                   1470: }
                   1471:  
1.162     brouard  1472: char *asc_diff_time(long time_sec, char ascdiff[])
                   1473: {
                   1474:   long sec_left, days, hours, minutes;
                   1475:   days = (time_sec) / (60*60*24);
                   1476:   sec_left = (time_sec) % (60*60*24);
                   1477:   hours = (sec_left) / (60*60) ;
                   1478:   sec_left = (sec_left) %(60*60);
                   1479:   minutes = (sec_left) /60;
                   1480:   sec_left = (sec_left) % (60);
                   1481:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1482:   return ascdiff;
                   1483: }
                   1484: 
1.126     brouard  1485: /***************** f1dim *************************/
                   1486: extern int ncom; 
                   1487: extern double *pcom,*xicom;
                   1488: extern double (*nrfunc)(double []); 
                   1489:  
                   1490: double f1dim(double x) 
                   1491: { 
                   1492:   int j; 
                   1493:   double f;
                   1494:   double *xt; 
                   1495:  
                   1496:   xt=vector(1,ncom); 
                   1497:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1498:   f=(*nrfunc)(xt); 
                   1499:   free_vector(xt,1,ncom); 
                   1500:   return f; 
                   1501: } 
                   1502: 
                   1503: /*****************brent *************************/
                   1504: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1505: {
                   1506:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1507:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1508:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1509:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1510:    * returned function value. 
                   1511:   */
1.126     brouard  1512:   int iter; 
                   1513:   double a,b,d,etemp;
1.159     brouard  1514:   double fu=0,fv,fw,fx;
1.164     brouard  1515:   double ftemp=0.;
1.126     brouard  1516:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1517:   double e=0.0; 
                   1518:  
                   1519:   a=(ax < cx ? ax : cx); 
                   1520:   b=(ax > cx ? ax : cx); 
                   1521:   x=w=v=bx; 
                   1522:   fw=fv=fx=(*f)(x); 
                   1523:   for (iter=1;iter<=ITMAX;iter++) { 
                   1524:     xm=0.5*(a+b); 
                   1525:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1526:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1527:     printf(".");fflush(stdout);
                   1528:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1529: #ifdef DEBUGBRENT
1.126     brouard  1530:     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);
                   1531:     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);
                   1532:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1533: #endif
                   1534:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1535:       *xmin=x; 
                   1536:       return fx; 
                   1537:     } 
                   1538:     ftemp=fu;
                   1539:     if (fabs(e) > tol1) { 
                   1540:       r=(x-w)*(fx-fv); 
                   1541:       q=(x-v)*(fx-fw); 
                   1542:       p=(x-v)*q-(x-w)*r; 
                   1543:       q=2.0*(q-r); 
                   1544:       if (q > 0.0) p = -p; 
                   1545:       q=fabs(q); 
                   1546:       etemp=e; 
                   1547:       e=d; 
                   1548:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
                   1549:        d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1550:       else { 
                   1551:        d=p/q; 
                   1552:        u=x+d; 
                   1553:        if (u-a < tol2 || b-u < tol2) 
                   1554:          d=SIGN(tol1,xm-x); 
                   1555:       } 
                   1556:     } else { 
                   1557:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1558:     } 
                   1559:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1560:     fu=(*f)(u); 
                   1561:     if (fu <= fx) { 
                   1562:       if (u >= x) a=x; else b=x; 
                   1563:       SHFT(v,w,x,u) 
1.183     brouard  1564:       SHFT(fv,fw,fx,fu) 
                   1565:     } else { 
                   1566:       if (u < x) a=u; else b=u; 
                   1567:       if (fu <= fw || w == x) { 
                   1568:        v=w; 
                   1569:        w=u; 
                   1570:        fv=fw; 
                   1571:        fw=fu; 
                   1572:       } else if (fu <= fv || v == x || v == w) { 
                   1573:        v=u; 
                   1574:        fv=fu; 
                   1575:       } 
                   1576:     } 
1.126     brouard  1577:   } 
                   1578:   nrerror("Too many iterations in brent"); 
                   1579:   *xmin=x; 
                   1580:   return fx; 
                   1581: } 
                   1582: 
                   1583: /****************** mnbrak ***********************/
                   1584: 
                   1585: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1586:            double (*func)(double)) 
1.183     brouard  1587: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1588: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1589: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1590: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1591:    */
1.126     brouard  1592:   double ulim,u,r,q, dum;
                   1593:   double fu; 
1.187     brouard  1594: 
                   1595:   double scale=10.;
                   1596:   int iterscale=0;
                   1597: 
                   1598:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   1599:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   1600: 
                   1601: 
                   1602:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   1603:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   1604:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   1605:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   1606:   /* } */
                   1607: 
1.126     brouard  1608:   if (*fb > *fa) { 
                   1609:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  1610:     SHFT(dum,*fb,*fa,dum) 
                   1611:   } 
1.126     brouard  1612:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1613:   *fc=(*func)(*cx); 
1.183     brouard  1614: #ifdef DEBUG
                   1615:   printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1616:   fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1617: #endif
                   1618:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1.126     brouard  1619:     r=(*bx-*ax)*(*fb-*fc); 
                   1620:     q=(*bx-*cx)*(*fb-*fa); 
                   1621:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  1622:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1623:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   1624:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  1625:       fu=(*func)(u); 
1.163     brouard  1626: #ifdef DEBUG
                   1627:       /* f(x)=A(x-u)**2+f(u) */
                   1628:       double A, fparabu; 
                   1629:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1630:       fparabu= *fa - A*(*ax-u)*(*ax-u);
                   1631:       printf("mnbrak (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf),  (*u=%.12f, fu=%.12lf, fparabu=%.12f)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu, fparabu);
                   1632:       fprintf(ficlog, "mnbrak (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf),  (*u=%.12f, fu=%.12lf, fparabu=%.12f)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu, fparabu);
1.183     brouard  1633:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   1634:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   1635:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   1636:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  1637: #endif 
1.184     brouard  1638: #ifdef MNBRAKORIGINAL
1.183     brouard  1639: #else
1.191     brouard  1640: /*       if (fu > *fc) { */
                   1641: /* #ifdef DEBUG */
                   1642: /*       printf("mnbrak4  fu > fc \n"); */
                   1643: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   1644: /* #endif */
                   1645: /*     /\* 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 *\\/  *\/ */
                   1646: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   1647: /*     dum=u; /\* Shifting c and u *\/ */
                   1648: /*     u = *cx; */
                   1649: /*     *cx = dum; */
                   1650: /*     dum = fu; */
                   1651: /*     fu = *fc; */
                   1652: /*     *fc =dum; */
                   1653: /*       } else { /\* end *\/ */
                   1654: /* #ifdef DEBUG */
                   1655: /*       printf("mnbrak3  fu < fc \n"); */
                   1656: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   1657: /* #endif */
                   1658: /*     dum=u; /\* Shifting c and u *\/ */
                   1659: /*     u = *cx; */
                   1660: /*     *cx = dum; */
                   1661: /*     dum = fu; */
                   1662: /*     fu = *fc; */
                   1663: /*     *fc =dum; */
                   1664: /*       } */
1.183     brouard  1665: #ifdef DEBUG
1.191     brouard  1666:       printf("mnbrak34  fu < or >= fc \n");
                   1667:       fprintf(ficlog, "mnbrak34 fu < fc\n");
1.183     brouard  1668: #endif
1.191     brouard  1669:       dum=u; /* Shifting c and u */
                   1670:       u = *cx;
                   1671:       *cx = dum;
                   1672:       dum = fu;
                   1673:       fu = *fc;
                   1674:       *fc =dum;
1.183     brouard  1675: #endif
1.162     brouard  1676:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  1677: #ifdef DEBUG
                   1678:       printf("mnbrak2  u after c but before ulim\n");
                   1679:       fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
                   1680: #endif
1.126     brouard  1681:       fu=(*func)(u); 
                   1682:       if (fu < *fc) { 
1.183     brouard  1683: #ifdef DEBUG
                   1684:       printf("mnbrak2  u after c but before ulim AND fu < fc\n");
                   1685:       fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
                   1686: #endif
1.126     brouard  1687:        SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
1.183     brouard  1688:        SHFT(*fb,*fc,fu,(*func)(u)) 
                   1689:       } 
1.162     brouard  1690:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  1691: #ifdef DEBUG
                   1692:       printf("mnbrak2  u outside ulim (verifying that ulim is beyond c)\n");
                   1693:       fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
                   1694: #endif
1.126     brouard  1695:       u=ulim; 
                   1696:       fu=(*func)(u); 
1.183     brouard  1697:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   1698: #ifdef DEBUG
                   1699:       printf("mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1700:       fprintf(ficlog, "mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1701: #endif
1.126     brouard  1702:       u=(*cx)+GOLD*(*cx-*bx); 
                   1703:       fu=(*func)(u); 
1.183     brouard  1704:     } /* end tests */
1.126     brouard  1705:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  1706:     SHFT(*fa,*fb,*fc,fu) 
                   1707: #ifdef DEBUG
                   1708:       printf("mnbrak2 (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf),  (*u=%.12f, fu=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu);
                   1709:       fprintf(ficlog, "mnbrak2 (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf),  (*u=%.12f, fu=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu);
                   1710: #endif
                   1711:   } /* 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  1712: } 
                   1713: 
                   1714: /*************** linmin ************************/
1.162     brouard  1715: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   1716: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   1717: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   1718: the value of func at the returned location p . This is actually all accomplished by calling the
                   1719: routines mnbrak and brent .*/
1.126     brouard  1720: int ncom; 
                   1721: double *pcom,*xicom;
                   1722: double (*nrfunc)(double []); 
                   1723:  
                   1724: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
                   1725: { 
                   1726:   double brent(double ax, double bx, double cx, 
                   1727:               double (*f)(double), double tol, double *xmin); 
                   1728:   double f1dim(double x); 
                   1729:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1730:              double *fc, double (*func)(double)); 
                   1731:   int j; 
                   1732:   double xx,xmin,bx,ax; 
                   1733:   double fx,fb,fa;
1.187     brouard  1734: 
1.203     brouard  1735: #ifdef LINMINORIGINAL
                   1736: #else
                   1737:   double scale=10., axs, xxs; /* Scale added for infinity */
                   1738: #endif
                   1739:   
1.126     brouard  1740:   ncom=n; 
                   1741:   pcom=vector(1,n); 
                   1742:   xicom=vector(1,n); 
                   1743:   nrfunc=func; 
                   1744:   for (j=1;j<=n;j++) { 
                   1745:     pcom[j]=p[j]; 
1.202     brouard  1746:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  1747:   } 
1.187     brouard  1748: 
1.203     brouard  1749: #ifdef LINMINORIGINAL
                   1750:   xx=1.;
                   1751: #else
                   1752:   axs=0.0;
                   1753:   xxs=1.;
                   1754:   do{
                   1755:     xx= xxs;
                   1756: #endif
1.187     brouard  1757:     ax=0.;
                   1758:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   1759:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   1760:     /* 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))   */
                   1761:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   1762:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   1763:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   1764:     /* 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  1765: #ifdef LINMINORIGINAL
                   1766: #else
                   1767:     if (fx != fx){
                   1768:        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   1769:        printf("|");
                   1770:        fprintf(ficlog,"|");
                   1771: #ifdef DEBUGLINMIN
                   1772:        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);
                   1773: #endif
                   1774:     }
                   1775:   }while(fx != fx);
                   1776: #endif
                   1777:   
1.191     brouard  1778: #ifdef DEBUGLINMIN
                   1779:   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  1780:   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  1781: #endif
1.187     brouard  1782:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   1783:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   1784:   /* fmin = f(p[j] + xmin * xi[j]) */
                   1785:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   1786:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  1787: #ifdef DEBUG
                   1788:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1789:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1790: #endif
1.191     brouard  1791: #ifdef DEBUGLINMIN
                   1792:   printf("linmin end ");
1.202     brouard  1793:   fprintf(ficlog,"linmin end ");
1.191     brouard  1794: #endif
1.126     brouard  1795:   for (j=1;j<=n;j++) { 
1.203     brouard  1796: #ifdef LINMINORIGINAL
                   1797:     xi[j] *= xmin; 
                   1798: #else
                   1799: #ifdef DEBUGLINMIN
                   1800:     if(xxs <1.0)
                   1801:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   1802: #endif
                   1803:     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) */
                   1804: #ifdef DEBUGLINMIN
                   1805:     if(xxs <1.0)
                   1806:       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 );
                   1807: #endif
                   1808: #endif
1.187     brouard  1809:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  1810:   } 
1.191     brouard  1811: #ifdef DEBUGLINMIN
1.203     brouard  1812:   printf("\n");
1.191     brouard  1813:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  1814:   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  1815:   for (j=1;j<=n;j++) { 
1.202     brouard  1816:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   1817:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   1818:     if(j % ncovmodel == 0){
1.191     brouard  1819:       printf("\n");
1.202     brouard  1820:       fprintf(ficlog,"\n");
                   1821:     }
1.191     brouard  1822:   }
1.203     brouard  1823: #else
1.191     brouard  1824: #endif
1.126     brouard  1825:   free_vector(xicom,1,n); 
                   1826:   free_vector(pcom,1,n); 
                   1827: } 
                   1828: 
                   1829: 
                   1830: /*************** powell ************************/
1.162     brouard  1831: /*
                   1832: Minimization of a function func of n variables. Input consists of an initial starting point
                   1833: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   1834: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   1835: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   1836: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   1837: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   1838:  */
1.126     brouard  1839: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   1840:            double (*func)(double [])) 
                   1841: { 
                   1842:   void linmin(double p[], double xi[], int n, double *fret, 
                   1843:              double (*func)(double [])); 
                   1844:   int i,ibig,j; 
                   1845:   double del,t,*pt,*ptt,*xit;
1.181     brouard  1846:   double directest;
1.126     brouard  1847:   double fp,fptt;
                   1848:   double *xits;
                   1849:   int niterf, itmp;
                   1850: 
                   1851:   pt=vector(1,n); 
                   1852:   ptt=vector(1,n); 
                   1853:   xit=vector(1,n); 
                   1854:   xits=vector(1,n); 
                   1855:   *fret=(*func)(p); 
                   1856:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  1857:   rcurr_time = time(NULL);  
1.126     brouard  1858:   for (*iter=1;;++(*iter)) { 
1.187     brouard  1859:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  1860:     ibig=0; 
                   1861:     del=0.0; 
1.157     brouard  1862:     rlast_time=rcurr_time;
                   1863:     /* (void) gettimeofday(&curr_time,&tzp); */
                   1864:     rcurr_time = time(NULL);  
                   1865:     curr_time = *localtime(&rcurr_time);
                   1866:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   1867:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   1868: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  1869:     for (i=1;i<=n;i++) {
1.126     brouard  1870:       printf(" %d %.12f",i, p[i]);
                   1871:       fprintf(ficlog," %d %.12lf",i, p[i]);
                   1872:       fprintf(ficrespow," %.12lf", p[i]);
                   1873:     }
                   1874:     printf("\n");
                   1875:     fprintf(ficlog,"\n");
                   1876:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   1877:     if(*iter <=3){
1.157     brouard  1878:       tml = *localtime(&rcurr_time);
                   1879:       strcpy(strcurr,asctime(&tml));
                   1880:       rforecast_time=rcurr_time; 
1.126     brouard  1881:       itmp = strlen(strcurr);
                   1882:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
                   1883:        strcurr[itmp-1]='\0';
1.162     brouard  1884:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  1885:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  1886:       for(niterf=10;niterf<=30;niterf+=10){
1.157     brouard  1887:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   1888:        forecast_time = *localtime(&rforecast_time);
                   1889:        strcpy(strfor,asctime(&forecast_time));
1.126     brouard  1890:        itmp = strlen(strfor);
                   1891:        if(strfor[itmp-1]=='\n')
                   1892:        strfor[itmp-1]='\0';
1.157     brouard  1893:        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);
                   1894:        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  1895:       }
                   1896:     }
1.187     brouard  1897:     for (i=1;i<=n;i++) { /* For each direction i */
                   1898:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  1899:       fptt=(*fret); 
                   1900: #ifdef DEBUG
1.203     brouard  1901:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   1902:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  1903: #endif
1.203     brouard  1904:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  1905:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.188     brouard  1906:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   1907:                                    /* Outputs are fret(new point p) p is updated and xit rescaled */
                   1908:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
                   1909:        /* because that direction will be replaced unless the gain del is small */
                   1910:        /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   1911:        /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   1912:        /* with the new direction. */
1.126     brouard  1913:        del=fabs(fptt-(*fret)); 
                   1914:        ibig=i; 
                   1915:       } 
                   1916: #ifdef DEBUG
                   1917:       printf("%d %.12e",i,(*fret));
                   1918:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   1919:       for (j=1;j<=n;j++) {
                   1920:        xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   1921:        printf(" x(%d)=%.12e",j,xit[j]);
                   1922:        fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
                   1923:       }
                   1924:       for(j=1;j<=n;j++) {
1.162     brouard  1925:        printf(" p(%d)=%.12e",j,p[j]);
                   1926:        fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  1927:       }
                   1928:       printf("\n");
                   1929:       fprintf(ficlog,"\n");
                   1930: #endif
1.187     brouard  1931:     } /* end loop on each direction i */
                   1932:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  1933:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  1934:     /* New value of last point Pn is not computed, P(n-1) */
1.182     brouard  1935:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1.188     brouard  1936:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   1937:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   1938:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   1939:       /* decreased of more than 3.84  */
                   1940:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   1941:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   1942:       /* By adding 10 parameters more the gain should be 18.31 */
                   1943: 
                   1944:       /* Starting the program with initial values given by a former maximization will simply change */
                   1945:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   1946:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   1947:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  1948: #ifdef DEBUG
                   1949:       int k[2],l;
                   1950:       k[0]=1;
                   1951:       k[1]=-1;
                   1952:       printf("Max: %.12e",(*func)(p));
                   1953:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   1954:       for (j=1;j<=n;j++) {
                   1955:        printf(" %.12e",p[j]);
                   1956:        fprintf(ficlog," %.12e",p[j]);
                   1957:       }
                   1958:       printf("\n");
                   1959:       fprintf(ficlog,"\n");
                   1960:       for(l=0;l<=1;l++) {
                   1961:        for (j=1;j<=n;j++) {
                   1962:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   1963:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1964:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1965:        }
                   1966:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1967:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1968:       }
                   1969: #endif
                   1970: 
                   1971: 
                   1972:       free_vector(xit,1,n); 
                   1973:       free_vector(xits,1,n); 
                   1974:       free_vector(ptt,1,n); 
                   1975:       free_vector(pt,1,n); 
                   1976:       return; 
1.192     brouard  1977:     } /* enough precision */ 
1.126     brouard  1978:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  1979:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  1980:       ptt[j]=2.0*p[j]-pt[j]; 
                   1981:       xit[j]=p[j]-pt[j]; 
                   1982:       pt[j]=p[j]; 
                   1983:     } 
1.181     brouard  1984:     fptt=(*func)(ptt); /* f_3 */
1.192     brouard  1985: #ifdef POWELLF1F3
                   1986: #else
1.161     brouard  1987:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  1988: #endif
1.162     brouard  1989:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  1990:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  1991:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   1992:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   1993:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.181     brouard  1994:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1.161     brouard  1995:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.183     brouard  1996: #ifdef NRCORIGINAL
                   1997:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   1998: #else
                   1999:       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  2000:       t= t- del*SQR(fp-fptt);
1.183     brouard  2001: #endif
1.202     brouard  2002:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2003: #ifdef DEBUG
1.181     brouard  2004:       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);
                   2005:       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  2006:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2007:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2008:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2009:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2010:       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);
                   2011:       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);
                   2012: #endif
1.183     brouard  2013: #ifdef POWELLORIGINAL
                   2014:       if (t < 0.0) { /* Then we use it for new direction */
                   2015: #else
1.182     brouard  2016:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.202     brouard  2017:        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  2018:         printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1.202     brouard  2019:         fprintf(ficlog,"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  2020:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2021:       } 
1.181     brouard  2022:       if (directest < 0.0) { /* Then we use it for new direction */
                   2023: #endif
1.191     brouard  2024: #ifdef DEBUGLINMIN
                   2025:        printf("Before linmin in direction P%d-P0\n",n);
                   2026:        for (j=1;j<=n;j++) { 
1.202     brouard  2027:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2028:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2029:          if(j % ncovmodel == 0){
1.191     brouard  2030:            printf("\n");
1.202     brouard  2031:            fprintf(ficlog,"\n");
                   2032:          }
1.191     brouard  2033:        }
                   2034: #endif
1.187     brouard  2035:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.191     brouard  2036: #ifdef DEBUGLINMIN
                   2037:        for (j=1;j<=n;j++) { 
                   2038:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1.202     brouard  2039:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2040:          if(j % ncovmodel == 0){
1.191     brouard  2041:            printf("\n");
1.202     brouard  2042:            fprintf(ficlog,"\n");
                   2043:          }
1.191     brouard  2044:        }
                   2045: #endif
1.126     brouard  2046:        for (j=1;j<=n;j++) { 
1.181     brouard  2047:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2048:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
1.126     brouard  2049:        }
1.181     brouard  2050:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2051:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161     brouard  2052: 
1.126     brouard  2053: #ifdef DEBUG
1.164     brouard  2054:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2055:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126     brouard  2056:        for(j=1;j<=n;j++){
                   2057:          printf(" %.12e",xit[j]);
                   2058:          fprintf(ficlog," %.12e",xit[j]);
                   2059:        }
                   2060:        printf("\n");
                   2061:        fprintf(ficlog,"\n");
                   2062: #endif
1.192     brouard  2063:       } /* end of t or directest negative */
                   2064: #ifdef POWELLF1F3
                   2065: #else
1.162     brouard  2066:     } /* end if (fptt < fp)  */
1.192     brouard  2067: #endif
                   2068:   } /* loop iteration */ 
1.126     brouard  2069: } 
                   2070: 
                   2071: /**** Prevalence limit (stable or period prevalence)  ****************/
                   2072: 
1.203     brouard  2073: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij)
1.126     brouard  2074: {
1.218     brouard  2075:   /* Computes the prevalence limit in each live state at age x and for covariate ij by left multiplying the unit
1.203     brouard  2076:      matrix by transitions matrix until convergence is reached with precision ftolpl */
1.206     brouard  2077:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2078:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2079:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2080:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2081:   /* Initial matrix pimij */
                   2082:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2083:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2084:   /*  0,                   0                  , 1} */
                   2085:   /*
                   2086:    * and after some iteration: */
                   2087:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2088:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2089:   /*  0,                   0                  , 1} */
                   2090:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2091:   /* {0.51571254859325999, 0.4842874514067399, */
                   2092:   /*  0.51326036147820708, 0.48673963852179264} */
                   2093:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2094: 
1.126     brouard  2095:   int i, ii,j,k;
1.209     brouard  2096:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2097:   /* double **matprod2(); */ /* test */
1.218     brouard  2098:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2099:   double **newm;
1.209     brouard  2100:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2101:   int ncvloop=0;
1.169     brouard  2102:   
1.209     brouard  2103:   min=vector(1,nlstate);
                   2104:   max=vector(1,nlstate);
                   2105:   meandiff=vector(1,nlstate);
                   2106: 
1.218     brouard  2107:        /* Starting with matrix unity */
1.126     brouard  2108:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2109:     for (j=1;j<=nlstate+ndeath;j++){
                   2110:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2111:     }
1.169     brouard  2112:   
                   2113:   cov[1]=1.;
                   2114:   
                   2115:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2116:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2117:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2118:     ncvloop++;
1.126     brouard  2119:     newm=savm;
                   2120:     /* Covariates have to be included here again */
1.138     brouard  2121:     cov[2]=agefin;
1.187     brouard  2122:     if(nagesqr==1)
                   2123:       cov[3]= agefin*agefin;;
1.138     brouard  2124:     for (k=1; k<=cptcovn;k++) {
1.200     brouard  2125:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.218     brouard  2126:                        /* Here comes the value of the covariate 'ij' */
1.200     brouard  2127:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
1.198     brouard  2128:       /* 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  2129:     }
1.186     brouard  2130:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  2131:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
                   2132:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
1.186     brouard  2133:     for (k=1; k<=cptcovprod;k++) /* Useless */
1.200     brouard  2134:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   2135:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
1.138     brouard  2136:     
                   2137:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2138:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2139:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2140:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2141:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2142:                /* age and covariate values of ij are in 'cov' */
1.142     brouard  2143:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2144:     
1.126     brouard  2145:     savm=oldm;
                   2146:     oldm=newm;
1.209     brouard  2147: 
                   2148:     for(j=1; j<=nlstate; j++){
                   2149:       max[j]=0.;
                   2150:       min[j]=1.;
                   2151:     }
                   2152:     for(i=1;i<=nlstate;i++){
                   2153:       sumnew=0;
                   2154:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2155:       for(j=1; j<=nlstate; j++){ 
                   2156:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2157:        max[j]=FMAX(max[j],prlim[i][j]);
                   2158:        min[j]=FMIN(min[j],prlim[i][j]);
                   2159:       }
                   2160:     }
                   2161: 
1.126     brouard  2162:     maxmax=0.;
1.209     brouard  2163:     for(j=1; j<=nlstate; j++){
                   2164:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2165:       maxmax=FMAX(maxmax,meandiff[j]);
                   2166:       /* 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  2167:     } /* j loop */
1.203     brouard  2168:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2169:     /* 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  2170:     if(maxmax < ftolpl){
1.209     brouard  2171:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2172:       free_vector(min,1,nlstate);
                   2173:       free_vector(max,1,nlstate);
                   2174:       free_vector(meandiff,1,nlstate);
1.126     brouard  2175:       return prlim;
                   2176:     }
1.169     brouard  2177:   } /* age loop */
1.208     brouard  2178:     /* After some age loop it doesn't converge */
1.209     brouard  2179:   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  2180: 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  2181:   /* 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); */
                   2182:   free_vector(min,1,nlstate);
                   2183:   free_vector(max,1,nlstate);
                   2184:   free_vector(meandiff,1,nlstate);
1.208     brouard  2185:   
1.169     brouard  2186:   return prlim; /* should not reach here */
1.126     brouard  2187: }
                   2188: 
1.217     brouard  2189: 
                   2190:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   2191: 
1.218     brouard  2192:  /* 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) */
                   2193:  /* 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) */
                   2194:  double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij)
1.217     brouard  2195: {
1.218     brouard  2196:   /* Computes the prevalence limit in each live state at age x and covariate ij by left multiplying the unit
1.217     brouard  2197:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   2198:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2199:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2200:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2201:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2202:   /* Initial matrix pimij */
                   2203:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2204:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2205:   /*  0,                   0                  , 1} */
                   2206:   /*
                   2207:    * and after some iteration: */
                   2208:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2209:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2210:   /*  0,                   0                  , 1} */
                   2211:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2212:   /* {0.51571254859325999, 0.4842874514067399, */
                   2213:   /*  0.51326036147820708, 0.48673963852179264} */
                   2214:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2215: 
                   2216:   int i, ii,j,k;
                   2217:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   2218:   /* double **matprod2(); */ /* test */
                   2219:   double **out, cov[NCOVMAX+1], **bmij();
                   2220:   double **newm;
1.218     brouard  2221:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   2222:   double        **oldm, **savm;  /* for use */
                   2223: 
1.217     brouard  2224:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   2225:   int ncvloop=0;
                   2226:   
                   2227:   min=vector(1,nlstate);
                   2228:   max=vector(1,nlstate);
                   2229:   meandiff=vector(1,nlstate);
                   2230: 
1.218     brouard  2231:        dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   2232:        oldm=oldms; savm=savms;
                   2233: 
                   2234:        /* Starting with matrix unity */
                   2235:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2236:                for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  2237:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2238:     }
                   2239:   
                   2240:   cov[1]=1.;
                   2241:   
                   2242:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2243:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  2244:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   2245:   for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  2246:     ncvloop++;
1.218     brouard  2247:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   2248:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  2249:     /* Covariates have to be included here again */
                   2250:     cov[2]=agefin;
                   2251:     if(nagesqr==1)
                   2252:       cov[3]= agefin*agefin;;
                   2253:     for (k=1; k<=cptcovn;k++) {
                   2254:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
                   2255:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   2256:       /* 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])]); */
                   2257:     }
                   2258:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   2259:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
                   2260:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
                   2261:     for (k=1; k<=cptcovprod;k++) /* Useless */
                   2262:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   2263:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2264:     
                   2265:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2266:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2267:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   2268:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2269:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2270:                /* ij should be linked to the correct index of cov */
                   2271:                /* age and covariate values ij are in 'cov', but we need to pass
                   2272:                 * ij for the observed prevalence at age and status and covariate
                   2273:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   2274:                 */
                   2275:     /* 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 *\/ */
                   2276:     /* 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 *\/ */
                   2277:     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  2278:     savm=oldm;
                   2279:     oldm=newm;
                   2280:     for(j=1; j<=nlstate; j++){
                   2281:       max[j]=0.;
                   2282:       min[j]=1.;
                   2283:     }
                   2284:     for(j=1; j<=nlstate; j++){ 
                   2285:       for(i=1;i<=nlstate;i++){
1.218     brouard  2286:                                /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   2287:                                bprlim[i][j]= newm[i][j];
                   2288:                                max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   2289:                                min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  2290:       }
                   2291:     }
1.218     brouard  2292:                
1.217     brouard  2293:     maxmax=0.;
                   2294:     for(i=1; i<=nlstate; i++){
                   2295:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column */
                   2296:       maxmax=FMAX(maxmax,meandiff[i]);
                   2297:       /* 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); */
                   2298:     } /* j loop */
                   2299:     *ncvyear= -( (int)age- (int)agefin);
1.218     brouard  2300:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear);*/
1.217     brouard  2301:     if(maxmax < ftolpl){
1.220     brouard  2302:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  2303:       free_vector(min,1,nlstate);
                   2304:       free_vector(max,1,nlstate);
                   2305:       free_vector(meandiff,1,nlstate);
                   2306:       return bprlim;
                   2307:     }
                   2308:   } /* age loop */
                   2309:     /* After some age loop it doesn't converge */
                   2310:   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\
                   2311: 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);
                   2312:   /* 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); */
                   2313:   free_vector(min,1,nlstate);
                   2314:   free_vector(max,1,nlstate);
                   2315:   free_vector(meandiff,1,nlstate);
                   2316:   
                   2317:   return bprlim; /* should not reach here */
                   2318: }
                   2319: 
1.126     brouard  2320: /*************** transition probabilities ***************/ 
                   2321: 
                   2322: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   2323: {
1.138     brouard  2324:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2325:      computes the probability to be observed in state j being in state i by appying the
                   2326:      model to the ncovmodel covariates (including constant and age).
                   2327:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2328:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2329:      ncth covariate in the global vector x is given by the formula:
                   2330:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2331:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2332:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2333:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2334:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2335:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2336:   */
                   2337:   double s1, lnpijopii;
1.126     brouard  2338:   /*double t34;*/
1.164     brouard  2339:   int i,j, nc, ii, jj;
1.126     brouard  2340: 
1.223   ! brouard  2341:   for(i=1; i<= nlstate; i++){
        !          2342:     for(j=1; j<i;j++){
        !          2343:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
        !          2344:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
        !          2345:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
        !          2346:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
        !          2347:       }
        !          2348:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
        !          2349:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
        !          2350:     }
        !          2351:     for(j=i+1; j<=nlstate+ndeath;j++){
        !          2352:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
        !          2353:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
        !          2354:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
        !          2355:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
        !          2356:       }
        !          2357:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
        !          2358:     }
        !          2359:   }
1.218     brouard  2360:   
1.223   ! brouard  2361:   for(i=1; i<= nlstate; i++){
        !          2362:     s1=0;
        !          2363:     for(j=1; j<i; j++){
        !          2364:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
        !          2365:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
        !          2366:     }
        !          2367:     for(j=i+1; j<=nlstate+ndeath; j++){
        !          2368:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
        !          2369:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
        !          2370:     }
        !          2371:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
        !          2372:     ps[i][i]=1./(s1+1.);
        !          2373:     /* Computing other pijs */
        !          2374:     for(j=1; j<i; j++)
        !          2375:       ps[i][j]= exp(ps[i][j])*ps[i][i];
        !          2376:     for(j=i+1; j<=nlstate+ndeath; j++)
        !          2377:       ps[i][j]= exp(ps[i][j])*ps[i][i];
        !          2378:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
        !          2379:   } /* end i */
1.218     brouard  2380:   
1.223   ! brouard  2381:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
        !          2382:     for(jj=1; jj<= nlstate+ndeath; jj++){
        !          2383:       ps[ii][jj]=0;
        !          2384:       ps[ii][ii]=1;
        !          2385:     }
        !          2386:   }
1.218     brouard  2387:   
                   2388:   
1.223   ! brouard  2389:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
        !          2390:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
        !          2391:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
        !          2392:   /*   } */
        !          2393:   /*   printf("\n "); */
        !          2394:   /* } */
        !          2395:   /* printf("\n ");printf("%lf ",cov[2]);*/
        !          2396:   /*
        !          2397:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  2398:                goto end;*/
1.223   ! brouard  2399:   return ps;
1.126     brouard  2400: }
                   2401: 
1.218     brouard  2402: /*************** backward transition probabilities ***************/ 
                   2403: 
                   2404:  /* 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 ) */
                   2405: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   2406:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   2407: {
1.222     brouard  2408:   /* Computes the backward probability at age agefin and covariate ij
                   2409:    * and returns in **ps as well as **bmij.
                   2410:    */
1.218     brouard  2411:   int i, ii, j,k;
1.222     brouard  2412:   
                   2413:   double **out, **pmij();
                   2414:   double sumnew=0.;
1.218     brouard  2415:   double agefin;
1.222     brouard  2416:   
                   2417:   double **dnewm, **dsavm, **doldm;
                   2418:   double **bbmij;
                   2419:   
1.218     brouard  2420:   doldm=ddoldms; /* global pointers */
1.222     brouard  2421:   dnewm=ddnewms;
                   2422:   dsavm=ddsavms;
                   2423:   
                   2424:   agefin=cov[2];
                   2425:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
                   2426:      the observed prevalence (with this covariate ij) */
                   2427:   dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate);
                   2428:   /* We do have the matrix Px in savm  and we need pij */
                   2429:   for (j=1;j<=nlstate+ndeath;j++){
                   2430:     sumnew=0.; /* w1 p11 + w2 p21 only on live states */
                   2431:     for (ii=1;ii<=nlstate;ii++){
                   2432:       sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij];
                   2433:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
                   2434:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   2435:       if(sumnew >= 1.e-10){
                   2436:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
                   2437:        /*      doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
                   2438:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
                   2439:        /*      doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
                   2440:        /* }else */
                   2441:        doldm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   2442:       }else{
                   2443:        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);
                   2444:       }
                   2445:     } /*End ii */
                   2446:   } /* End j, At the end doldm is diag[1/(w_1p1i+w_2 p2i)] */
                   2447:   /* left Product of this diag matrix by dsavm=Px (newm=dsavm*doldm) */
                   2448:   bbmij=matprod2(dnewm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, doldm); /* Bug Valgrind */
                   2449:   /* dsavm=doldm; /\* dsavm is now diag [1/(w_1p1i+w_2 p2i)] but can be overwritten*\/ */
                   2450:   /* doldm=dnewm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
                   2451:   /* dnewm=dsavm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
                   2452:   /* left Product of this matrix by diag matrix of prevalences (savm) */
                   2453:   for (j=1;j<=nlstate+ndeath;j++){
                   2454:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   2455:       dsavm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij] : 0.0);
                   2456:     }
                   2457:   } /* End j, At the end oldm is diag[1/(w_1p1i+w_2 p2i)] */
                   2458:   ps=matprod2(doldm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dnewm); /* Bug Valgrind */
                   2459:   /* newm or out is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
                   2460:   /* end bmij */
                   2461:   return ps; 
1.218     brouard  2462: }
1.217     brouard  2463: /*************** transition probabilities ***************/ 
                   2464: 
1.218     brouard  2465: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  2466: {
                   2467:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2468:      computes the probability to be observed in state j being in state i by appying the
                   2469:      model to the ncovmodel covariates (including constant and age).
                   2470:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2471:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2472:      ncth covariate in the global vector x is given by the formula:
                   2473:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2474:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2475:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2476:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2477:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2478:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2479:   */
                   2480:   double s1, lnpijopii;
                   2481:   /*double t34;*/
                   2482:   int i,j, nc, ii, jj;
                   2483: 
1.218     brouard  2484:        for(i=1; i<= nlstate; i++){
                   2485:                for(j=1; j<i;j++){
                   2486:                        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2487:                                /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2488:                                lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2489:                                /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2490:                        }
                   2491:                        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2492:                        /*      printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2493:                }
                   2494:                for(j=i+1; j<=nlstate+ndeath;j++){
                   2495:                        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2496:                                /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2497:                                lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2498:                                /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   2499:                        }
                   2500:                        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2501:                }
                   2502:        }
                   2503:        
                   2504:        for(i=1; i<= nlstate; i++){
                   2505:                s1=0;
                   2506:                for(j=1; j<i; j++){
                   2507:                        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2508:                        /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2509:                }
                   2510:                for(j=i+1; j<=nlstate+ndeath; j++){
                   2511:                        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2512:                        /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2513:                }
                   2514:                /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   2515:                ps[i][i]=1./(s1+1.);
                   2516:                /* Computing other pijs */
                   2517:                for(j=1; j<i; j++)
                   2518:                        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2519:                for(j=i+1; j<=nlstate+ndeath; j++)
                   2520:                        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2521:                /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2522:        } /* end i */
                   2523:        
                   2524:        for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2525:                for(jj=1; jj<= nlstate+ndeath; jj++){
                   2526:                        ps[ii][jj]=0;
                   2527:                        ps[ii][ii]=1;
                   2528:                }
                   2529:        }
                   2530:        /* Added for backcast */ /* Transposed matrix too */
                   2531:        for(jj=1; jj<= nlstate+ndeath; jj++){
                   2532:                s1=0.;
                   2533:                for(ii=1; ii<= nlstate+ndeath; ii++){
                   2534:                        s1+=ps[ii][jj];
                   2535:                }
                   2536:                for(ii=1; ii<= nlstate; ii++){
                   2537:                        ps[ii][jj]=ps[ii][jj]/s1;
                   2538:                }
                   2539:        }
                   2540:        /* Transposition */
                   2541:        for(jj=1; jj<= nlstate+ndeath; jj++){
                   2542:                for(ii=jj; ii<= nlstate+ndeath; ii++){
                   2543:                        s1=ps[ii][jj];
                   2544:                        ps[ii][jj]=ps[jj][ii];
                   2545:                        ps[jj][ii]=s1;
                   2546:                }
                   2547:        }
                   2548:        /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2549:        /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2550:        /*      printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2551:        /*   } */
                   2552:        /*   printf("\n "); */
                   2553:        /* } */
                   2554:        /* printf("\n ");printf("%lf ",cov[2]);*/
                   2555:        /*
                   2556:                for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   2557:                goto end;*/
                   2558:        return ps;
1.217     brouard  2559: }
                   2560: 
                   2561: 
1.126     brouard  2562: /**************** Product of 2 matrices ******************/
                   2563: 
1.145     brouard  2564: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  2565: {
                   2566:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   2567:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   2568:   /* in, b, out are matrice of pointers which should have been initialized 
                   2569:      before: only the contents of out is modified. The function returns
                   2570:      a pointer to pointers identical to out */
1.145     brouard  2571:   int i, j, k;
1.126     brouard  2572:   for(i=nrl; i<= nrh; i++)
1.145     brouard  2573:     for(k=ncolol; k<=ncoloh; k++){
                   2574:       out[i][k]=0.;
                   2575:       for(j=ncl; j<=nch; j++)
                   2576:        out[i][k] +=in[i][j]*b[j][k];
                   2577:     }
1.126     brouard  2578:   return out;
                   2579: }
                   2580: 
                   2581: 
                   2582: /************* Higher Matrix Product ***************/
                   2583: 
                   2584: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
                   2585: {
1.218     brouard  2586:   /* Computes the transition matrix starting at age 'age' and combination of covariate values corresponding to ij over 
1.126     brouard  2587:      'nhstepm*hstepm*stepm' months (i.e. until
                   2588:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   2589:      nhstepm*hstepm matrices. 
                   2590:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   2591:      (typically every 2 years instead of every month which is too big 
                   2592:      for the memory).
                   2593:      Model is determined by parameters x and covariates have to be 
                   2594:      included manually here. 
                   2595: 
                   2596:      */
                   2597: 
                   2598:   int i, j, d, h, k;
1.131     brouard  2599:   double **out, cov[NCOVMAX+1];
1.126     brouard  2600:   double **newm;
1.187     brouard  2601:   double agexact;
1.214     brouard  2602:   double agebegin, ageend;
1.126     brouard  2603: 
                   2604:   /* Hstepm could be zero and should return the unit matrix */
                   2605:   for (i=1;i<=nlstate+ndeath;i++)
                   2606:     for (j=1;j<=nlstate+ndeath;j++){
                   2607:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   2608:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   2609:     }
                   2610:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2611:   for(h=1; h <=nhstepm; h++){
                   2612:     for(d=1; d <=hstepm; d++){
                   2613:       newm=savm;
                   2614:       /* Covariates have to be included here again */
                   2615:       cov[1]=1.;
1.214     brouard  2616:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  2617:       cov[2]=agexact;
                   2618:       if(nagesqr==1)
1.218     brouard  2619:                                cov[3]= agexact*agexact;
1.131     brouard  2620:       for (k=1; k<=cptcovn;k++) 
1.218     brouard  2621:                                cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   2622:                        /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.186     brouard  2623:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
1.218     brouard  2624:                                /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   2625:                                cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2626:                        /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
1.145     brouard  2627:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.218     brouard  2628:                                cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2629:                        /* 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  2630: 
                   2631: 
                   2632:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   2633:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.218     brouard  2634:                        /* right multiplication of oldm by the current matrix */
1.126     brouard  2635:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   2636:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  2637:       /* if((int)age == 70){ */
                   2638:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   2639:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   2640:       /*         printf("%d pmmij ",i); */
                   2641:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2642:       /*           printf("%f ",pmmij[i][j]); */
                   2643:       /*         } */
                   2644:       /*         printf(" oldm "); */
                   2645:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2646:       /*           printf("%f ",oldm[i][j]); */
                   2647:       /*         } */
                   2648:       /*         printf("\n"); */
                   2649:       /*       } */
                   2650:       /* } */
1.126     brouard  2651:       savm=oldm;
                   2652:       oldm=newm;
                   2653:     }
                   2654:     for(i=1; i<=nlstate+ndeath; i++)
                   2655:       for(j=1;j<=nlstate+ndeath;j++) {
1.218     brouard  2656:                                po[i][j][h]=newm[i][j];
                   2657:                                /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  2658:       }
1.128     brouard  2659:     /*printf("h=%d ",h);*/
1.126     brouard  2660:   } /* end h */
1.218     brouard  2661:        /*     printf("\n H=%d \n",h); */
1.126     brouard  2662:   return po;
                   2663: }
                   2664: 
1.217     brouard  2665: /************* Higher Back Matrix Product ***************/
1.218     brouard  2666: /* 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  2667: double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, double ***prevacurrent, int nlstate, int stepm, int ij )
1.217     brouard  2668: {
1.218     brouard  2669:   /* Computes the transition matrix starting at age 'age' over
1.217     brouard  2670:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  2671:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   2672:      nhstepm*hstepm matrices.
                   2673:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   2674:      (typically every 2 years instead of every month which is too big
1.217     brouard  2675:      for the memory).
1.218     brouard  2676:      Model is determined by parameters x and covariates have to be
                   2677:      included manually here.
1.217     brouard  2678: 
1.222     brouard  2679:   */
1.217     brouard  2680: 
                   2681:   int i, j, d, h, k;
                   2682:   double **out, cov[NCOVMAX+1];
                   2683:   double **newm;
                   2684:   double agexact;
                   2685:   double agebegin, ageend;
1.222     brouard  2686:   double **oldm, **savm;
1.217     brouard  2687: 
1.222     brouard  2688:   oldm=oldms;savm=savms;
1.217     brouard  2689:   /* Hstepm could be zero and should return the unit matrix */
                   2690:   for (i=1;i<=nlstate+ndeath;i++)
                   2691:     for (j=1;j<=nlstate+ndeath;j++){
                   2692:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   2693:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   2694:     }
                   2695:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2696:   for(h=1; h <=nhstepm; h++){
                   2697:     for(d=1; d <=hstepm; d++){
                   2698:       newm=savm;
                   2699:       /* Covariates have to be included here again */
                   2700:       cov[1]=1.;
                   2701:       agexact=age-((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
                   2702:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
                   2703:       cov[2]=agexact;
                   2704:       if(nagesqr==1)
1.222     brouard  2705:        cov[3]= agexact*agexact;
1.218     brouard  2706:       for (k=1; k<=cptcovn;k++)
1.222     brouard  2707:        cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   2708:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.217     brouard  2709:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
1.222     brouard  2710:        /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   2711:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2712:       /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
1.217     brouard  2713:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.222     brouard  2714:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2715:       /* 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  2716:                        
                   2717:                        
1.217     brouard  2718:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   2719:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.218     brouard  2720:       /* Careful transposed matrix */
1.222     brouard  2721:       /* age is in cov[2] */
1.218     brouard  2722:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  2723:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  2724:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.222     brouard  2725:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
1.217     brouard  2726:       /* if((int)age == 70){ */
                   2727:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   2728:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   2729:       /*         printf("%d pmmij ",i); */
                   2730:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2731:       /*           printf("%f ",pmmij[i][j]); */
                   2732:       /*         } */
                   2733:       /*         printf(" oldm "); */
                   2734:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   2735:       /*           printf("%f ",oldm[i][j]); */
                   2736:       /*         } */
                   2737:       /*         printf("\n"); */
                   2738:       /*       } */
                   2739:       /* } */
                   2740:       savm=oldm;
                   2741:       oldm=newm;
                   2742:     }
                   2743:     for(i=1; i<=nlstate+ndeath; i++)
                   2744:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  2745:        po[i][j][h]=newm[i][j];
                   2746:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.217     brouard  2747:       }
                   2748:     /*printf("h=%d ",h);*/
                   2749:   } /* end h */
1.222     brouard  2750:   /*     printf("\n H=%d \n",h); */
1.217     brouard  2751:   return po;
                   2752: }
                   2753: 
                   2754: 
1.162     brouard  2755: #ifdef NLOPT
                   2756:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   2757:   double fret;
                   2758:   double *xt;
                   2759:   int j;
                   2760:   myfunc_data *d2 = (myfunc_data *) pd;
                   2761: /* xt = (p1-1); */
                   2762:   xt=vector(1,n); 
                   2763:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   2764: 
                   2765:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   2766:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   2767:   printf("Function = %.12lf ",fret);
                   2768:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   2769:   printf("\n");
                   2770:  free_vector(xt,1,n);
                   2771:   return fret;
                   2772: }
                   2773: #endif
1.126     brouard  2774: 
                   2775: /*************** log-likelihood *************/
                   2776: double func( double *x)
                   2777: {
                   2778:   int i, ii, j, k, mi, d, kk;
1.223   ! brouard  2779:        int ioffset;
1.131     brouard  2780:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2781:   double **out;
                   2782:   double sw; /* Sum of weights */
                   2783:   double lli; /* Individual log likelihood */
                   2784:   int s1, s2;
1.223   ! brouard  2785:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate */
1.126     brouard  2786:   double bbh, survp;
                   2787:   long ipmx;
1.187     brouard  2788:   double agexact;
1.126     brouard  2789:   /*extern weight */
                   2790:   /* We are differentiating ll according to initial status */
                   2791:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2792:   /*for(i=1;i<imx;i++) 
                   2793:     printf(" %d\n",s[4][i]);
                   2794:   */
1.162     brouard  2795: 
                   2796:   ++countcallfunc;
                   2797: 
1.126     brouard  2798:   cov[1]=1.;
                   2799: 
                   2800:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2801: 
                   2802:   if(mle==1){
                   2803:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138     brouard  2804:       /* Computes the values of the ncovmodel covariates of the model
1.223   ! brouard  2805:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
1.138     brouard  2806:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   2807:         to be observed in j being in i according to the model.
                   2808:        */
1.223   ! brouard  2809:       ioffset=2+nagesqr;
1.145     brouard  2810:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1.223   ! brouard  2811:         cov[++ioffset]=covar[Tvar[k]][i];
        !          2812:       }
        !          2813:       for(iqv=1; iqv <= nqv; iqv++){ /* Varying quantitatives covariates */
        !          2814:        /* cov[2+nagesqr+cptcovn+iqv]=varq[mw[mi+1][i]][iqv][i]; */
1.145     brouard  2815:       }
1.223   ! brouard  2816: 
1.137     brouard  2817:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.138     brouard  2818:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
1.137     brouard  2819:         has been calculated etc */
1.223   ! brouard  2820:       /* For an individual i, wav[i] gives the number of effective waves */
        !          2821:       /* We compute the contribution to Likelihood of each effective transition
        !          2822:         mw[mi][i] is real wave of the mi th effectve wave */
        !          2823:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
        !          2824:        s2=s[mw[mi+1][i]][i];
        !          2825:        And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
        !          2826:        But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
        !          2827:        meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
        !          2828:       */
1.126     brouard  2829:       for(mi=1; mi<= wav[i]-1; mi++){
1.223   ! brouard  2830:        for(itv=1; itv <= ntv; itv++){ /* Varying dummy covariates */
        !          2831:          cov[++ioffset]=cotvar[mw[mi+1][i]][itv][i];
        !          2832:        }
        !          2833:        for(iqtv=1; iqtv <= nqtv; iqtv++){ /* Varying quantitatives covariates */
        !          2834:          /* cov[2+nagesqr+cptcovn+nqv+ntv+iqtv]=varq[mw[mi+1][i]][iqtv][i]; */
        !          2835:        }
        !          2836:        ioffset=2+nagesqr+cptcovn+nqv+ntv+nqtv;
1.126     brouard  2837:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2838:          for (j=1;j<=nlstate+ndeath;j++){
                   2839:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2840:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2841:          }
                   2842:        for(d=0; d<dh[mi][i]; d++){
                   2843:          newm=savm;
1.187     brouard  2844:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2845:          cov[2]=agexact;
                   2846:          if(nagesqr==1)
1.223   ! brouard  2847:            cov[3]= agexact*agexact;  /* Should be changed here */
1.126     brouard  2848:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2849:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.126     brouard  2850:          }
                   2851:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2852:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2853:          savm=oldm;
                   2854:          oldm=newm;
                   2855:        } /* end mult */
                   2856:       
                   2857:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   2858:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   2859:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   2860:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   2861:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   2862:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   2863:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   2864:         * probability in order to take into account the bias as a fraction of the way
                   2865:         * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   2866:         * -stepm/2 to stepm/2 .
                   2867:         * For stepm=1 the results are the same as for previous versions of Imach.
                   2868:         * For stepm > 1 the results are less biased than in previous versions. 
                   2869:         */
                   2870:        s1=s[mw[mi][i]][i];
                   2871:        s2=s[mw[mi+1][i]][i];
                   2872:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2873:        /* bias bh is positive if real duration
                   2874:         * is higher than the multiple of stepm and negative otherwise.
                   2875:         */
                   2876:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   2877:        if( s2 > nlstate){ 
                   2878:          /* i.e. if s2 is a death state and if the date of death is known 
                   2879:             then the contribution to the likelihood is the probability to 
                   2880:             die between last step unit time and current  step unit time, 
                   2881:             which is also equal to probability to die before dh 
                   2882:             minus probability to die before dh-stepm . 
                   2883:             In version up to 0.92 likelihood was computed
                   2884:        as if date of death was unknown. Death was treated as any other
                   2885:        health state: the date of the interview describes the actual state
                   2886:        and not the date of a change in health state. The former idea was
                   2887:        to consider that at each interview the state was recorded
                   2888:        (healthy, disable or death) and IMaCh was corrected; but when we
                   2889:        introduced the exact date of death then we should have modified
                   2890:        the contribution of an exact death to the likelihood. This new
                   2891:        contribution is smaller and very dependent of the step unit
                   2892:        stepm. It is no more the probability to die between last interview
                   2893:        and month of death but the probability to survive from last
                   2894:        interview up to one month before death multiplied by the
                   2895:        probability to die within a month. Thanks to Chris
                   2896:        Jackson for correcting this bug.  Former versions increased
                   2897:        mortality artificially. The bad side is that we add another loop
                   2898:        which slows down the processing. The difference can be up to 10%
                   2899:        lower mortality.
                   2900:          */
1.183     brouard  2901:        /* If, at the beginning of the maximization mostly, the
                   2902:           cumulative probability or probability to be dead is
                   2903:           constant (ie = 1) over time d, the difference is equal to
                   2904:           0.  out[s1][3] = savm[s1][3]: probability, being at state
                   2905:           s1 at precedent wave, to be dead a month before current
                   2906:           wave is equal to probability, being at state s1 at
                   2907:           precedent wave, to be dead at mont of the current
                   2908:           wave. Then the observed probability (that this person died)
                   2909:           is null according to current estimated parameter. In fact,
                   2910:           it should be very low but not zero otherwise the log go to
                   2911:           infinity.
                   2912:        */
                   2913: /* #ifdef INFINITYORIGINAL */
                   2914: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2915: /* #else */
                   2916: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   2917: /*         lli=log(mytinydouble); */
                   2918: /*       else */
                   2919: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2920: /* #endif */
1.216     brouard  2921:          lli=log(out[s1][s2] - savm[s1][s2]);
                   2922:          
                   2923:        } else if  ( s2==-1 ) { /* alive */
1.126     brouard  2924:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   2925:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2926:          /*survp += out[s1][j]; */
                   2927:          lli= log(survp);
                   2928:        }
                   2929:        else if  (s2==-4) { 
                   2930:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   2931:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2932:          lli= log(survp); 
                   2933:        } 
                   2934:        else if  (s2==-5) { 
                   2935:          for (j=1,survp=0. ; j<=2; j++)  
                   2936:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2937:          lli= log(survp); 
                   2938:        } 
                   2939:        else{
                   2940:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2941:          /*  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 */
                   2942:        } 
                   2943:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   2944:        /*if(lli ==000.0)*/
                   2945:        /*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); */
                   2946:        ipmx +=1;
                   2947:        sw += weight[i];
                   2948:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.183     brouard  2949:        /* if (lli < log(mytinydouble)){ */
                   2950:        /*   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); */
                   2951:        /*   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]); */
                   2952:        /* } */
1.126     brouard  2953:       } /* end of wave */
                   2954:     } /* end of individual */
                   2955:   }  else if(mle==2){
                   2956:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2957:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2958:       for(mi=1; mi<= wav[i]-1; mi++){
                   2959:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2960:          for (j=1;j<=nlstate+ndeath;j++){
                   2961:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2962:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2963:          }
                   2964:        for(d=0; d<=dh[mi][i]; d++){
                   2965:          newm=savm;
1.187     brouard  2966:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2967:          cov[2]=agexact;
                   2968:          if(nagesqr==1)
                   2969:            cov[3]= agexact*agexact;
1.126     brouard  2970:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2971:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2972:          }
                   2973:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2974:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2975:          savm=oldm;
                   2976:          oldm=newm;
                   2977:        } /* end mult */
                   2978:       
                   2979:        s1=s[mw[mi][i]][i];
                   2980:        s2=s[mw[mi+1][i]][i];
                   2981:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2982:        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 */
                   2983:        ipmx +=1;
                   2984:        sw += weight[i];
                   2985:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2986:       } /* end of wave */
                   2987:     } /* end of individual */
                   2988:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   2989:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2990:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2991:       for(mi=1; mi<= wav[i]-1; mi++){
                   2992:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2993:          for (j=1;j<=nlstate+ndeath;j++){
                   2994:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2995:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2996:          }
                   2997:        for(d=0; d<dh[mi][i]; d++){
                   2998:          newm=savm;
1.187     brouard  2999:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3000:          cov[2]=agexact;
                   3001:          if(nagesqr==1)
                   3002:            cov[3]= agexact*agexact;
1.126     brouard  3003:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  3004:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  3005:          }
                   3006:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3007:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3008:          savm=oldm;
                   3009:          oldm=newm;
                   3010:        } /* end mult */
                   3011:       
                   3012:        s1=s[mw[mi][i]][i];
                   3013:        s2=s[mw[mi+1][i]][i];
                   3014:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3015:        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 */
                   3016:        ipmx +=1;
                   3017:        sw += weight[i];
                   3018:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3019:       } /* end of wave */
                   3020:     } /* end of individual */
                   3021:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   3022:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  3023:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  3024:       for(mi=1; mi<= wav[i]-1; mi++){
                   3025:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3026:          for (j=1;j<=nlstate+ndeath;j++){
                   3027:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3028:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3029:          }
                   3030:        for(d=0; d<dh[mi][i]; d++){
                   3031:          newm=savm;
1.187     brouard  3032:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3033:          cov[2]=agexact;
                   3034:          if(nagesqr==1)
                   3035:            cov[3]= agexact*agexact;
1.126     brouard  3036:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  3037:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  3038:          }
                   3039:        
                   3040:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3041:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3042:          savm=oldm;
                   3043:          oldm=newm;
                   3044:        } /* end mult */
                   3045:       
                   3046:        s1=s[mw[mi][i]][i];
                   3047:        s2=s[mw[mi+1][i]][i];
                   3048:        if( s2 > nlstate){ 
                   3049:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3050:        } else if  ( s2==-1 ) { /* alive */
                   3051:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3052:            survp += out[s1][j];
                   3053:          lli= log(survp);
1.126     brouard  3054:        }else{
                   3055:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3056:        }
                   3057:        ipmx +=1;
                   3058:        sw += weight[i];
                   3059:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3060: /*     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]); */
                   3061:       } /* end of wave */
                   3062:     } /* end of individual */
                   3063:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   3064:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  3065:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  3066:       for(mi=1; mi<= wav[i]-1; mi++){
                   3067:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3068:          for (j=1;j<=nlstate+ndeath;j++){
                   3069:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3070:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3071:          }
                   3072:        for(d=0; d<dh[mi][i]; d++){
                   3073:          newm=savm;
1.187     brouard  3074:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3075:          cov[2]=agexact;
                   3076:          if(nagesqr==1)
                   3077:            cov[3]= agexact*agexact;
1.126     brouard  3078:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  3079:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  3080:          }
                   3081:        
                   3082:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3083:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3084:          savm=oldm;
                   3085:          oldm=newm;
                   3086:        } /* end mult */
                   3087:       
                   3088:        s1=s[mw[mi][i]][i];
                   3089:        s2=s[mw[mi+1][i]][i];
                   3090:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3091:        ipmx +=1;
                   3092:        sw += weight[i];
                   3093:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3094:        /*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]);*/
                   3095:       } /* end of wave */
                   3096:     } /* end of individual */
                   3097:   } /* End of if */
                   3098:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3099:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3100:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3101:   return -l;
                   3102: }
                   3103: 
                   3104: /*************** log-likelihood *************/
                   3105: double funcone( double *x)
                   3106: {
                   3107:   /* Same as likeli but slower because of a lot of printf and if */
                   3108:   int i, ii, j, k, mi, d, kk;
1.131     brouard  3109:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  3110:   double **out;
                   3111:   double lli; /* Individual log likelihood */
                   3112:   double llt;
                   3113:   int s1, s2;
                   3114:   double bbh, survp;
1.187     brouard  3115:   double agexact;
1.214     brouard  3116:   double agebegin, ageend;
1.126     brouard  3117:   /*extern weight */
                   3118:   /* We are differentiating ll according to initial status */
                   3119:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3120:   /*for(i=1;i<imx;i++) 
                   3121:     printf(" %d\n",s[4][i]);
                   3122:   */
                   3123:   cov[1]=1.;
                   3124: 
                   3125:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   3126: 
                   3127:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  3128:     for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  3129:     for(mi=1; mi<= wav[i]-1; mi++){
                   3130:       for (ii=1;ii<=nlstate+ndeath;ii++)
                   3131:        for (j=1;j<=nlstate+ndeath;j++){
                   3132:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3133:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3134:        }
1.214     brouard  3135:       
                   3136:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   3137:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   3138:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
                   3139:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   3140:          and mw[mi+1][i]. dh depends on stepm.*/
1.126     brouard  3141:        newm=savm;
1.187     brouard  3142:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3143:        cov[2]=agexact;
                   3144:        if(nagesqr==1)
                   3145:          cov[3]= agexact*agexact;
1.126     brouard  3146:        for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  3147:          cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  3148:        }
1.187     brouard  3149: 
1.145     brouard  3150:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126     brouard  3151:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3152:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145     brouard  3153:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   3154:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126     brouard  3155:        savm=oldm;
                   3156:        oldm=newm;
                   3157:       } /* end mult */
                   3158:       
                   3159:       s1=s[mw[mi][i]][i];
                   3160:       s2=s[mw[mi+1][i]][i];
1.217     brouard  3161:       /* if(s2==-1){ */
                   3162:       /*       printf(" s1=%d, s2=%d i=%d \n", s1, s2, i); */
                   3163:       /*       /\* exit(1); *\/ */
                   3164:       /* } */
1.126     brouard  3165:       bbh=(double)bh[mi][i]/(double)stepm; 
                   3166:       /* bias is positive if real duration
                   3167:        * is higher than the multiple of stepm and negative otherwise.
                   3168:        */
                   3169:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
                   3170:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3171:       } else if  ( s2==-1 ) { /* alive */
1.126     brouard  3172:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   3173:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3174:        lli= log(survp);
                   3175:       }else if (mle==1){
                   3176:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3177:       } else if(mle==2){
                   3178:        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 */
                   3179:       } else if(mle==3){  /* exponential inter-extrapolation */
                   3180:        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 */
                   3181:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
                   3182:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  3183:       } else{  /* mle=0 back to 1 */
                   3184:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3185:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  3186:       } /* End of if */
                   3187:       ipmx +=1;
                   3188:       sw += weight[i];
                   3189:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  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]); */
1.126     brouard  3191:       if(globpr){
1.214     brouard  3192:        fprintf(ficresilk,"%9ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %11.6f %8.4f %8.3f\
1.126     brouard  3193:  %11.6f %11.6f %11.6f ", \
1.214     brouard  3194:                num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
1.126     brouard  3195:                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
                   3196:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   3197:          llt +=ll[k]*gipmx/gsw;
                   3198:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   3199:        }
                   3200:        fprintf(ficresilk," %10.6f\n", -llt);
                   3201:       }
                   3202:     } /* end of wave */
                   3203:   } /* end of individual */
                   3204:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3205:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3206:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3207:   if(globpr==0){ /* First time we count the contributions and weights */
                   3208:     gipmx=ipmx;
                   3209:     gsw=sw;
                   3210:   }
                   3211:   return -l;
                   3212: }
                   3213: 
                   3214: 
                   3215: /*************** function likelione ***********/
                   3216: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   3217: {
                   3218:   /* This routine should help understanding what is done with 
                   3219:      the selection of individuals/waves and
                   3220:      to check the exact contribution to the likelihood.
                   3221:      Plotting could be done.
                   3222:    */
                   3223:   int k;
                   3224: 
                   3225:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  3226:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  3227:     strcat(fileresilk,fileresu);
1.126     brouard  3228:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   3229:       printf("Problem with resultfile: %s\n", fileresilk);
                   3230:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   3231:     }
1.214     brouard  3232:     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");
                   3233:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  3234:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   3235:     for(k=1; k<=nlstate; k++) 
                   3236:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   3237:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   3238:   }
                   3239: 
                   3240:   *fretone=(*funcone)(p);
                   3241:   if(*globpri !=0){
                   3242:     fclose(ficresilk);
1.205     brouard  3243:     if (mle ==0)
                   3244:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   3245:     else if(mle >=1)
                   3246:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   3247:     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  3248:     
1.208     brouard  3249:       
                   3250:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  3251:       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  3252: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   3253:     }
1.207     brouard  3254:     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  3255: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3256:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  3257: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3258:     fflush(fichtm);
1.205     brouard  3259:   }
1.126     brouard  3260:   return;
                   3261: }
                   3262: 
                   3263: 
                   3264: /*********** Maximum Likelihood Estimation ***************/
                   3265: 
                   3266: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   3267: {
1.165     brouard  3268:   int i,j, iter=0;
1.126     brouard  3269:   double **xi;
                   3270:   double fret;
                   3271:   double fretone; /* Only one call to likelihood */
                   3272:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  3273: 
                   3274: #ifdef NLOPT
                   3275:   int creturn;
                   3276:   nlopt_opt opt;
                   3277:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   3278:   double *lb;
                   3279:   double minf; /* the minimum objective value, upon return */
                   3280:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   3281:   myfunc_data dinst, *d = &dinst;
                   3282: #endif
                   3283: 
                   3284: 
1.126     brouard  3285:   xi=matrix(1,npar,1,npar);
                   3286:   for (i=1;i<=npar;i++)
                   3287:     for (j=1;j<=npar;j++)
                   3288:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   3289:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  3290:   strcpy(filerespow,"POW_"); 
1.126     brouard  3291:   strcat(filerespow,fileres);
                   3292:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   3293:     printf("Problem with resultfile: %s\n", filerespow);
                   3294:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   3295:   }
                   3296:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   3297:   for (i=1;i<=nlstate;i++)
                   3298:     for(j=1;j<=nlstate+ndeath;j++)
                   3299:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   3300:   fprintf(ficrespow,"\n");
1.162     brouard  3301: #ifdef POWELL
1.126     brouard  3302:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  3303: #endif
1.126     brouard  3304: 
1.162     brouard  3305: #ifdef NLOPT
                   3306: #ifdef NEWUOA
                   3307:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   3308: #else
                   3309:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   3310: #endif
                   3311:   lb=vector(0,npar-1);
                   3312:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   3313:   nlopt_set_lower_bounds(opt, lb);
                   3314:   nlopt_set_initial_step1(opt, 0.1);
                   3315:   
                   3316:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   3317:   d->function = func;
                   3318:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   3319:   nlopt_set_min_objective(opt, myfunc, d);
                   3320:   nlopt_set_xtol_rel(opt, ftol);
                   3321:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   3322:     printf("nlopt failed! %d\n",creturn); 
                   3323:   }
                   3324:   else {
                   3325:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   3326:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   3327:     iter=1; /* not equal */
                   3328:   }
                   3329:   nlopt_destroy(opt);
                   3330: #endif
1.126     brouard  3331:   free_matrix(xi,1,npar,1,npar);
                   3332:   fclose(ficrespow);
1.203     brouard  3333:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   3334:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  3335:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  3336: 
                   3337: }
                   3338: 
                   3339: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  3340: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  3341: {
                   3342:   double  **a,**y,*x,pd;
1.203     brouard  3343:   /* double **hess; */
1.164     brouard  3344:   int i, j;
1.126     brouard  3345:   int *indx;
                   3346: 
                   3347:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  3348:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  3349:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   3350:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   3351:   double gompertz(double p[]);
1.203     brouard  3352:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  3353: 
                   3354:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   3355:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   3356:   for (i=1;i<=npar;i++){
1.203     brouard  3357:     printf("%d-",i);fflush(stdout);
                   3358:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  3359:    
                   3360:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   3361:     
                   3362:     /*  printf(" %f ",p[i]);
                   3363:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   3364:   }
                   3365:   
                   3366:   for (i=1;i<=npar;i++) {
                   3367:     for (j=1;j<=npar;j++)  {
                   3368:       if (j>i) { 
1.203     brouard  3369:        printf(".%d-%d",i,j);fflush(stdout);
                   3370:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   3371:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  3372:        
                   3373:        hess[j][i]=hess[i][j];    
                   3374:        /*printf(" %lf ",hess[i][j]);*/
                   3375:       }
                   3376:     }
                   3377:   }
                   3378:   printf("\n");
                   3379:   fprintf(ficlog,"\n");
                   3380: 
                   3381:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   3382:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   3383:   
                   3384:   a=matrix(1,npar,1,npar);
                   3385:   y=matrix(1,npar,1,npar);
                   3386:   x=vector(1,npar);
                   3387:   indx=ivector(1,npar);
                   3388:   for (i=1;i<=npar;i++)
                   3389:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   3390:   ludcmp(a,npar,indx,&pd);
                   3391: 
                   3392:   for (j=1;j<=npar;j++) {
                   3393:     for (i=1;i<=npar;i++) x[i]=0;
                   3394:     x[j]=1;
                   3395:     lubksb(a,npar,indx,x);
                   3396:     for (i=1;i<=npar;i++){ 
                   3397:       matcov[i][j]=x[i];
                   3398:     }
                   3399:   }
                   3400: 
                   3401:   printf("\n#Hessian matrix#\n");
                   3402:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   3403:   for (i=1;i<=npar;i++) { 
                   3404:     for (j=1;j<=npar;j++) { 
1.203     brouard  3405:       printf("%.6e ",hess[i][j]);
                   3406:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  3407:     }
                   3408:     printf("\n");
                   3409:     fprintf(ficlog,"\n");
                   3410:   }
                   3411: 
1.203     brouard  3412:   /* printf("\n#Covariance matrix#\n"); */
                   3413:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   3414:   /* for (i=1;i<=npar;i++) {  */
                   3415:   /*   for (j=1;j<=npar;j++) {  */
                   3416:   /*     printf("%.6e ",matcov[i][j]); */
                   3417:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   3418:   /*   } */
                   3419:   /*   printf("\n"); */
                   3420:   /*   fprintf(ficlog,"\n"); */
                   3421:   /* } */
                   3422: 
1.126     brouard  3423:   /* Recompute Inverse */
1.203     brouard  3424:   /* for (i=1;i<=npar;i++) */
                   3425:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   3426:   /* ludcmp(a,npar,indx,&pd); */
                   3427: 
                   3428:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   3429: 
                   3430:   /* for (j=1;j<=npar;j++) { */
                   3431:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   3432:   /*   x[j]=1; */
                   3433:   /*   lubksb(a,npar,indx,x); */
                   3434:   /*   for (i=1;i<=npar;i++){  */
                   3435:   /*     y[i][j]=x[i]; */
                   3436:   /*     printf("%.3e ",y[i][j]); */
                   3437:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   3438:   /*   } */
                   3439:   /*   printf("\n"); */
                   3440:   /*   fprintf(ficlog,"\n"); */
                   3441:   /* } */
                   3442: 
                   3443:   /* Verifying the inverse matrix */
                   3444: #ifdef DEBUGHESS
                   3445:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  3446: 
1.203     brouard  3447:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   3448:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  3449: 
                   3450:   for (j=1;j<=npar;j++) {
                   3451:     for (i=1;i<=npar;i++){ 
1.203     brouard  3452:       printf("%.2f ",y[i][j]);
                   3453:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  3454:     }
                   3455:     printf("\n");
                   3456:     fprintf(ficlog,"\n");
                   3457:   }
1.203     brouard  3458: #endif
1.126     brouard  3459: 
                   3460:   free_matrix(a,1,npar,1,npar);
                   3461:   free_matrix(y,1,npar,1,npar);
                   3462:   free_vector(x,1,npar);
                   3463:   free_ivector(indx,1,npar);
1.203     brouard  3464:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  3465: 
                   3466: 
                   3467: }
                   3468: 
                   3469: /*************** hessian matrix ****************/
                   3470: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  3471: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  3472:   int i;
                   3473:   int l=1, lmax=20;
1.203     brouard  3474:   double k1,k2, res, fx;
1.132     brouard  3475:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  3476:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   3477:   int k=0,kmax=10;
                   3478:   double l1;
                   3479: 
                   3480:   fx=func(x);
                   3481:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  3482:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  3483:     l1=pow(10,l);
                   3484:     delts=delt;
                   3485:     for(k=1 ; k <kmax; k=k+1){
                   3486:       delt = delta*(l1*k);
                   3487:       p2[theta]=x[theta] +delt;
1.145     brouard  3488:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  3489:       p2[theta]=x[theta]-delt;
                   3490:       k2=func(p2)-fx;
                   3491:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  3492:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  3493:       
1.203     brouard  3494: #ifdef DEBUGHESSII
1.126     brouard  3495:       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);
                   3496:       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);
                   3497: #endif
                   3498:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   3499:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   3500:        k=kmax;
                   3501:       }
                   3502:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  3503:        k=kmax; l=lmax*10;
1.126     brouard  3504:       }
                   3505:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   3506:        delts=delt;
                   3507:       }
1.203     brouard  3508:     } /* End loop k */
1.126     brouard  3509:   }
                   3510:   delti[theta]=delts;
                   3511:   return res; 
                   3512:   
                   3513: }
                   3514: 
1.203     brouard  3515: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  3516: {
                   3517:   int i;
1.164     brouard  3518:   int l=1, lmax=20;
1.126     brouard  3519:   double k1,k2,k3,k4,res,fx;
1.132     brouard  3520:   double p2[MAXPARM+1];
1.203     brouard  3521:   int k, kmax=1;
                   3522:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  3523: 
                   3524:   int firstime=0;
1.203     brouard  3525:   
1.126     brouard  3526:   fx=func(x);
1.203     brouard  3527:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  3528:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  3529:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   3530:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  3531:     k1=func(p2)-fx;
                   3532:   
1.203     brouard  3533:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   3534:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  3535:     k2=func(p2)-fx;
                   3536:   
1.203     brouard  3537:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   3538:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  3539:     k3=func(p2)-fx;
                   3540:   
1.203     brouard  3541:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   3542:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  3543:     k4=func(p2)-fx;
1.203     brouard  3544:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   3545:     if(k1*k2*k3*k4 <0.){
1.208     brouard  3546:       firstime=1;
1.203     brouard  3547:       kmax=kmax+10;
1.208     brouard  3548:     }
                   3549:     if(kmax >=10 || firstime ==1){
1.218     brouard  3550:       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);
                   3551:       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  3552:       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);
                   3553:       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);
                   3554:     }
                   3555: #ifdef DEBUGHESSIJ
                   3556:     v1=hess[thetai][thetai];
                   3557:     v2=hess[thetaj][thetaj];
                   3558:     cv12=res;
                   3559:     /* Computing eigen value of Hessian matrix */
                   3560:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   3561:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   3562:     if ((lc2 <0) || (lc1 <0) ){
                   3563:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   3564:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   3565:       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);
                   3566:       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);
                   3567:     }
1.126     brouard  3568: #endif
                   3569:   }
                   3570:   return res;
                   3571: }
                   3572: 
1.203     brouard  3573:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   3574: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   3575: /* { */
                   3576: /*   int i; */
                   3577: /*   int l=1, lmax=20; */
                   3578: /*   double k1,k2,k3,k4,res,fx; */
                   3579: /*   double p2[MAXPARM+1]; */
                   3580: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   3581: /*   int k=0,kmax=10; */
                   3582: /*   double l1; */
                   3583:   
                   3584: /*   fx=func(x); */
                   3585: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   3586: /*     l1=pow(10,l); */
                   3587: /*     delts=delt; */
                   3588: /*     for(k=1 ; k <kmax; k=k+1){ */
                   3589: /*       delt = delti*(l1*k); */
                   3590: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   3591: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   3592: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   3593: /*       k1=func(p2)-fx; */
                   3594:       
                   3595: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   3596: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   3597: /*       k2=func(p2)-fx; */
                   3598:       
                   3599: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   3600: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   3601: /*       k3=func(p2)-fx; */
                   3602:       
                   3603: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   3604: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   3605: /*       k4=func(p2)-fx; */
                   3606: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   3607: /* #ifdef DEBUGHESSIJ */
                   3608: /*       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); */
                   3609: /*       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); */
                   3610: /* #endif */
                   3611: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   3612: /*     k=kmax; */
                   3613: /*       } */
                   3614: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   3615: /*     k=kmax; l=lmax*10; */
                   3616: /*       } */
                   3617: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   3618: /*     delts=delt; */
                   3619: /*       } */
                   3620: /*     } /\* End loop k *\/ */
                   3621: /*   } */
                   3622: /*   delti[theta]=delts; */
                   3623: /*   return res;  */
                   3624: /* } */
                   3625: 
                   3626: 
1.126     brouard  3627: /************** Inverse of matrix **************/
                   3628: void ludcmp(double **a, int n, int *indx, double *d) 
                   3629: { 
                   3630:   int i,imax,j,k; 
                   3631:   double big,dum,sum,temp; 
                   3632:   double *vv; 
                   3633:  
                   3634:   vv=vector(1,n); 
                   3635:   *d=1.0; 
                   3636:   for (i=1;i<=n;i++) { 
                   3637:     big=0.0; 
                   3638:     for (j=1;j<=n;j++) 
                   3639:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   3640:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   3641:     vv[i]=1.0/big; 
                   3642:   } 
                   3643:   for (j=1;j<=n;j++) { 
                   3644:     for (i=1;i<j;i++) { 
                   3645:       sum=a[i][j]; 
                   3646:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   3647:       a[i][j]=sum; 
                   3648:     } 
                   3649:     big=0.0; 
                   3650:     for (i=j;i<=n;i++) { 
                   3651:       sum=a[i][j]; 
                   3652:       for (k=1;k<j;k++) 
                   3653:        sum -= a[i][k]*a[k][j]; 
                   3654:       a[i][j]=sum; 
                   3655:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   3656:        big=dum; 
                   3657:        imax=i; 
                   3658:       } 
                   3659:     } 
                   3660:     if (j != imax) { 
                   3661:       for (k=1;k<=n;k++) { 
                   3662:        dum=a[imax][k]; 
                   3663:        a[imax][k]=a[j][k]; 
                   3664:        a[j][k]=dum; 
                   3665:       } 
                   3666:       *d = -(*d); 
                   3667:       vv[imax]=vv[j]; 
                   3668:     } 
                   3669:     indx[j]=imax; 
                   3670:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   3671:     if (j != n) { 
                   3672:       dum=1.0/(a[j][j]); 
                   3673:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   3674:     } 
                   3675:   } 
                   3676:   free_vector(vv,1,n);  /* Doesn't work */
                   3677: ;
                   3678: } 
                   3679: 
                   3680: void lubksb(double **a, int n, int *indx, double b[]) 
                   3681: { 
                   3682:   int i,ii=0,ip,j; 
                   3683:   double sum; 
                   3684:  
                   3685:   for (i=1;i<=n;i++) { 
                   3686:     ip=indx[i]; 
                   3687:     sum=b[ip]; 
                   3688:     b[ip]=b[i]; 
                   3689:     if (ii) 
                   3690:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   3691:     else if (sum) ii=i; 
                   3692:     b[i]=sum; 
                   3693:   } 
                   3694:   for (i=n;i>=1;i--) { 
                   3695:     sum=b[i]; 
                   3696:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   3697:     b[i]=sum/a[i][i]; 
                   3698:   } 
                   3699: } 
                   3700: 
                   3701: void pstamp(FILE *fichier)
                   3702: {
1.196     brouard  3703:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  3704: }
                   3705: 
                   3706: /************ Frequencies ********************/
1.220     brouard  3707:  void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
                   3708:                                                                         int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[],  \
                   3709:                                                                         int firstpass,  int lastpass, int stepm, int weightopt, char model[])
                   3710:  {  /* Some frequencies */
                   3711:   
                   3712:         int i, m, jk, j1, bool, z1,j;
                   3713:         int iind=0, iage=0;
                   3714:         int mi; /* Effective wave */
                   3715:         int first;
                   3716:         double ***freq; /* Frequencies */
                   3717:         double *pp, **prop, *posprop, *pospropt;
                   3718:         double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   3719:         char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   3720:         double agebegin, ageend;
                   3721:     
                   3722:         pp=vector(1,nlstate);
                   3723:         prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
                   3724:         posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   3725:         pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   3726:         /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   3727:         strcpy(fileresp,"P_");
                   3728:         strcat(fileresp,fileresu);
                   3729:         /*strcat(fileresphtm,fileresu);*/
                   3730:         if((ficresp=fopen(fileresp,"w"))==NULL) {
                   3731:                 printf("Problem with prevalence resultfile: %s\n", fileresp);
                   3732:                 fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   3733:                 exit(0);
                   3734:         }
1.214     brouard  3735: 
1.220     brouard  3736:         strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   3737:         if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   3738:                 printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   3739:                 fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   3740:                 fflush(ficlog);
                   3741:                 exit(70); 
                   3742:         }
                   3743:         else{
                   3744:                 fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.214     brouard  3745: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   3746: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.220     brouard  3747:                                                 fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   3748:         }
                   3749:         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  3750:     
1.220     brouard  3751:         strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   3752:         if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   3753:                 printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   3754:                 fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   3755:                 fflush(ficlog);
                   3756:                 exit(70); 
                   3757:         }
                   3758:         else{
                   3759:                 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  3760: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   3761: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.220     brouard  3762:                                                 fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   3763:         }
                   3764:         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  3765: 
1.220     brouard  3766:         freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+3+AGEMARGE);
                   3767:         j1=0;
1.126     brouard  3768:   
1.220     brouard  3769:         j=cptcoveff;
                   3770:         if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   3771: 
                   3772:         first=1;
                   3773: 
                   3774:         /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   3775:                        reference=low_education V1=0,V2=0
                   3776:                        med_educ                V1=1 V2=0, 
                   3777:                        high_educ               V1=0 V2=1
                   3778:                        Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcoveff 
                   3779:         */
1.126     brouard  3780: 
1.220     brouard  3781:         for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){ /* Loop on covariates combination */
                   3782:                 posproptt=0.;
                   3783:                 /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   3784:                         scanf("%d", i);*/
                   3785:                 for (i=-5; i<=nlstate+ndeath; i++)  
                   3786:                         for (jk=-5; jk<=nlstate+ndeath; jk++)  
                   3787:                                 for(m=iagemin; m <= iagemax+3; m++)
                   3788:                                         freq[i][jk][m]=0;
                   3789:       
                   3790:                 for (i=1; i<=nlstate; i++)  {
                   3791:                         for(m=iagemin; m <= iagemax+3; m++)
                   3792:                                 prop[i][m]=0;
                   3793:                         posprop[i]=0;
                   3794:                         pospropt[i]=0;
                   3795:                 }
                   3796:       
                   3797:                 dateintsum=0;
                   3798:                 k2cpt=0;
1.126     brouard  3799: 
1.220     brouard  3800:                 for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   3801:                         bool=1;
                   3802:                         if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   3803:                                 for (z1=1; z1<=cptcoveff; z1++) {      
                   3804:                                         if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
                   3805:                                                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
                   3806:                                                 bool=0;
                   3807:                                                 /* 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  3808:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   3809:                 j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
1.220     brouard  3810:                                                 /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   3811:                                         } 
                   3812:                                 } /* end z1 */
                   3813:                         } /* cptcovn > 0 */
                   3814: 
                   3815:                         if (bool==1){
                   3816:                                 /* for(m=firstpass; m<=lastpass; m++){ */
                   3817:                                 for(mi=1; mi<wav[iind];mi++){
                   3818:                                         m=mw[mi][iind];
                   3819:                                         /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   3820:                                                        and mw[mi+1][iind]. dh depends on stepm. */
                   3821:                                         agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   3822:                                         ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   3823:                                         if(m >=firstpass && m <=lastpass){
                   3824:                                                 k2=anint[m][iind]+(mint[m][iind]/12.);
                   3825:                                                 /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   3826:                                                 if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   3827:                                                 if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   3828:                                                 if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   3829:                                                         prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   3830:                                                 if (m<lastpass) {
                   3831:                                                         /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   3832:                                                         /*   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]); */
                   3833:                                                         if(s[m][iind]==-1)
                   3834:                                                                 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.));
                   3835:                                                         freq[s[m][iind]][s[m+1][iind]][(int)agev[m][iind]] += weight[iind]; /* At age of beginning of transition, where status is known */
                   3836:                                                         /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   3837:                                                         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 */
                   3838:                                                 }
                   3839:                                         }  
                   3840:                                         if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99)) {
                   3841:                                                 dateintsum=dateintsum+k2;
                   3842:                                                 k2cpt++;
                   3843:                                                 /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
                   3844:                                         }
                   3845:                                         /*}*/
                   3846:                                 } /* end m */
                   3847:                         } /* end bool */
                   3848:                 } /* end iind = 1 to imx */
                   3849:        /* prop[s][age] is feeded for any initial and valid live state as well as
                   3850:                                        freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   3851: 
                   3852: 
                   3853:                 /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   3854:                 pstamp(ficresp);
                   3855:                 if  (cptcovn>0) {
                   3856:                         fprintf(ficresp, "\n#********** Variable "); 
                   3857:                         fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   3858:                         fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   3859:                         for (z1=1; z1<=cptcoveff; z1++){
                   3860:                                 fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   3861:                                 fprintf(ficresphtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   3862:                                 fprintf(ficresphtmfr, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   3863:                         }
                   3864:                         fprintf(ficresp, "**********\n#");
                   3865:                         fprintf(ficresphtm, "**********</h3>\n");
                   3866:                         fprintf(ficresphtmfr, "**********</h3>\n");
                   3867:                         fprintf(ficlog, "\n#********** Variable "); 
                   3868:                         for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   3869:                         fprintf(ficlog, "**********\n");
                   3870:                 }
                   3871:                 fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
                   3872:                 for(i=1; i<=nlstate;i++) {
                   3873:                         fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
                   3874:                         fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   3875:                 }
                   3876:                 fprintf(ficresp, "\n");
                   3877:                 fprintf(ficresphtm, "\n");
                   3878:       
                   3879:                 /* Header of frequency table by age */
                   3880:                 fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   3881:                 fprintf(ficresphtmfr,"<th>Age</th> ");
                   3882:                 for(jk=-1; jk <=nlstate+ndeath; jk++){
                   3883:                         for(m=-1; m <=nlstate+ndeath; m++){
                   3884:                                 if(jk!=0 && m!=0)
                   3885:                                         fprintf(ficresphtmfr,"<th>%d%d</th> ",jk,m);
                   3886:                         }
                   3887:                 }
                   3888:                 fprintf(ficresphtmfr, "\n");
1.214     brouard  3889:       
1.220     brouard  3890:                 /* For each age */
                   3891:                 for(iage=iagemin; iage <= iagemax+3; iage++){
                   3892:                         fprintf(ficresphtm,"<tr>");
                   3893:                         if(iage==iagemax+1){
                   3894:                                 fprintf(ficlog,"1");
                   3895:                                 fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   3896:                         }else if(iage==iagemax+2){
                   3897:                                 fprintf(ficlog,"0");
                   3898:                                 fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   3899:                         }else if(iage==iagemax+3){
                   3900:                                 fprintf(ficlog,"Total");
                   3901:                                 fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   3902:                         }else{
                   3903:                                 if(first==1){
                   3904:                                         first=0;
                   3905:                                         printf("See log file for details...\n");
                   3906:                                 }
                   3907:                                 fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   3908:                                 fprintf(ficlog,"Age %d", iage);
                   3909:                         }
                   3910:                         for(jk=1; jk <=nlstate ; jk++){
                   3911:                                 for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   3912:                                         pp[jk] += freq[jk][m][iage]; 
                   3913:                         }
                   3914:                         for(jk=1; jk <=nlstate ; jk++){
                   3915:                                 for(m=-1, pos=0; m <=0 ; m++)
                   3916:                                         pos += freq[jk][m][iage];
                   3917:                                 if(pp[jk]>=1.e-10){
                   3918:                                         if(first==1){
                   3919:                                                 printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   3920:                                         }
                   3921:                                         fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   3922:                                 }else{
                   3923:                                         if(first==1)
                   3924:                                                 printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   3925:                                         fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   3926:                                 }
                   3927:                         }
                   3928: 
                   3929:                         for(jk=1; jk <=nlstate ; jk++){ 
                   3930:                                 /* posprop[jk]=0; */
                   3931:                                 for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   3932:                                         pp[jk] += freq[jk][m][iage];
                   3933:                         }      /* pp[jk] is the total number of transitions starting from state jk and any ending status until this age */
                   3934: 
                   3935:                         for(jk=1,pos=0, pospropta=0.; jk <=nlstate ; jk++){
                   3936:                                 pos += pp[jk]; /* pos is the total number of transitions until this age */
                   3937:                                 posprop[jk] += prop[jk][iage]; /* prop is the number of transitions from a live state
                   3938:                                                                                                                                                                         from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   3939:                                 pospropta += prop[jk][iage]; /* prop is the number of transitions from a live state
                   3940:                                                                                                                                                                         from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   3941:                         }
                   3942:                         for(jk=1; jk <=nlstate ; jk++){
                   3943:                                 if(pos>=1.e-5){
                   3944:                                         if(first==1)
                   3945:                                                 printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   3946:                                         fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   3947:                                 }else{
                   3948:                                         if(first==1)
                   3949:                                                 printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   3950:                                         fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   3951:                                 }
                   3952:                                 if( iage <= iagemax){
                   3953:                                         if(pos>=1.e-5){
                   3954:                                                 fprintf(ficresp," %d %.5f %.0f %.0f",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
                   3955:                                                 fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
                   3956:                                                 /*probs[iage][jk][j1]= pp[jk]/pos;*/
                   3957:                                                 /*printf("\niage=%d jk=%d j1=%d %.5f %.0f %.0f %f",iage,jk,j1,pp[jk]/pos, pp[jk],pos,probs[iage][jk][j1]);*/
                   3958:                                         }
                   3959:                                         else{
                   3960:                                                 fprintf(ficresp," %d NaNq %.0f %.0f",iage,prop[jk][iage],pospropta);
                   3961:                                                 fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[jk][iage],pospropta);
                   3962:                                         }
                   3963:                                 }
                   3964:                                 pospropt[jk] +=posprop[jk];
                   3965:                         } /* end loop jk */
                   3966:                         /* pospropt=0.; */
                   3967:                         for(jk=-1; jk <=nlstate+ndeath; jk++){
                   3968:                                 for(m=-1; m <=nlstate+ndeath; m++){
                   3969:                                         if(freq[jk][m][iage] !=0 ) { /* minimizing output */
                   3970:                                                 if(first==1){
                   3971:                                                         printf(" %d%d=%.0f",jk,m,freq[jk][m][iage]);
                   3972:                                                 }
                   3973:                                                 fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][iage]);
                   3974:                                         }
                   3975:                                         if(jk!=0 && m!=0)
                   3976:                                                 fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[jk][m][iage]);
                   3977:                                 }
                   3978:                         } /* end loop jk */
                   3979:                         posproptt=0.; 
                   3980:                         for(jk=1; jk <=nlstate; jk++){
                   3981:                                 posproptt += pospropt[jk];
                   3982:                         }
                   3983:                         fprintf(ficresphtmfr,"</tr>\n ");
                   3984:                         if(iage <= iagemax){
                   3985:                                 fprintf(ficresp,"\n");
                   3986:                                 fprintf(ficresphtm,"</tr>\n");
                   3987:                         }
                   3988:                         if(first==1)
                   3989:                                 printf("Others in log...\n");
                   3990:                         fprintf(ficlog,"\n");
                   3991:                 } /* end loop age iage */
                   3992:                 fprintf(ficresphtm,"<tr><th>Tot</th>");
                   3993:                 for(jk=1; jk <=nlstate ; jk++){
                   3994:                         if(posproptt < 1.e-5){
1.221     brouard  3995:                                 fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[jk],posproptt);  
                   3996:                         }else{
1.220     brouard  3997:                                 fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[jk]/posproptt,pospropt[jk],posproptt);   
                   3998:                         }
                   3999:                 }
                   4000:                 fprintf(ficresphtm,"</tr>\n");
                   4001:                 fprintf(ficresphtm,"</table>\n");
                   4002:                 fprintf(ficresphtmfr,"</table>\n");
                   4003:                 if(posproptt < 1.e-5){
                   4004:                         fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   4005:                         fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   4006:                         fprintf(ficres,"\n  This combination (%d) is not valid and no result will be produced\n\n",j1);
                   4007:                         invalidvarcomb[j1]=1;
                   4008:                 }else{
                   4009:                         fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
                   4010:                         invalidvarcomb[j1]=0;
                   4011:                 }
                   4012:                 fprintf(ficresphtmfr,"</table>\n");
                   4013:         } /* end selected combination of covariate j1 */
                   4014:         dateintmean=dateintsum/k2cpt; 
                   4015:                 
                   4016:         fclose(ficresp);
                   4017:         fclose(ficresphtm);
                   4018:         fclose(ficresphtmfr);
                   4019:         free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+3+AGEMARGE);
                   4020:         free_vector(pospropt,1,nlstate);
                   4021:         free_vector(posprop,1,nlstate);
                   4022:         free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+3+AGEMARGE);
                   4023:         free_vector(pp,1,nlstate);
                   4024:         /* End of Freq */
                   4025:  }
1.126     brouard  4026: 
                   4027: /************ Prevalence ********************/
1.222     brouard  4028:  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)
                   4029:  {  
                   4030:    /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   4031:       in each health status at the date of interview (if between dateprev1 and dateprev2).
                   4032:       We still use firstpass and lastpass as another selection.
                   4033:    */
1.126     brouard  4034:  
1.222     brouard  4035:    int i, m, jk, j1, bool, z1,j;
                   4036:    int mi; /* Effective wave */
                   4037:    int iage;
                   4038:    double agebegin, ageend;
                   4039: 
                   4040:    double **prop;
                   4041:    double posprop; 
                   4042:    double  y2; /* in fractional years */
                   4043:    int iagemin, iagemax;
                   4044:    int first; /** to stop verbosity which is redirected to log file */
                   4045: 
                   4046:    iagemin= (int) agemin;
                   4047:    iagemax= (int) agemax;
                   4048:    /*pp=vector(1,nlstate);*/
                   4049:    prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+3+AGEMARGE); 
                   4050:    /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   4051:    j1=0;
                   4052:   
                   4053:    /*j=cptcoveff;*/
                   4054:    if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   4055:   
                   4056:    first=1;
                   4057:    for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of covariate */
                   4058:      for (i=1; i<=nlstate; i++)  
                   4059:        for(iage=iagemin-AGEMARGE; iage <= iagemax+3+AGEMARGE; iage++)
                   4060:         prop[i][iage]=0.0;
                   4061:     
                   4062:      for (i=1; i<=imx; i++) { /* Each individual */
                   4063:        bool=1;
                   4064:        if  (cptcovn>0) {  /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   4065:         for (z1=1; z1<=cptcoveff; 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*/
                   4066:           if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) 
                   4067:             bool=0;
                   4068:        } 
                   4069:        if (bool==1) { /* For this combination of covariates values, this individual fits */
                   4070:         /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   4071:         for(mi=1; mi<wav[i];mi++){
                   4072:           m=mw[mi][i];
                   4073:           agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   4074:           /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   4075:           if(m >=firstpass && m <=lastpass){
                   4076:             y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   4077:             if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   4078:               if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   4079:               if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   4080:               if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+3+AGEMARGE){
                   4081:                 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); 
                   4082:                 exit(1);
                   4083:               }
                   4084:               if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   4085:                 /*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]]);*/
                   4086:                 prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   4087:                 prop[s[m][i]][iagemax+3] += weight[i]; 
                   4088:               } /* end valid statuses */ 
                   4089:             } /* end selection of dates */
                   4090:           } /* end selection of waves */
                   4091:         } /* end effective waves */
                   4092:        } /* end bool */
                   4093:      }
                   4094:      for(i=iagemin; i <= iagemax+3; i++){  
                   4095:        for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   4096:         posprop += prop[jk][i]; 
                   4097:        } 
                   4098:       
                   4099:        for(jk=1; jk <=nlstate ; jk++){     
                   4100:         if( i <=  iagemax){ 
                   4101:           if(posprop>=1.e-5){ 
                   4102:             probs[i][jk][j1]= prop[jk][i]/posprop;
                   4103:           } else{
                   4104:             if(first==1){
                   4105:               first=0;
                   4106:               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]);
                   4107:             }
                   4108:           }
                   4109:         } 
                   4110:        }/* end jk */ 
                   4111:      }/* end i */ 
                   4112:      /*} *//* end i1 */
                   4113:    } /* end j1 */
                   4114:   
                   4115:    /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   4116:    /*free_vector(pp,1,nlstate);*/
                   4117:    free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+3+AGEMARGE);
                   4118:  }  /* End of prevalence */
1.126     brouard  4119: 
                   4120: /************* Waves Concatenation ***************/
                   4121: 
                   4122: 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)
                   4123: {
                   4124:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   4125:      Death is a valid wave (if date is known).
                   4126:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   4127:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4128:      and mw[mi+1][i]. dh depends on stepm.
                   4129:      */
                   4130: 
                   4131:   int i, mi, m;
                   4132:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   4133:      double sum=0., jmean=0.;*/
1.218     brouard  4134:   int first, firstwo, firsthree, firstfour;
1.126     brouard  4135:   int j, k=0,jk, ju, jl;
                   4136:   double sum=0.;
                   4137:   first=0;
1.214     brouard  4138:   firstwo=0;
1.217     brouard  4139:   firsthree=0;
1.218     brouard  4140:   firstfour=0;
1.164     brouard  4141:   jmin=100000;
1.126     brouard  4142:   jmax=-1;
                   4143:   jmean=0.;
1.214     brouard  4144:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.126     brouard  4145:     mi=0;
                   4146:     m=firstpass;
1.214     brouard  4147:     while(s[m][i] <= nlstate){  /* a live state */
1.216     brouard  4148:       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  4149:                                mw[++mi][i]=m;
1.216     brouard  4150:       }
                   4151:       if(m >=lastpass){
1.223   ! brouard  4152:                                if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){
        !          4153:                                        if(firsthree == 0){
        !          4154:                                                printf("Information! Unknown health 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.\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);
        !          4155:                                                firsthree=1;
        !          4156:                                        }
        !          4157:                                        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.\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);
        !          4158:                                        mw[++mi][i]=m;
        !          4159:                                }
        !          4160:                                if(s[m][i]==-2){ /* Vital status is really unknown */
        !          4161:                                        nbwarn++;
        !          4162:                                        if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified? */
        !          4163:                                                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);
        !          4164:                                                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.\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);
        !          4165:                                        }
        !          4166:                                        break;
        !          4167:                                }
        !          4168:                                break;
1.216     brouard  4169:       }
1.126     brouard  4170:       else
1.223   ! brouard  4171:                                m++;
1.126     brouard  4172:     }/* end while */
1.216     brouard  4173:     
                   4174:     /* After last pass */
1.214     brouard  4175:     if (s[m][i] > nlstate){  /* In a death state */
1.126     brouard  4176:       mi++;    /* Death is another wave */
                   4177:       /* if(mi==0)  never been interviewed correctly before death */
1.223   ! brouard  4178:                        /* Only death is a correct wave */
1.126     brouard  4179:       mw[mi][i]=m;
1.216     brouard  4180:     }else if ((int) andc[i] != 9999) { /* Status is either death or negative. A death occured after lastpass, we can't take it into account because of potential bias */
                   4181:       /* m++; */
                   4182:       /* mi++; */
                   4183:       /* s[m][i]=nlstate+1;  /\* We are setting the status to the last of non live state *\/ */
                   4184:       /* mw[mi][i]=m; */
                   4185:       nberr++;
1.218     brouard  4186:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.223   ! brouard  4187:                                if(firstwo==0){
        !          4188:                                        printf("Error! Death for individual %ld line=%d  occurred %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 );
        !          4189:                                        firstwo=1;
        !          4190:                                }
        !          4191:                                fprintf(ficlog,"Error! Death for individual %ld line=%d  occurred %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.218     brouard  4192:       }else{ /* end date of interview is known */
1.223   ! brouard  4193:                                /* death is known but not confirmed by death status at any wave */
        !          4194:                                if(firstfour==0){
        !          4195:                                        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 );
        !          4196:                                        firstfour=1;
        !          4197:                                }
        !          4198:                                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  4199:       }
1.126     brouard  4200:     }
                   4201:     wav[i]=mi;
                   4202:     if(mi==0){
                   4203:       nbwarn++;
                   4204:       if(first==0){
1.223   ! brouard  4205:                                printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
        !          4206:                                first=1;
1.126     brouard  4207:       }
                   4208:       if(first==1){
1.223   ! brouard  4209:                                fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  4210:       }
                   4211:     } /* end mi==0 */
                   4212:   } /* End individuals */
1.214     brouard  4213:   /* wav and mw are no more changed */
1.223   ! brouard  4214:        
1.214     brouard  4215:   
1.126     brouard  4216:   for(i=1; i<=imx; i++){
                   4217:     for(mi=1; mi<wav[i];mi++){
                   4218:       if (stepm <=0)
1.223   ! brouard  4219:                                dh[mi][i]=1;
1.126     brouard  4220:       else{
1.223   ! brouard  4221:                                if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
        !          4222:                                        if (agedc[i] < 2*AGESUP) {
        !          4223:                                                j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
        !          4224:                                                if(j==0) j=1;  /* Survives at least one month after exam */
        !          4225:                                                else if(j<0){
        !          4226:                                                        nberr++;
        !          4227:                                                        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]);
        !          4228:                                                        j=1; /* Temporary Dangerous patch */
        !          4229:                                                        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);
        !          4230:                                                        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]);
        !          4231:                                                        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);
        !          4232:                                                }
        !          4233:                                                k=k+1;
        !          4234:                                                if (j >= jmax){
        !          4235:                                                        jmax=j;
        !          4236:                                                        ijmax=i;
        !          4237:                                                }
        !          4238:                                                if (j <= jmin){
        !          4239:                                                        jmin=j;
        !          4240:                                                        ijmin=i;
        !          4241:                                                }
        !          4242:                                                sum=sum+j;
        !          4243:                                                /*if (j<0) printf("j=%d num=%d \n",j,i);*/
        !          4244:                                                /*        printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
        !          4245:                                        }
        !          4246:                                }
        !          4247:                                else{
        !          4248:                                        j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  4249: /*       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  4250:                                        
        !          4251:                                        k=k+1;
        !          4252:                                        if (j >= jmax) {
        !          4253:                                                jmax=j;
        !          4254:                                                ijmax=i;
        !          4255:                                        }
        !          4256:                                        else if (j <= jmin){
        !          4257:                                                jmin=j;
        !          4258:                                                ijmin=i;
        !          4259:                                        }
        !          4260:                                        /*          if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
        !          4261:                                        /*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]);*/
        !          4262:                                        if(j<0){
        !          4263:                                                nberr++;
        !          4264:                                                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]);
        !          4265:                                                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]);
        !          4266:                                        }
        !          4267:                                        sum=sum+j;
        !          4268:                                }
        !          4269:                                jk= j/stepm;
        !          4270:                                jl= j -jk*stepm;
        !          4271:                                ju= j -(jk+1)*stepm;
        !          4272:                                if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
        !          4273:                                        if(jl==0){
        !          4274:                                                dh[mi][i]=jk;
        !          4275:                                                bh[mi][i]=0;
        !          4276:                                        }else{ /* We want a negative bias in order to only have interpolation ie
        !          4277:                                                                        * to avoid the price of an extra matrix product in likelihood */
        !          4278:                                                dh[mi][i]=jk+1;
        !          4279:                                                bh[mi][i]=ju;
        !          4280:                                        }
        !          4281:                                }else{
        !          4282:                                        if(jl <= -ju){
        !          4283:                                                dh[mi][i]=jk;
        !          4284:                                                bh[mi][i]=jl;   /* bias is positive if real duration
        !          4285:                                                                                                         * is higher than the multiple of stepm and negative otherwise.
        !          4286:                                                                                                         */
        !          4287:                                        }
        !          4288:                                        else{
        !          4289:                                                dh[mi][i]=jk+1;
        !          4290:                                                bh[mi][i]=ju;
        !          4291:                                        }
        !          4292:                                        if(dh[mi][i]==0){
        !          4293:                                                dh[mi][i]=1; /* At least one step */
        !          4294:                                                bh[mi][i]=ju; /* At least one step */
        !          4295:                                                /*  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);*/
        !          4296:                                        }
        !          4297:                                } /* end if mle */
1.126     brouard  4298:       }
                   4299:     } /* end wave */
                   4300:   }
                   4301:   jmean=sum/k;
                   4302:   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  4303:   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  4304:  }
                   4305: 
                   4306: /*********** Tricode ****************************/
1.220     brouard  4307:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.126     brouard  4308: {
1.144     brouard  4309:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   4310:   /*     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  4311:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145     brouard  4312:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.220     brouard  4313:    * nbcode[Tvar[5]][1]= nbcode[2][1]=0, nbcode[2][2]=1 (usually);
1.144     brouard  4314:   */
1.130     brouard  4315: 
1.145     brouard  4316:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136     brouard  4317:   int modmaxcovj=0; /* Modality max of covariates j */
1.145     brouard  4318:   int cptcode=0; /* Modality max of covariates j */
                   4319:   int modmincovj=0; /* Modality min of covariates j */
                   4320: 
                   4321: 
1.220     brouard  4322:   /* cptcoveff=0;  */
                   4323:        *cptcov=0;
1.126     brouard  4324:  
1.144     brouard  4325:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  4326: 
1.145     brouard  4327:   /* Loop on covariates without age and products */
1.186     brouard  4328:   for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
1.192     brouard  4329:     for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.186     brouard  4330:     for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the 
1.219     brouard  4331:                                                                                                                                modality of this covariate Vj*/ 
1.145     brouard  4332:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
1.219     brouard  4333:                                                                                                                                                * If product of Vn*Vm, still boolean *:
                   4334:                                                                                                                                                * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   4335:                                                                                                                                                * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
1.145     brouard  4336:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136     brouard  4337:                                      modality of the nth covariate of individual i. */
1.145     brouard  4338:       if (ij > modmaxcovj)
                   4339:         modmaxcovj=ij; 
                   4340:       else if (ij < modmincovj) 
1.219     brouard  4341:                                modmincovj=ij; 
1.145     brouard  4342:       if ((ij < -1) && (ij > NCOVMAX)){
1.219     brouard  4343:                                printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   4344:                                exit(1);
1.145     brouard  4345:       }else
1.136     brouard  4346:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145     brouard  4347:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126     brouard  4348:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136     brouard  4349:       /* getting the maximum value of the modality of the covariate
                   4350:         (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   4351:         female is 1, then modmaxcovj=1.*/
1.192     brouard  4352:     } /* end for loop on individuals i */
1.145     brouard  4353:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
1.192     brouard  4354:     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  4355:     cptcode=modmaxcovj;
1.137     brouard  4356:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145     brouard  4357:    /*for (i=0; i<=cptcode; i++) {*/
1.192     brouard  4358:     for (k=modmincovj;  k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
                   4359:       printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   4360:       fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   4361:       if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
1.219     brouard  4362:                                if( k != -1){
                   4363:                                        ncodemax[j]++;  /* ncodemax[j]= Number of modalities of the j th
                   4364:                                                                                                                 covariate for which somebody answered excluding 
                   4365:                                                                                                                 undefined. Usually 2: 0 and 1. */
                   4366:                                }
                   4367:                                ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
                   4368:                                                                                                                                covariate for which somebody answered including 
                   4369:                                                                                                                                undefined. Usually 3: -1, 0 and 1. */
1.145     brouard  4370:       }
                   4371:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
1.219     brouard  4372:                                 historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131     brouard  4373:     } /* Ndum[-1] number of undefined modalities */
1.219     brouard  4374:                
1.136     brouard  4375:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.186     brouard  4376:     /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. 
                   4377:        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  4378:        modmincovj=3; modmaxcovj = 7;
1.186     brouard  4379:        There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
                   4380:        which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
                   4381:        defining two dummy variables: variables V1_1 and V1_2.
1.145     brouard  4382:        nbcode[Tvar[j]][ij]=k;
                   4383:        nbcode[Tvar[j]][1]=0;
                   4384:        nbcode[Tvar[j]][2]=1;
                   4385:        nbcode[Tvar[j]][3]=2;
1.197     brouard  4386:        To be continued (not working yet).
1.145     brouard  4387:     */
1.197     brouard  4388:     ij=0; /* ij is similar to i but can jump over null modalities */
                   4389:     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*/
                   4390:        if (Ndum[i] == 0) { /* If nobody responded to this modality k */
1.219     brouard  4391:                                break;
                   4392:                        }
1.192     brouard  4393:        ij++;
1.197     brouard  4394:        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.*/
1.192     brouard  4395:        cptcode = ij; /* New max modality for covar j */
                   4396:     } /* end of loop on modality i=-1 to 1 or more */
                   4397:       
                   4398:     /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
                   4399:     /*         /\*recode from 0 *\/ */
                   4400:     /*                                      k is a modality. If we have model=V1+V1*sex  */
                   4401:     /*                                      then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
                   4402:     /*                                   But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
                   4403:     /*         } */
                   4404:     /*         /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
                   4405:     /*         if (ij > ncodemax[j]) { */
                   4406:     /*           printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
                   4407:     /*           fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
                   4408:     /*           break; */
                   4409:     /*         } */
                   4410:     /*   }  /\* end of loop on modality k *\/ */
1.137     brouard  4411:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   4412:   
1.219     brouard  4413:        for (k=-1; k< maxncov; k++) Ndum[k]=0; 
1.137     brouard  4414:   
1.187     brouard  4415:   for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
1.219     brouard  4416:                /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   4417:                ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
                   4418:                Ndum[ij]++; /* Might be supersed V1 + V1*age */
                   4419:        } 
                   4420:        
                   4421:        ij=0;
                   4422:        for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   4423:                /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   4424:                if((Ndum[i]!=0) && (i<=ncovcol)){
                   4425:                        ij++;
                   4426:                        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   4427:                        Tvaraff[ij]=i; /*For printing (unclear) */
                   4428:                }else{
                   4429:                        /* Tvaraff[ij]=0; */
                   4430:                }
                   4431:        }
                   4432:        /* ij--; */
1.220     brouard  4433:        /* cptcoveff=ij; /\*Number of total covariates*\/ */
                   4434:        *cptcov=ij; /*Number of total covariates*/
1.219     brouard  4435:        
1.126     brouard  4436: }
                   4437: 
1.145     brouard  4438: 
1.126     brouard  4439: /*********** Health Expectancies ****************/
                   4440: 
1.127     brouard  4441: 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  4442: 
                   4443: {
                   4444:   /* Health expectancies, no variances */
1.164     brouard  4445:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  4446:   int nhstepma, nstepma; /* Decreasing with age */
                   4447:   double age, agelim, hf;
                   4448:   double ***p3mat;
                   4449:   double eip;
                   4450: 
                   4451:   pstamp(ficreseij);
                   4452:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   4453:   fprintf(ficreseij,"# Age");
                   4454:   for(i=1; i<=nlstate;i++){
                   4455:     for(j=1; j<=nlstate;j++){
                   4456:       fprintf(ficreseij," e%1d%1d ",i,j);
                   4457:     }
                   4458:     fprintf(ficreseij," e%1d. ",i);
                   4459:   }
                   4460:   fprintf(ficreseij,"\n");
                   4461: 
                   4462:   
                   4463:   if(estepm < stepm){
                   4464:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4465:   }
                   4466:   else  hstepm=estepm;   
                   4467:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   4468:    * This is mainly to measure the difference between two models: for example
                   4469:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   4470:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   4471:    * progression in between and thus overestimating or underestimating according
                   4472:    * to the curvature of the survival function. If, for the same date, we 
                   4473:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   4474:    * to compare the new estimate of Life expectancy with the same linear 
                   4475:    * hypothesis. A more precise result, taking into account a more precise
                   4476:    * curvature will be obtained if estepm is as small as stepm. */
                   4477: 
                   4478:   /* For example we decided to compute the life expectancy with the smallest unit */
                   4479:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   4480:      nhstepm is the number of hstepm from age to agelim 
                   4481:      nstepm is the number of stepm from age to agelin. 
                   4482:      Look at hpijx to understand the reason of that which relies in memory size
                   4483:      and note for a fixed period like estepm months */
                   4484:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   4485:      survival function given by stepm (the optimization length). Unfortunately it
                   4486:      means that if the survival funtion is printed only each two years of age and if
                   4487:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   4488:      results. So we changed our mind and took the option of the best precision.
                   4489:   */
                   4490:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   4491: 
                   4492:   agelim=AGESUP;
                   4493:   /* If stepm=6 months */
                   4494:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   4495:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   4496:     
                   4497: /* nhstepm age range expressed in number of stepm */
                   4498:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   4499:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   4500:   /* if (stepm >= YEARM) hstepm=1;*/
                   4501:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   4502:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4503: 
                   4504:   for (age=bage; age<=fage; age ++){ 
                   4505:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   4506:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   4507:     /* if (stepm >= YEARM) hstepm=1;*/
                   4508:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   4509: 
                   4510:     /* If stepm=6 months */
                   4511:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   4512:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   4513:     
                   4514:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   4515:     
                   4516:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   4517:     
                   4518:     printf("%d|",(int)age);fflush(stdout);
                   4519:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   4520:     
                   4521:     /* Computing expectancies */
                   4522:     for(i=1; i<=nlstate;i++)
                   4523:       for(j=1; j<=nlstate;j++)
                   4524:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   4525:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   4526:          
                   4527:          /* 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]);*/
                   4528: 
                   4529:        }
                   4530: 
                   4531:     fprintf(ficreseij,"%3.0f",age );
                   4532:     for(i=1; i<=nlstate;i++){
                   4533:       eip=0;
                   4534:       for(j=1; j<=nlstate;j++){
                   4535:        eip +=eij[i][j][(int)age];
                   4536:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   4537:       }
                   4538:       fprintf(ficreseij,"%9.4f", eip );
                   4539:     }
                   4540:     fprintf(ficreseij,"\n");
                   4541:     
                   4542:   }
                   4543:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4544:   printf("\n");
                   4545:   fprintf(ficlog,"\n");
                   4546:   
                   4547: }
                   4548: 
1.127     brouard  4549: 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  4550: 
                   4551: {
                   4552:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  4553:      to initial status i, ei. .
1.126     brouard  4554:   */
                   4555:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   4556:   int nhstepma, nstepma; /* Decreasing with age */
                   4557:   double age, agelim, hf;
                   4558:   double ***p3matp, ***p3matm, ***varhe;
                   4559:   double **dnewm,**doldm;
                   4560:   double *xp, *xm;
                   4561:   double **gp, **gm;
                   4562:   double ***gradg, ***trgradg;
                   4563:   int theta;
                   4564: 
                   4565:   double eip, vip;
                   4566: 
                   4567:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   4568:   xp=vector(1,npar);
                   4569:   xm=vector(1,npar);
                   4570:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   4571:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   4572:   
                   4573:   pstamp(ficresstdeij);
                   4574:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   4575:   fprintf(ficresstdeij,"# Age");
                   4576:   for(i=1; i<=nlstate;i++){
                   4577:     for(j=1; j<=nlstate;j++)
                   4578:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   4579:     fprintf(ficresstdeij," e%1d. ",i);
                   4580:   }
                   4581:   fprintf(ficresstdeij,"\n");
                   4582: 
                   4583:   pstamp(ficrescveij);
                   4584:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   4585:   fprintf(ficrescveij,"# Age");
                   4586:   for(i=1; i<=nlstate;i++)
                   4587:     for(j=1; j<=nlstate;j++){
                   4588:       cptj= (j-1)*nlstate+i;
                   4589:       for(i2=1; i2<=nlstate;i2++)
                   4590:        for(j2=1; j2<=nlstate;j2++){
                   4591:          cptj2= (j2-1)*nlstate+i2;
                   4592:          if(cptj2 <= cptj)
                   4593:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   4594:        }
                   4595:     }
                   4596:   fprintf(ficrescveij,"\n");
                   4597:   
                   4598:   if(estepm < stepm){
                   4599:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4600:   }
                   4601:   else  hstepm=estepm;   
                   4602:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   4603:    * This is mainly to measure the difference between two models: for example
                   4604:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   4605:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   4606:    * progression in between and thus overestimating or underestimating according
                   4607:    * to the curvature of the survival function. If, for the same date, we 
                   4608:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   4609:    * to compare the new estimate of Life expectancy with the same linear 
                   4610:    * hypothesis. A more precise result, taking into account a more precise
                   4611:    * curvature will be obtained if estepm is as small as stepm. */
                   4612: 
                   4613:   /* For example we decided to compute the life expectancy with the smallest unit */
                   4614:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   4615:      nhstepm is the number of hstepm from age to agelim 
                   4616:      nstepm is the number of stepm from age to agelin. 
                   4617:      Look at hpijx to understand the reason of that which relies in memory size
                   4618:      and note for a fixed period like estepm months */
                   4619:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   4620:      survival function given by stepm (the optimization length). Unfortunately it
                   4621:      means that if the survival funtion is printed only each two years of age and if
                   4622:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   4623:      results. So we changed our mind and took the option of the best precision.
                   4624:   */
                   4625:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   4626: 
                   4627:   /* If stepm=6 months */
                   4628:   /* nhstepm age range expressed in number of stepm */
                   4629:   agelim=AGESUP;
                   4630:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   4631:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   4632:   /* if (stepm >= YEARM) hstepm=1;*/
                   4633:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   4634:   
                   4635:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4636:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4637:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   4638:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   4639:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   4640:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   4641: 
                   4642:   for (age=bage; age<=fage; age ++){ 
                   4643:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   4644:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   4645:     /* if (stepm >= YEARM) hstepm=1;*/
                   4646:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  4647:                
1.126     brouard  4648:     /* If stepm=6 months */
                   4649:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   4650:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   4651:     
                   4652:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  4653:                
1.126     brouard  4654:     /* Computing  Variances of health expectancies */
                   4655:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   4656:        decrease memory allocation */
                   4657:     for(theta=1; theta <=npar; theta++){
                   4658:       for(i=1; i<=npar; i++){ 
1.222     brouard  4659:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4660:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  4661:       }
                   4662:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
                   4663:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
1.218     brouard  4664:                        
1.126     brouard  4665:       for(j=1; j<= nlstate; j++){
1.222     brouard  4666:        for(i=1; i<=nlstate; i++){
                   4667:          for(h=0; h<=nhstepm-1; h++){
                   4668:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   4669:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   4670:          }
                   4671:        }
1.126     brouard  4672:       }
1.218     brouard  4673:                        
1.126     brouard  4674:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  4675:        for(h=0; h<=nhstepm-1; h++){
                   4676:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   4677:        }
1.126     brouard  4678:     }/* End theta */
                   4679:     
                   4680:     
                   4681:     for(h=0; h<=nhstepm-1; h++)
                   4682:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  4683:        for(theta=1; theta <=npar; theta++)
                   4684:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  4685:     
1.218     brouard  4686:                
1.222     brouard  4687:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  4688:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  4689:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  4690:                
1.222     brouard  4691:     printf("%d|",(int)age);fflush(stdout);
                   4692:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   4693:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  4694:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  4695:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   4696:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   4697:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   4698:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   4699:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  4700:       }
                   4701:     }
1.218     brouard  4702:                
1.126     brouard  4703:     /* Computing expectancies */
                   4704:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   4705:     for(i=1; i<=nlstate;i++)
                   4706:       for(j=1; j<=nlstate;j++)
1.222     brouard  4707:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   4708:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  4709:                                        
1.222     brouard  4710:          /* 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  4711:                                        
1.222     brouard  4712:        }
1.218     brouard  4713:                
1.126     brouard  4714:     fprintf(ficresstdeij,"%3.0f",age );
                   4715:     for(i=1; i<=nlstate;i++){
                   4716:       eip=0.;
                   4717:       vip=0.;
                   4718:       for(j=1; j<=nlstate;j++){
1.222     brouard  4719:        eip += eij[i][j][(int)age];
                   4720:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   4721:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   4722:        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  4723:       }
                   4724:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   4725:     }
                   4726:     fprintf(ficresstdeij,"\n");
1.218     brouard  4727:                
1.126     brouard  4728:     fprintf(ficrescveij,"%3.0f",age );
                   4729:     for(i=1; i<=nlstate;i++)
                   4730:       for(j=1; j<=nlstate;j++){
1.222     brouard  4731:        cptj= (j-1)*nlstate+i;
                   4732:        for(i2=1; i2<=nlstate;i2++)
                   4733:          for(j2=1; j2<=nlstate;j2++){
                   4734:            cptj2= (j2-1)*nlstate+i2;
                   4735:            if(cptj2 <= cptj)
                   4736:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   4737:          }
1.126     brouard  4738:       }
                   4739:     fprintf(ficrescveij,"\n");
1.218     brouard  4740:                
1.126     brouard  4741:   }
                   4742:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   4743:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   4744:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   4745:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   4746:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4747:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4748:   printf("\n");
                   4749:   fprintf(ficlog,"\n");
1.218     brouard  4750:        
1.126     brouard  4751:   free_vector(xm,1,npar);
                   4752:   free_vector(xp,1,npar);
                   4753:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   4754:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   4755:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   4756: }
1.218     brouard  4757:  
1.126     brouard  4758: /************ Variance ******************/
1.209     brouard  4759:  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  4760:  {
                   4761:    /* Variance of health expectancies */
                   4762:    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   4763:    /* double **newm;*/
                   4764:    /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
                   4765:   
                   4766:    /* int movingaverage(); */
                   4767:    double **dnewm,**doldm;
                   4768:    double **dnewmp,**doldmp;
                   4769:    int i, j, nhstepm, hstepm, h, nstepm ;
                   4770:    int k;
                   4771:    double *xp;
                   4772:    double **gp, **gm;  /* for var eij */
                   4773:    double ***gradg, ***trgradg; /*for var eij */
                   4774:    double **gradgp, **trgradgp; /* for var p point j */
                   4775:    double *gpp, *gmp; /* for var p point j */
                   4776:    double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   4777:    double ***p3mat;
                   4778:    double age,agelim, hf;
                   4779:    /* double ***mobaverage; */
                   4780:    int theta;
                   4781:    char digit[4];
                   4782:    char digitp[25];
                   4783: 
                   4784:    char fileresprobmorprev[FILENAMELENGTH];
                   4785: 
                   4786:    if(popbased==1){
                   4787:      if(mobilav!=0)
                   4788:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   4789:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   4790:    }
                   4791:    else 
                   4792:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  4793: 
1.218     brouard  4794:    /* if (mobilav!=0) { */
                   4795:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   4796:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   4797:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   4798:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   4799:    /*   } */
                   4800:    /* } */
                   4801: 
                   4802:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   4803:    sprintf(digit,"%-d",ij);
                   4804:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   4805:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   4806:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   4807:    strcat(fileresprobmorprev,fileresu);
                   4808:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   4809:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   4810:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   4811:    }
                   4812:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   4813:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   4814:    pstamp(ficresprobmorprev);
                   4815:    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);
                   4816:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   4817:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   4818:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   4819:      for(i=1; i<=nlstate;i++)
                   4820:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   4821:    }  
                   4822:    fprintf(ficresprobmorprev,"\n");
                   4823:   
                   4824:    fprintf(ficgp,"\n# Routine varevsij");
                   4825:    fprintf(ficgp,"\nunset title \n");
                   4826:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   4827:    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");
                   4828:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   4829:    /*   } */
                   4830:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4831:    pstamp(ficresvij);
                   4832:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   4833:    if(popbased==1)
                   4834:      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);
                   4835:    else
                   4836:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   4837:    fprintf(ficresvij,"# Age");
                   4838:    for(i=1; i<=nlstate;i++)
                   4839:      for(j=1; j<=nlstate;j++)
                   4840:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   4841:    fprintf(ficresvij,"\n");
                   4842: 
                   4843:    xp=vector(1,npar);
                   4844:    dnewm=matrix(1,nlstate,1,npar);
                   4845:    doldm=matrix(1,nlstate,1,nlstate);
                   4846:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   4847:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4848: 
                   4849:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   4850:    gpp=vector(nlstate+1,nlstate+ndeath);
                   4851:    gmp=vector(nlstate+1,nlstate+ndeath);
                   4852:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  4853:   
1.218     brouard  4854:    if(estepm < stepm){
                   4855:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   4856:    }
                   4857:    else  hstepm=estepm;   
                   4858:    /* For example we decided to compute the life expectancy with the smallest unit */
                   4859:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   4860:       nhstepm is the number of hstepm from age to agelim 
                   4861:       nstepm is the number of stepm from age to agelim. 
                   4862:       Look at function hpijx to understand why because of memory size limitations, 
                   4863:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   4864:       survival function given by stepm (the optimization length). Unfortunately it
                   4865:       means that if the survival funtion is printed every two years of age and if
                   4866:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   4867:       results. So we changed our mind and took the option of the best precision.
                   4868:    */
                   4869:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   4870:    agelim = AGESUP;
                   4871:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   4872:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   4873:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   4874:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4875:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   4876:      gp=matrix(0,nhstepm,1,nlstate);
                   4877:      gm=matrix(0,nhstepm,1,nlstate);
                   4878:                
                   4879:                
                   4880:      for(theta=1; theta <=npar; theta++){
                   4881:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   4882:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4883:        }
                   4884:                        
                   4885:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
                   4886:                        
                   4887:        if (popbased==1) {
                   4888:         if(mobilav ==0){
                   4889:           for(i=1; i<=nlstate;i++)
                   4890:             prlim[i][i]=probs[(int)age][i][ij];
                   4891:         }else{ /* mobilav */ 
                   4892:           for(i=1; i<=nlstate;i++)
                   4893:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   4894:         }
                   4895:        }
                   4896:                        
                   4897:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  /* Returns p3mat[i][j][h] for h=1 to nhstepm */
                   4898:        for(j=1; j<= nlstate; j++){
                   4899:         for(h=0; h<=nhstepm; h++){
                   4900:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   4901:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   4902:         }
                   4903:        }
                   4904:        /* Next for computing probability of death (h=1 means
                   4905:          computed over hstepm matrices product = hstepm*stepm months) 
                   4906:          as a weighted average of prlim.
                   4907:        */
                   4908:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4909:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   4910:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   4911:        }    
                   4912:        /* end probability of death */
                   4913:                        
                   4914:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   4915:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   4916:                        
                   4917:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij);
                   4918:                        
                   4919:        if (popbased==1) {
                   4920:         if(mobilav ==0){
                   4921:           for(i=1; i<=nlstate;i++)
                   4922:             prlim[i][i]=probs[(int)age][i][ij];
                   4923:         }else{ /* mobilav */ 
                   4924:           for(i=1; i<=nlstate;i++)
                   4925:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   4926:         }
                   4927:        }
                   4928:                        
                   4929:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   4930:                        
                   4931:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   4932:         for(h=0; h<=nhstepm; h++){
                   4933:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   4934:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   4935:         }
                   4936:        }
                   4937:        /* This for computing probability of death (h=1 means
                   4938:          computed over hstepm matrices product = hstepm*stepm months) 
                   4939:          as a weighted average of prlim.
                   4940:        */
                   4941:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4942:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   4943:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   4944:        }    
                   4945:        /* end probability of death */
                   4946:                        
                   4947:        for(j=1; j<= nlstate; j++) /* vareij */
                   4948:         for(h=0; h<=nhstepm; h++){
                   4949:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   4950:         }
                   4951:                        
                   4952:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   4953:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   4954:        }
                   4955:                        
                   4956:      } /* End theta */
                   4957:                
                   4958:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   4959:                
                   4960:      for(h=0; h<=nhstepm; h++) /* veij */
                   4961:        for(j=1; j<=nlstate;j++)
                   4962:         for(theta=1; theta <=npar; theta++)
                   4963:           trgradg[h][j][theta]=gradg[h][theta][j];
                   4964:                
                   4965:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   4966:        for(theta=1; theta <=npar; theta++)
                   4967:         trgradgp[j][theta]=gradgp[theta][j];
                   4968:                
                   4969:                
                   4970:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   4971:      for(i=1;i<=nlstate;i++)
                   4972:        for(j=1;j<=nlstate;j++)
                   4973:         vareij[i][j][(int)age] =0.;
                   4974:                
                   4975:      for(h=0;h<=nhstepm;h++){
                   4976:        for(k=0;k<=nhstepm;k++){
                   4977:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   4978:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   4979:         for(i=1;i<=nlstate;i++)
                   4980:           for(j=1;j<=nlstate;j++)
                   4981:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   4982:        }
                   4983:      }
                   4984:                
                   4985:      /* pptj */
                   4986:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   4987:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   4988:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   4989:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   4990:         varppt[j][i]=doldmp[j][i];
                   4991:      /* end ppptj */
                   4992:      /*  x centered again */
                   4993:                
                   4994:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij);
                   4995:                
                   4996:      if (popbased==1) {
                   4997:        if(mobilav ==0){
                   4998:         for(i=1; i<=nlstate;i++)
                   4999:           prlim[i][i]=probs[(int)age][i][ij];
                   5000:        }else{ /* mobilav */ 
                   5001:         for(i=1; i<=nlstate;i++)
                   5002:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   5003:        }
                   5004:      }
                   5005:                
                   5006:      /* This for computing probability of death (h=1 means
                   5007:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   5008:        as a weighted average of prlim.
                   5009:      */
                   5010:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
                   5011:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   5012:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   5013:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   5014:      }    
                   5015:      /* end probability of death */
                   5016:                
                   5017:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   5018:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   5019:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   5020:        for(i=1; i<=nlstate;i++){
                   5021:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   5022:        }
                   5023:      } 
                   5024:      fprintf(ficresprobmorprev,"\n");
                   5025:                
                   5026:      fprintf(ficresvij,"%.0f ",age );
                   5027:      for(i=1; i<=nlstate;i++)
                   5028:        for(j=1; j<=nlstate;j++){
                   5029:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   5030:        }
                   5031:      fprintf(ficresvij,"\n");
                   5032:      free_matrix(gp,0,nhstepm,1,nlstate);
                   5033:      free_matrix(gm,0,nhstepm,1,nlstate);
                   5034:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   5035:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   5036:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5037:    } /* End age */
                   5038:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   5039:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   5040:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   5041:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   5042:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   5043:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   5044:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   5045:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   5046:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   5047:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   5048:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   5049:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   5050:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   5051:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   5052:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   5053:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   5054:    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);
                   5055:    /*  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  5056:     */
1.218     brouard  5057:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   5058:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  5059: 
1.218     brouard  5060:    free_vector(xp,1,npar);
                   5061:    free_matrix(doldm,1,nlstate,1,nlstate);
                   5062:    free_matrix(dnewm,1,nlstate,1,npar);
                   5063:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5064:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   5065:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5066:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   5067:    fclose(ficresprobmorprev);
                   5068:    fflush(ficgp);
                   5069:    fflush(fichtm); 
                   5070:  }  /* end varevsij */
1.126     brouard  5071: 
                   5072: /************ Variance of prevlim ******************/
1.209     brouard  5073:  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  5074: {
1.205     brouard  5075:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  5076:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  5077: 
1.126     brouard  5078:   double **dnewm,**doldm;
                   5079:   int i, j, nhstepm, hstepm;
                   5080:   double *xp;
                   5081:   double *gp, *gm;
                   5082:   double **gradg, **trgradg;
1.208     brouard  5083:   double **mgm, **mgp;
1.126     brouard  5084:   double age,agelim;
                   5085:   int theta;
                   5086:   
                   5087:   pstamp(ficresvpl);
                   5088:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
                   5089:   fprintf(ficresvpl,"# Age");
                   5090:   for(i=1; i<=nlstate;i++)
                   5091:       fprintf(ficresvpl," %1d-%1d",i,i);
                   5092:   fprintf(ficresvpl,"\n");
                   5093: 
                   5094:   xp=vector(1,npar);
                   5095:   dnewm=matrix(1,nlstate,1,npar);
                   5096:   doldm=matrix(1,nlstate,1,nlstate);
                   5097:   
                   5098:   hstepm=1*YEARM; /* Every year of age */
                   5099:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   5100:   agelim = AGESUP;
                   5101:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   5102:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   5103:     if (stepm >= YEARM) hstepm=1;
                   5104:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   5105:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  5106:     mgp=matrix(1,npar,1,nlstate);
                   5107:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  5108:     gp=vector(1,nlstate);
                   5109:     gm=vector(1,nlstate);
                   5110: 
                   5111:     for(theta=1; theta <=npar; theta++){
                   5112:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   5113:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5114:       }
1.209     brouard  5115:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
                   5116:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
                   5117:       else
                   5118:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
1.208     brouard  5119:       for(i=1;i<=nlstate;i++){
1.126     brouard  5120:        gp[i] = prlim[i][i];
1.208     brouard  5121:        mgp[theta][i] = prlim[i][i];
                   5122:       }
1.126     brouard  5123:       for(i=1; i<=npar; i++) /* Computes gradient */
                   5124:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.209     brouard  5125:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
                   5126:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
                   5127:       else
                   5128:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
1.208     brouard  5129:       for(i=1;i<=nlstate;i++){
1.126     brouard  5130:        gm[i] = prlim[i][i];
1.208     brouard  5131:        mgm[theta][i] = prlim[i][i];
                   5132:       }
1.126     brouard  5133:       for(i=1;i<=nlstate;i++)
                   5134:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  5135:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  5136:     } /* End theta */
                   5137: 
                   5138:     trgradg =matrix(1,nlstate,1,npar);
                   5139: 
                   5140:     for(j=1; j<=nlstate;j++)
                   5141:       for(theta=1; theta <=npar; theta++)
                   5142:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  5143:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   5144:     /*   printf("\nmgm mgp %d ",(int)age); */
                   5145:     /*   for(j=1; j<=nlstate;j++){ */
                   5146:     /*         printf(" %d ",j); */
                   5147:     /*         for(theta=1; theta <=npar; theta++) */
                   5148:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   5149:     /*         printf("\n "); */
                   5150:     /*   } */
                   5151:     /* } */
                   5152:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   5153:     /*   printf("\n gradg %d ",(int)age); */
                   5154:     /*   for(j=1; j<=nlstate;j++){ */
                   5155:     /*         printf("%d ",j); */
                   5156:     /*         for(theta=1; theta <=npar; theta++) */
                   5157:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   5158:     /*         printf("\n "); */
                   5159:     /*   } */
                   5160:     /* } */
1.126     brouard  5161: 
                   5162:     for(i=1;i<=nlstate;i++)
                   5163:       varpl[i][(int)age] =0.;
1.209     brouard  5164:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.205     brouard  5165:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   5166:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   5167:     }else{
1.126     brouard  5168:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   5169:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  5170:     }
1.126     brouard  5171:     for(i=1;i<=nlstate;i++)
                   5172:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   5173: 
                   5174:     fprintf(ficresvpl,"%.0f ",age );
                   5175:     for(i=1; i<=nlstate;i++)
                   5176:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   5177:     fprintf(ficresvpl,"\n");
                   5178:     free_vector(gp,1,nlstate);
                   5179:     free_vector(gm,1,nlstate);
1.208     brouard  5180:     free_matrix(mgm,1,npar,1,nlstate);
                   5181:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  5182:     free_matrix(gradg,1,npar,1,nlstate);
                   5183:     free_matrix(trgradg,1,nlstate,1,npar);
                   5184:   } /* End age */
                   5185: 
                   5186:   free_vector(xp,1,npar);
                   5187:   free_matrix(doldm,1,nlstate,1,npar);
                   5188:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   5189: 
                   5190: }
                   5191: 
                   5192: /************ Variance of one-step probabilities  ******************/
                   5193: 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  5194:  {
                   5195:    int i, j=0,  k1, l1, tj;
                   5196:    int k2, l2, j1,  z1;
                   5197:    int k=0, l;
                   5198:    int first=1, first1, first2;
                   5199:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   5200:    double **dnewm,**doldm;
                   5201:    double *xp;
                   5202:    double *gp, *gm;
                   5203:    double **gradg, **trgradg;
                   5204:    double **mu;
                   5205:    double age, cov[NCOVMAX+1];
                   5206:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   5207:    int theta;
                   5208:    char fileresprob[FILENAMELENGTH];
                   5209:    char fileresprobcov[FILENAMELENGTH];
                   5210:    char fileresprobcor[FILENAMELENGTH];
                   5211:    double ***varpij;
                   5212: 
                   5213:    strcpy(fileresprob,"PROB_"); 
                   5214:    strcat(fileresprob,fileres);
                   5215:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   5216:      printf("Problem with resultfile: %s\n", fileresprob);
                   5217:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   5218:    }
                   5219:    strcpy(fileresprobcov,"PROBCOV_"); 
                   5220:    strcat(fileresprobcov,fileresu);
                   5221:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   5222:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   5223:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   5224:    }
                   5225:    strcpy(fileresprobcor,"PROBCOR_"); 
                   5226:    strcat(fileresprobcor,fileresu);
                   5227:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   5228:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   5229:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   5230:    }
                   5231:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   5232:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   5233:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   5234:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   5235:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   5236:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   5237:    pstamp(ficresprob);
                   5238:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   5239:    fprintf(ficresprob,"# Age");
                   5240:    pstamp(ficresprobcov);
                   5241:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   5242:    fprintf(ficresprobcov,"# Age");
                   5243:    pstamp(ficresprobcor);
                   5244:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   5245:    fprintf(ficresprobcor,"# Age");
1.126     brouard  5246: 
                   5247: 
1.222     brouard  5248:    for(i=1; i<=nlstate;i++)
                   5249:      for(j=1; j<=(nlstate+ndeath);j++){
                   5250:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   5251:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   5252:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   5253:      }  
                   5254:    /* fprintf(ficresprob,"\n");
                   5255:       fprintf(ficresprobcov,"\n");
                   5256:       fprintf(ficresprobcor,"\n");
                   5257:    */
                   5258:    xp=vector(1,npar);
                   5259:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   5260:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   5261:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   5262:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   5263:    first=1;
                   5264:    fprintf(ficgp,"\n# Routine varprob");
                   5265:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   5266:    fprintf(fichtm,"\n");
                   5267: 
                   5268:    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);
                   5269:    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);
                   5270:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  5271: and drawn. It helps understanding how is the covariance between two incidences.\
                   5272:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  5273:    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  5274: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   5275: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   5276: standard deviations wide on each axis. <br>\
                   5277:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   5278:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   5279: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   5280: 
1.222     brouard  5281:    cov[1]=1;
                   5282:    /* tj=cptcoveff; */
                   5283:    tj = (int) pow(2,cptcoveff);
                   5284:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   5285:    j1=0;
                   5286:    for(j1=1; j1<=tj;j1++){  /* For each valid combination of covariates */
                   5287:      if  (cptcovn>0) {
                   5288:        fprintf(ficresprob, "\n#********** Variable "); 
                   5289:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   5290:        fprintf(ficresprob, "**********\n#\n");
                   5291:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   5292:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   5293:        fprintf(ficresprobcov, "**********\n#\n");
1.220     brouard  5294:                        
1.222     brouard  5295:        fprintf(ficgp, "\n#********** Variable "); 
                   5296:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   5297:        fprintf(ficgp, "**********\n#\n");
1.220     brouard  5298:                        
                   5299:                        
1.222     brouard  5300:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   5301:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   5302:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  5303:                        
1.222     brouard  5304:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   5305:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   5306:        fprintf(ficresprobcor, "**********\n#");    
                   5307:        if(invalidvarcomb[j1]){
                   5308:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   5309:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   5310:         continue;
                   5311:        }
                   5312:      }
                   5313:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   5314:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   5315:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   5316:      gm=vector(1,(nlstate)*(nlstate+ndeath));
                   5317:      for (age=bage; age<=fage; age ++){ 
                   5318:        cov[2]=age;
                   5319:        if(nagesqr==1)
                   5320:         cov[3]= age*age;
                   5321:        for (k=1; k<=cptcovn;k++) {
                   5322:         cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
                   5323:         /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
                   5324:                                                                    * 1  1 1 1 1
                   5325:                                                                    * 2  2 1 1 1
                   5326:                                                                    * 3  1 2 1 1
                   5327:                                                                    */
                   5328:         /* nbcode[1][1]=0 nbcode[1][2]=1;*/
                   5329:        }
                   5330:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   5331:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   5332:        for (k=1; k<=cptcovprod;k++)
                   5333:         cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.220     brouard  5334:                        
                   5335:                        
1.222     brouard  5336:        for(theta=1; theta <=npar; theta++){
                   5337:         for(i=1; i<=npar; i++)
                   5338:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  5339:                                
1.222     brouard  5340:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  5341:                                
1.222     brouard  5342:         k=0;
                   5343:         for(i=1; i<= (nlstate); i++){
                   5344:           for(j=1; j<=(nlstate+ndeath);j++){
                   5345:             k=k+1;
                   5346:             gp[k]=pmmij[i][j];
                   5347:           }
                   5348:         }
1.220     brouard  5349:                                
1.222     brouard  5350:         for(i=1; i<=npar; i++)
                   5351:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  5352:                                
1.222     brouard  5353:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   5354:         k=0;
                   5355:         for(i=1; i<=(nlstate); i++){
                   5356:           for(j=1; j<=(nlstate+ndeath);j++){
                   5357:             k=k+1;
                   5358:             gm[k]=pmmij[i][j];
                   5359:           }
                   5360:         }
1.220     brouard  5361:                                
1.222     brouard  5362:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   5363:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   5364:        }
1.126     brouard  5365: 
1.222     brouard  5366:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   5367:         for(theta=1; theta <=npar; theta++)
                   5368:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  5369:                        
1.222     brouard  5370:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   5371:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  5372:                        
1.222     brouard  5373:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  5374:                        
1.222     brouard  5375:        k=0;
                   5376:        for(i=1; i<=(nlstate); i++){
                   5377:         for(j=1; j<=(nlstate+ndeath);j++){
                   5378:           k=k+1;
                   5379:           mu[k][(int) age]=pmmij[i][j];
                   5380:         }
                   5381:        }
                   5382:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   5383:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   5384:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  5385:                        
1.222     brouard  5386:        /*printf("\n%d ",(int)age);
                   5387:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   5388:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   5389:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   5390:         }*/
1.220     brouard  5391:                        
1.222     brouard  5392:        fprintf(ficresprob,"\n%d ",(int)age);
                   5393:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   5394:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  5395:                        
1.222     brouard  5396:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   5397:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   5398:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   5399:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   5400:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   5401:        }
                   5402:        i=0;
                   5403:        for (k=1; k<=(nlstate);k++){
                   5404:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   5405:           i++;
                   5406:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   5407:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   5408:           for (j=1; j<=i;j++){
                   5409:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   5410:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   5411:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   5412:           }
                   5413:         }
                   5414:        }/* end of loop for state */
                   5415:      } /* end of loop for age */
                   5416:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   5417:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   5418:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   5419:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   5420:     
                   5421:      /* Confidence intervalle of pij  */
                   5422:      /*
                   5423:        fprintf(ficgp,"\nunset parametric;unset label");
                   5424:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   5425:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   5426:        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);
                   5427:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   5428:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   5429:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   5430:      */
                   5431:                
                   5432:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   5433:      first1=1;first2=2;
                   5434:      for (k2=1; k2<=(nlstate);k2++){
                   5435:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   5436:         if(l2==k2) continue;
                   5437:         j=(k2-1)*(nlstate+ndeath)+l2;
                   5438:         for (k1=1; k1<=(nlstate);k1++){
                   5439:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   5440:             if(l1==k1) continue;
                   5441:             i=(k1-1)*(nlstate+ndeath)+l1;
                   5442:             if(i<=j) continue;
                   5443:             for (age=bage; age<=fage; age ++){ 
                   5444:               if ((int)age %5==0){
                   5445:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   5446:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   5447:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   5448:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   5449:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   5450:                 c12=cv12/sqrt(v1*v2);
                   5451:                 /* Computing eigen value of matrix of covariance */
                   5452:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5453:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   5454:                 if ((lc2 <0) || (lc1 <0) ){
                   5455:                   if(first2==1){
                   5456:                     first1=0;
                   5457:                     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);
                   5458:                   }
                   5459:                   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);
                   5460:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   5461:                   /* lc2=fabs(lc2); */
                   5462:                 }
1.220     brouard  5463:                                                                
1.222     brouard  5464:                 /* Eigen vectors */
                   5465:                 v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   5466:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   5467:                 v21=(lc1-v1)/cv12*v11;
                   5468:                 v12=-v21;
                   5469:                 v22=v11;
                   5470:                 tnalp=v21/v11;
                   5471:                 if(first1==1){
                   5472:                   first1=0;
                   5473:                   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);
                   5474:                 }
                   5475:                 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);
                   5476:                 /*printf(fignu*/
                   5477:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   5478:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   5479:                 if(first==1){
                   5480:                   first=0;
                   5481:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   5482:                   fprintf(ficgp,"\nset parametric;unset label");
                   5483:                   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);
                   5484:                   fprintf(ficgp,"\nset ter svg size 640, 480");
                   5485:                   fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  5486:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  5487: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  5488:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   5489:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   5490:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   5491:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   5492:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   5493:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   5494:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   5495:                   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",      \
                   5496:                           mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),                                                                         \
                   5497:                           mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   5498:                 }else{
                   5499:                   first=0;
                   5500:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   5501:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   5502:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   5503:                   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", \
                   5504:                           mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),                                 \
                   5505:                           mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   5506:                 }/* if first */
                   5507:               } /* age mod 5 */
                   5508:             } /* end loop age */
                   5509:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   5510:             first=1;
                   5511:           } /*l12 */
                   5512:         } /* k12 */
                   5513:        } /*l1 */
                   5514:      }/* k1 */
                   5515:    }  /* loop on combination of covariates j1 */
                   5516:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   5517:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   5518:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   5519:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   5520:    free_vector(xp,1,npar);
                   5521:    fclose(ficresprob);
                   5522:    fclose(ficresprobcov);
                   5523:    fclose(ficresprobcor);
                   5524:    fflush(ficgp);
                   5525:    fflush(fichtmcov);
                   5526:  }
1.126     brouard  5527: 
                   5528: 
                   5529: /******************* Printing html file ***********/
1.201     brouard  5530: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  5531:                  int lastpass, int stepm, int weightopt, char model[],\
                   5532:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.217     brouard  5533:                  int popforecast, int prevfcast, int backcast, int estepm , \
1.213     brouard  5534:                  double jprev1, double mprev1,double anprev1, double dateprev1, \
                   5535:                  double jprev2, double mprev2,double anprev2, double dateprev2){
1.126     brouard  5536:   int jj1, k1, i1, cpt;
                   5537: 
                   5538:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   5539:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   5540: </ul>");
1.214     brouard  5541:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   5542:    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",
                   5543:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
                   5544:    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  5545:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   5546:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  5547:    fprintf(fichtm,"\
                   5548:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  5549:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  5550:    fprintf(fichtm,"\
1.217     brouard  5551:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   5552:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   5553:    fprintf(fichtm,"\
1.126     brouard  5554:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  5555:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  5556:    fprintf(fichtm,"\
1.217     brouard  5557:  - Period (stable) back prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
                   5558:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   5559:    fprintf(fichtm,"\
1.211     brouard  5560:  - (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  5561:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  5562:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  5563:    if(prevfcast==1){
                   5564:      fprintf(fichtm,"\
                   5565:  - Prevalence projections by age and states:                           \
1.201     brouard  5566:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  5567:    }
1.126     brouard  5568: 
1.222     brouard  5569:    fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
1.126     brouard  5570: 
1.222     brouard  5571:    m=pow(2,cptcoveff);
                   5572:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  5573: 
1.222     brouard  5574:    jj1=0;
                   5575:    for(k1=1; k1<=m;k1++){
1.220     brouard  5576: 
1.222     brouard  5577:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   5578:      jj1++;
                   5579:      if (cptcovn > 0) {
                   5580:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   5581:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
                   5582:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
                   5583:         printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout);
                   5584:        }
                   5585:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   5586:        if(invalidvarcomb[k1]){
                   5587:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   5588:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   5589:         continue;
                   5590:        }
                   5591:      }
                   5592:      /* aij, bij */
                   5593:      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  5594: <img src=\"%s_%d-1.svg\">",model,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
1.222     brouard  5595:      /* Pij */
                   5596:      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  5597: <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);     
1.222     brouard  5598:      /* Quasi-incidences */
                   5599:      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  5600:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  5601:  incidence (rates) are the limit when h tends to zero of the ratio of the probability  <sub>h</sub>P<sub>ij</sub> \
                   5602: 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  5603: <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1); 
1.222     brouard  5604:      /* Survival functions (period) in state j */
                   5605:      for(cpt=1; cpt<=nlstate;cpt++){
                   5606:        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  5607: <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  5608:      }
                   5609:      /* State specific survival functions (period) */
                   5610:      for(cpt=1; cpt<=nlstate;cpt++){
                   5611:        fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
1.220     brouard  5612:  Or probability to survive in various states (1 to %d) being in state %d at different ages.    \
1.201     brouard  5613:  <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  5614:      }
                   5615:      /* Period (stable) prevalence in each health state */
                   5616:      for(cpt=1; cpt<=nlstate;cpt++){
                   5617:        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  5618: <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  5619:      }
                   5620:      if(backcast==1){
                   5621:        /* Period (stable) back prevalence in each health state */
                   5622:        for(cpt=1; cpt<=nlstate;cpt++){
                   5623:         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  5624: <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  5625:        }
1.217     brouard  5626:      }
1.222     brouard  5627:      if(prevfcast==1){
                   5628:        /* Projection of prevalence up to period (stable) prevalence in each health state */
                   5629:        for(cpt=1; cpt<=nlstate;cpt++){
                   5630:         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  5631: <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  5632:        }
                   5633:      }
1.220     brouard  5634:         
1.222     brouard  5635:      for(cpt=1; cpt<=nlstate;cpt++) {
                   5636:        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  5637: <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  5638:      }
                   5639:      /* } /\* end i1 *\/ */
                   5640:    }/* End k1 */
                   5641:    fprintf(fichtm,"</ul>");
1.126     brouard  5642: 
1.222     brouard  5643:    fprintf(fichtm,"\
1.126     brouard  5644: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  5645:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  5646:  - 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  5647: But because parameters are usually highly correlated (a higher incidence of disability \
                   5648: and a higher incidence of recovery can give very close observed transition) it might \
                   5649: be very useful to look not only at linear confidence intervals estimated from the \
                   5650: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   5651: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   5652: covariance matrix of the one-step probabilities. \
                   5653: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  5654: 
1.222     brouard  5655:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   5656:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   5657:    fprintf(fichtm,"\
1.126     brouard  5658:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  5659:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  5660: 
1.222     brouard  5661:    fprintf(fichtm,"\
1.126     brouard  5662:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  5663:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   5664:    fprintf(fichtm,"\
1.126     brouard  5665:  - 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): \
                   5666:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  5667:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  5668:    fprintf(fichtm,"\
1.126     brouard  5669:  - (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): \
                   5670:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  5671:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  5672:    fprintf(fichtm,"\
1.128     brouard  5673:  - 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  5674:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   5675:    fprintf(fichtm,"\
1.128     brouard  5676:  - 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  5677:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   5678:    fprintf(fichtm,"\
1.126     brouard  5679:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  5680:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  5681: 
                   5682: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   5683: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   5684: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   5685: /*     <br>",fileres,fileres,fileres,fileres); */
                   5686: /*  else  */
                   5687: /*    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  5688:    fflush(fichtm);
                   5689:    fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
1.126     brouard  5690: 
1.222     brouard  5691:    m=pow(2,cptcoveff);
                   5692:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  5693: 
1.222     brouard  5694:    jj1=0;
                   5695:    for(k1=1; k1<=m;k1++){
                   5696:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   5697:      jj1++;
1.126     brouard  5698:      if (cptcovn > 0) {
                   5699:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   5700:        for (cpt=1; cpt<=cptcoveff;cpt++) 
1.222     brouard  5701:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
1.126     brouard  5702:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  5703: 
1.222     brouard  5704:        if(invalidvarcomb[k1]){
                   5705:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   5706:         continue;
                   5707:        }
1.126     brouard  5708:      }
                   5709:      for(cpt=1; cpt<=nlstate;cpt++) {
1.218     brouard  5710:        fprintf(fichtm,"\n<br>- Observed (cross-sectional) and period (incidence based) \
                   5711: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d-%d.svg\"> %s_%d-%d.svg</a>\n <br>\
1.205     brouard  5712: <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  5713:      }
                   5714:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  5715: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   5716: true period expectancies (those weighted with period prevalences are also\
                   5717:  drawn in addition to the population based expectancies computed using\
1.218     brouard  5718:  observed and cahotic prevalences:  <a href=\"%s_%d.svg\">%s_%d.svg</a>\n<br>\
1.205     brouard  5719: <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);
1.222     brouard  5720:      /* } /\* end i1 *\/ */
                   5721:    }/* End k1 */
                   5722:    fprintf(fichtm,"</ul>");
                   5723:    fflush(fichtm);
1.126     brouard  5724: }
                   5725: 
                   5726: /******************* Gnuplot file **************/
1.223   ! brouard  5727: void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , int prevfcast, int backcast, char pathc[], double p[]){
1.126     brouard  5728: 
                   5729:   char dirfileres[132],optfileres[132];
1.223   ! brouard  5730:   char gplotcondition[132];
1.164     brouard  5731:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.211     brouard  5732:   int lv=0, vlv=0, kl=0;
1.130     brouard  5733:   int ng=0;
1.201     brouard  5734:   int vpopbased;
1.223   ! brouard  5735:   int ioffset; /* variable offset for columns */
1.219     brouard  5736: 
1.126     brouard  5737: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   5738: /*     printf("Problem with file %s",optionfilegnuplot); */
                   5739: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   5740: /*   } */
                   5741: 
                   5742:   /*#ifdef windows */
                   5743:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223   ! brouard  5744:   /*#endif */
1.126     brouard  5745:   m=pow(2,cptcoveff);
                   5746: 
1.202     brouard  5747:   /* Contribution to likelihood */
                   5748:   /* Plot the probability implied in the likelihood */
1.223   ! brouard  5749:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
        !          5750:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
        !          5751:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
        !          5752:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  5753: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  5754:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   5755: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223   ! brouard  5756:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
        !          5757:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
        !          5758:   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));
        !          5759:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
        !          5760:   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));
        !          5761:   for (i=1; i<= nlstate ; i ++) {
        !          5762:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
        !          5763:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
        !          5764:     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);
        !          5765:     for (j=2; j<= nlstate+ndeath ; j ++) {
        !          5766:       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);
        !          5767:     }
        !          5768:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
        !          5769:   }
        !          5770:   /* 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 */               
        !          5771:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
        !          5772:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
        !          5773:   fprintf(ficgp,"\nset out;unset log\n");
        !          5774:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  5775: 
1.126     brouard  5776:   strcpy(dirfileres,optionfilefiname);
                   5777:   strcpy(optfileres,"vpl");
1.223   ! brouard  5778:   /* 1eme*/
1.211     brouard  5779:   for (cpt=1; cpt<= nlstate ; cpt ++) { /* For each live state */
1.220     brouard  5780:     for (k1=1; k1<= m ; k1 ++) { /* For each valid combination of covariate */
1.211     brouard  5781:       /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
                   5782:       fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files ");
1.219     brouard  5783:       for (k=1; k<=cptcoveff; k++){    /* For each covariate k get corresponding value lv for combination k1 */
1.223   ! brouard  5784:        lv= decodtabm(k1,k,cptcoveff); /* Should be the value of the covariate corresponding to k1 combination */
        !          5785:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
        !          5786:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
        !          5787:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
        !          5788:        vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
        !          5789:        /* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
        !          5790:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  5791:       }
                   5792:       fprintf(ficgp,"\n#\n");
1.223   ! brouard  5793:       if(invalidvarcomb[k1]){
        !          5794:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
        !          5795:        continue;
        !          5796:       }
1.211     brouard  5797: 
1.223   ! brouard  5798:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);
        !          5799:       fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);
        !          5800:       fprintf(ficgp,"set xlabel \"Age\" \n\
1.219     brouard  5801: set ylabel \"Probability\" \n  \
                   5802: set ter svg size 640, 480\n    \
1.201     brouard  5803: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);
1.219     brouard  5804:                        
1.223   ! brouard  5805:       for (i=1; i<= nlstate ; i ++) {
        !          5806:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
        !          5807:        else        fprintf(ficgp," %%*lf (%%*lf)");
        !          5808:       }
        !          5809:       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);
        !          5810:       for (i=1; i<= nlstate ; i ++) {
        !          5811:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
        !          5812:        else fprintf(ficgp," %%*lf (%%*lf)");
        !          5813:       } 
        !          5814:       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); 
        !          5815:       for (i=1; i<= nlstate ; i ++) {
        !          5816:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
        !          5817:        else fprintf(ficgp," %%*lf (%%*lf)");
        !          5818:       }  
        !          5819:       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));
        !          5820:       if(backcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
        !          5821:        /* 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); */
        !          5822:        fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1 */
        !          5823:        if(cptcoveff ==0){
        !          5824:          fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line ",  2+(cpt-1),  cpt );
        !          5825:        }else{
        !          5826:          kl=0;
        !          5827:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
        !          5828:            lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
        !          5829:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
        !          5830:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
        !          5831:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
        !          5832:            vlv= nbcode[Tvaraff[k]][lv];
        !          5833:            kl++;
        !          5834:            /* 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 *\/ */
        !          5835:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
        !          5836:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
        !          5837:            /* ''  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*/
        !          5838:            if(k==cptcoveff){
        !          5839:              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], \
        !          5840:                      6+(cpt-1),  cpt );
        !          5841:            }else{
        !          5842:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
        !          5843:              kl++;
        !          5844:            }
        !          5845:          } /* end covariate */
        !          5846:        } /* end if no covariate */
        !          5847:       } /* end if backcast */
        !          5848:       fprintf(ficgp,"\nset out \n");
1.201     brouard  5849:     } /* k1 */
                   5850:   } /* cpt */
1.126     brouard  5851:   /*2 eme*/
                   5852:   for (k1=1; k1<= m ; k1 ++) { 
1.220     brouard  5853: 
1.223   ! brouard  5854:     fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
        !          5855:     for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
        !          5856:       lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
        !          5857:       /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
        !          5858:       /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
        !          5859:       /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
        !          5860:       vlv= nbcode[Tvaraff[k]][lv];
        !          5861:       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
        !          5862:     }
        !          5863:     fprintf(ficgp,"\n#\n");
        !          5864:     if(invalidvarcomb[k1]){
        !          5865:       fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
        !          5866:       continue;
        !          5867:     }
1.219     brouard  5868:                        
1.223   ! brouard  5869:     fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);
        !          5870:     for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
        !          5871:       if(vpopbased==0)
        !          5872:        fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
        !          5873:       else
        !          5874:        fprintf(ficgp,"\nreplot ");
        !          5875:       for (i=1; i<= nlstate+1 ; i ++) {
        !          5876:        k=2*i;
        !          5877:        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);
        !          5878:        for (j=1; j<= nlstate+1 ; j ++) {
        !          5879:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
        !          5880:          else fprintf(ficgp," %%*lf (%%*lf)");
        !          5881:        }   
        !          5882:        if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
        !          5883:        else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
        !          5884:        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);
        !          5885:        for (j=1; j<= nlstate+1 ; j ++) {
        !          5886:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
        !          5887:          else fprintf(ficgp," %%*lf (%%*lf)");
        !          5888:        }   
        !          5889:        fprintf(ficgp,"\" t\"\" w l lt 0,");
        !          5890:        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);
        !          5891:        for (j=1; j<= nlstate+1 ; j ++) {
        !          5892:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
        !          5893:          else fprintf(ficgp," %%*lf (%%*lf)");
        !          5894:        }   
        !          5895:        if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
        !          5896:        else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
        !          5897:       } /* state */
        !          5898:     } /* vpopbased */
        !          5899:     fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
1.201     brouard  5900:   } /* k1 */
1.219     brouard  5901:        
                   5902:        
1.126     brouard  5903:   /*3eme*/
                   5904:   for (k1=1; k1<= m ; k1 ++) { 
1.220     brouard  5905: 
1.126     brouard  5906:     for (cpt=1; cpt<= nlstate ; cpt ++) {
1.211     brouard  5907:       fprintf(ficgp,"\n# 3d: Life expectancy with EXP_ files:  cov=%d state=%d",k1, cpt);
                   5908:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.223   ! brouard  5909:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
        !          5910:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
        !          5911:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
        !          5912:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
        !          5913:        vlv= nbcode[Tvaraff[k]][lv];
        !          5914:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  5915:       }
                   5916:       fprintf(ficgp,"\n#\n");
1.223   ! brouard  5917:       if(invalidvarcomb[k1]){
        !          5918:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
        !          5919:        continue;
        !          5920:       }
1.219     brouard  5921:                        
1.126     brouard  5922:       /*       k=2+nlstate*(2*cpt-2); */
                   5923:       k=2+(nlstate+1)*(cpt-1);
1.201     brouard  5924:       fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);
1.199     brouard  5925:       fprintf(ficgp,"set ter svg size 640, 480\n\
1.201     brouard  5926: 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  5927:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
1.223   ! brouard  5928:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
        !          5929:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
        !          5930:        fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
        !          5931:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
        !          5932:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  5933:                                
1.126     brouard  5934:       */
                   5935:       for (i=1; i< nlstate ; i ++) {
1.223   ! brouard  5936:        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);
        !          5937:        /*      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  5938:                                
1.126     brouard  5939:       } 
1.201     brouard  5940:       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  5941:     }
                   5942:   }
                   5943:   
1.223   ! brouard  5944:   /* 4eme */
1.201     brouard  5945:   /* Survival functions (period) from state i in state j by initial state i */
                   5946:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
1.220     brouard  5947: 
1.201     brouard  5948:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.211     brouard  5949:       fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
                   5950:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.223   ! brouard  5951:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
        !          5952:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
        !          5953:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
        !          5954:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
        !          5955:        vlv= nbcode[Tvaraff[k]][lv];
        !          5956:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  5957:       }
                   5958:       fprintf(ficgp,"\n#\n");
1.223   ! brouard  5959:       if(invalidvarcomb[k1]){
        !          5960:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
        !          5961:        continue;
        !          5962:       }
1.220     brouard  5963:                        
1.201     brouard  5964:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);
                   5965:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
1.220     brouard  5966: set ter svg size 640, 480\n                                                                                                                                                                                    \
                   5967: unset log y\n                                                                                                                                                                                                                                          \
1.201     brouard  5968: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  5969:       k=3;
1.201     brouard  5970:       for (i=1; i<= nlstate ; i ++){
1.223   ! brouard  5971:        if(i==1){
        !          5972:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
        !          5973:        }else{
        !          5974:          fprintf(ficgp,", '' ");
        !          5975:        }
        !          5976:        l=(nlstate+ndeath)*(i-1)+1;
        !          5977:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
        !          5978:        for (j=2; j<= nlstate+ndeath ; j ++)
        !          5979:          fprintf(ficgp,"+$%d",k+l+j-1);
        !          5980:        fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
1.201     brouard  5981:       } /* nlstate */
                   5982:       fprintf(ficgp,"\nset out\n");
                   5983:     } /* end cpt state*/ 
                   5984:   } /* end covariate */  
1.220     brouard  5985:        
                   5986: /* 5eme */
1.201     brouard  5987:   /* Survival functions (period) from state i in state j by final state j */
1.202     brouard  5988:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
1.201     brouard  5989:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.223   ! brouard  5990:                        
1.201     brouard  5991:       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.211     brouard  5992:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.220     brouard  5993:                                lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   5994:                                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5995:                                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5996:                                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5997:                                vlv= nbcode[Tvaraff[k]][lv];
                   5998:                                fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  5999:       }
                   6000:       fprintf(ficgp,"\n#\n");
1.223   ! brouard  6001:       if(invalidvarcomb[k1]){
        !          6002:                                fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
        !          6003:                                continue;
        !          6004:       }
1.220     brouard  6005:                        
1.201     brouard  6006:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);
                   6007:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
1.220     brouard  6008: set ter svg size 640, 480\n                                                                                                                                                                                    \
                   6009: unset log y\n                                                                                                                                                                                                                                          \
1.201     brouard  6010: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  6011:       k=3;
1.201     brouard  6012:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
1.220     brouard  6013:                                if(j==1)
                   6014:                                        fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   6015:                                else
                   6016:                                        fprintf(ficgp,", '' ");
                   6017:                                l=(nlstate+ndeath)*(cpt-1) +j;
                   6018:                                fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   6019:                                /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   6020:                                /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   6021:                                fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
1.201     brouard  6022:       } /* nlstate */
                   6023:       fprintf(ficgp,", '' ");
                   6024:       fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   6025:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
1.220     brouard  6026:                                l=(nlstate+ndeath)*(cpt-1) +j;
                   6027:                                if(j < nlstate)
                   6028:                                        fprintf(ficgp,"$%d +",k+l);
                   6029:                                else
                   6030:                                        fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
1.201     brouard  6031:       }
                   6032:       fprintf(ficgp,"\nset out\n");
                   6033:     } /* end cpt state*/ 
                   6034:   } /* end covariate */  
1.220     brouard  6035:        
                   6036: /* 6eme */
1.202     brouard  6037:   /* CV preval stable (period) for each covariate */
1.211     brouard  6038:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
1.153     brouard  6039:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.223   ! brouard  6040:                        
1.211     brouard  6041:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
                   6042:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.220     brouard  6043:                                lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6044:                                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6045:                                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6046:                                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6047:                                vlv= nbcode[Tvaraff[k]][lv];
                   6048:                                fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  6049:       }
                   6050:       fprintf(ficgp,"\n#\n");
1.223   ! brouard  6051:       if(invalidvarcomb[k1]){
        !          6052:                                fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
        !          6053:                                continue;
        !          6054:       }
        !          6055:                        
1.201     brouard  6056:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);
1.126     brouard  6057:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.223   ! brouard  6058: set ter svg size 640, 480\n                                                                                                                                                                             \
        !          6059: unset log y\n                                                                                                                                                                                                                                   \
1.153     brouard  6060: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  6061:       k=3; /* Offset */
1.153     brouard  6062:       for (i=1; i<= nlstate ; i ++){
1.220     brouard  6063:                                if(i==1)
                   6064:                                        fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   6065:                                else
                   6066:                                        fprintf(ficgp,", '' ");
                   6067:                                l=(nlstate+ndeath)*(i-1)+1;
                   6068:                                fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   6069:                                for (j=2; j<= nlstate ; j ++)
                   6070:                                        fprintf(ficgp,"+$%d",k+l+j-1);
                   6071:                                fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  6072:       } /* nlstate */
1.201     brouard  6073:       fprintf(ficgp,"\nset out\n");
1.153     brouard  6074:     } /* end cpt state*/ 
                   6075:   } /* end covariate */  
1.223   ! brouard  6076:        
        !          6077:        
1.220     brouard  6078: /* 7eme */
1.218     brouard  6079:   if(backcast == 1){
1.217     brouard  6080:     /* CV back preval stable (period) for each covariate */
1.218     brouard  6081:     for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
                   6082:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.220     brouard  6083:                                fprintf(ficgp,"\n#\n#\n#CV Back preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
                   6084:                                for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6085:                                        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6086:                                        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6087:                                        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
1.223   ! brouard  6088:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.220     brouard  6089:                                        vlv= nbcode[Tvaraff[k]][lv];
                   6090:                                        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6091:                                }
                   6092:                                fprintf(ficgp,"\n#\n");
                   6093:                                if(invalidvarcomb[k1]){
1.223   ! brouard  6094:                                        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
        !          6095:                                        continue;
1.220     brouard  6096:                                }
                   6097:                                
                   6098:                                fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1);
                   6099:                                fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
                   6100: set ter svg size 640, 480\n                                                                                                                                                                                    \
                   6101: unset log y\n                                                                                                                                                                                                                                          \
1.218     brouard  6102: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.220     brouard  6103:                                k=3; /* Offset */
                   6104:                                for (i=1; i<= nlstate ; i ++){
                   6105:                                        if(i==1)
                   6106:                                                fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   6107:                                        else
                   6108:                                                fprintf(ficgp,", '' ");
                   6109:                                        /* l=(nlstate+ndeath)*(i-1)+1; */
                   6110:                                        l=(nlstate+ndeath)*(cpt-1)+1;
                   6111:                                        /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   6112:                                        /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l+(cpt-1)+i-1); /\* a vérifier *\/ */
                   6113:                                        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+(cpt-1)+i-1); /* a vérifier */
                   6114:                                        /* for (j=2; j<= nlstate ; j ++) */
                   6115:                                        /*      fprintf(ficgp,"+$%d",k+l+j-1); */
                   6116:                                        /*      /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
                   6117:                                        fprintf(ficgp,") t \"bprev(%d,%d)\" w l",i,cpt);
                   6118:                                } /* nlstate */
                   6119:                                fprintf(ficgp,"\nset out\n");
1.218     brouard  6120:       } /* end cpt state*/ 
                   6121:     } /* end covariate */  
                   6122:   } /* End if backcast */
                   6123:   
1.223   ! brouard  6124:   /* 8eme */
1.218     brouard  6125:   if(prevfcast==1){
                   6126:     /* Projection from cross-sectional to stable (period) for each covariate */
                   6127:     
                   6128:     for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
1.211     brouard  6129:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.219     brouard  6130:                                fprintf(ficgp,"\n#\n#\n#Projection of prevalence to stable (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
                   6131:                                for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   6132:                                        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   6133:                                        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6134:                                        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6135:                                        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6136:                                        vlv= nbcode[Tvaraff[k]][lv];
1.220     brouard  6137:                                        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.219     brouard  6138:                                }
                   6139:                                fprintf(ficgp,"\n#\n");
1.220     brouard  6140:                                if(invalidvarcomb[k1]){
1.223   ! brouard  6141:                                        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
        !          6142:                                        continue;
1.220     brouard  6143:                                }
1.219     brouard  6144:                                
                   6145:                                fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
                   6146:                                fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1);
                   6147:                                fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.223   ! brouard  6148: set ter svg size 640, 480\n                                                                                                                                                                                    \
        !          6149: unset log y\n                                                                                                                                                                                                                                          \
1.219     brouard  6150: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   6151:                                for (i=1; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   6152:                                        /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   6153:                                        /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   6154:                                        /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   6155:                                        /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   6156:                                        if(i==1){
                   6157:                                                fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   6158:                                        }else{
                   6159:                                                fprintf(ficgp,",\\\n '' ");
                   6160:                                        }
                   6161:                                        if(cptcoveff ==0){ /* No covariate */
                   6162:                                                ioffset=2; /* Age is in 2 */
                   6163:                                                /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   6164:                                                /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   6165:                                                /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   6166:                                                /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   6167:                                                fprintf(ficgp," u %d:(", ioffset); 
                   6168:                                                if(i==nlstate+1)
                   6169:                                                        fprintf(ficgp," $%d/(1.-$%d)) t 'pw.%d' with line ",                    \
                   6170:                                                                                        ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   6171:                                                else
                   6172:                                                        fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",                    \
                   6173:                                                                                        ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   6174:                                        }else{ /* more than 2 covariates */
                   6175:                                                if(cptcoveff ==1){
                   6176:                                                        ioffset=4; /* Age is in 4 */
                   6177:                                                }else{
                   6178:                                                        ioffset=6; /* Age is in 6 */
1.223   ! brouard  6179:                                                        /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
        !          6180:                                                        /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
1.219     brouard  6181:                                                }   
1.220     brouard  6182:                                                fprintf(ficgp," u %d:(",ioffset); 
1.219     brouard  6183:                                                kl=0;
1.220     brouard  6184:                                                strcpy(gplotcondition,"(");
                   6185:                                                for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
1.219     brouard  6186:                                                        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   6187:                                                        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6188:                                                        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6189:                                                        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.220     brouard  6190:                                                        vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   6191:                                                        kl++;
                   6192:                                                        sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
1.219     brouard  6193:                                                        kl++;
1.220     brouard  6194:                                                        if(k <cptcoveff && cptcoveff>1)
                   6195:                                                                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   6196:                                                }
                   6197:                                                strcpy(gplotcondition+strlen(gplotcondition),")");
                   6198:                                                /* 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 *\/ */
                   6199:                                                /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   6200:                                                /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   6201:                                                /* ''  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*/
                   6202:                                                if(i==nlstate+1){
                   6203:                                                        fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p.%d' with line ", gplotcondition, \
                   6204:                                                                                        ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   6205:                                                }else{
1.223   ! brouard  6206:                                                        fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
        !          6207:                                                                                        ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
1.220     brouard  6208:                                                }
1.219     brouard  6209:                                        } /* end if covariate */
                   6210:                                } /* nlstate */
                   6211:                                fprintf(ficgp,"\nset out\n");
1.223   ! brouard  6212:       } /* end cpt state*/
        !          6213:     } /* end covariate */
        !          6214:   } /* End if prevfcast */
1.219     brouard  6215:        
1.211     brouard  6216:        
1.223   ! brouard  6217:   /* proba elementaires */
        !          6218:   fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
1.126     brouard  6219:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  6220:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  6221:     for(k=1; k <=(nlstate+ndeath); k++){
                   6222:       if (k != i) {
1.223   ! brouard  6223:                                fprintf(ficgp,"#   current state %d\n",k);
        !          6224:                                for(j=1; j <=ncovmodel; j++){
        !          6225:                                        fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
        !          6226:                                        jk++; 
        !          6227:                                }
        !          6228:                                fprintf(ficgp,"\n");
1.126     brouard  6229:       }
                   6230:     }
1.223   ! brouard  6231:   }
1.187     brouard  6232:   fprintf(ficgp,"##############\n#\n");
1.223   ! brouard  6233:        
1.145     brouard  6234:   /*goto avoid;*/
1.200     brouard  6235:   fprintf(ficgp,"\n##############\n#Graphics of probabilities or incidences\n#############\n");
1.187     brouard  6236:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   6237:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   6238:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   6239:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   6240:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6241:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   6242:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6243:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   6244:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   6245:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   6246:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   6247:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   6248:   fprintf(ficgp,"#\n");
1.223   ! brouard  6249:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
        !          6250:     fprintf(ficgp,"# ng=%d\n",ng);
        !          6251:     fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);
        !          6252:     for(jk=1; jk <=m; jk++) {
        !          6253:       fprintf(ficgp,"#    jk=%d\n",jk);
        !          6254:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);
        !          6255:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
        !          6256:       if (ng==1){
        !          6257:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
        !          6258:        fprintf(ficgp,"\nunset log y");
        !          6259:       }else if (ng==2){
        !          6260:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
        !          6261:        fprintf(ficgp,"\nset log y");
        !          6262:       }else if (ng==3){
        !          6263:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
        !          6264:        fprintf(ficgp,"\nset log y");
        !          6265:       }else
        !          6266:        fprintf(ficgp,"\nunset title ");
        !          6267:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
        !          6268:       i=1;
        !          6269:       for(k2=1; k2<=nlstate; k2++) {
        !          6270:        k3=i;
        !          6271:        for(k=1; k<=(nlstate+ndeath); k++) {
        !          6272:          if (k != k2){
        !          6273:            switch( ng) {
        !          6274:            case 1:
        !          6275:              if(nagesqr==0)
        !          6276:                fprintf(ficgp," p%d+p%d*x",i,i+1);
        !          6277:              else /* nagesqr =1 */
        !          6278:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
        !          6279:              break;
        !          6280:            case 2: /* ng=2 */
        !          6281:              if(nagesqr==0)
        !          6282:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
        !          6283:              else /* nagesqr =1 */
        !          6284:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
        !          6285:              break;
        !          6286:            case 3:
        !          6287:              if(nagesqr==0)
        !          6288:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
        !          6289:              else /* nagesqr =1 */
        !          6290:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
        !          6291:              break;
        !          6292:            }
        !          6293:            ij=1;/* To be checked else nbcode[0][0] wrong */
        !          6294:            for(j=3; j <=ncovmodel-nagesqr; j++) {
        !          6295:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
        !          6296:              if(ij <=cptcovage) { /* Bug valgrind */
        !          6297:                if((j-2)==Tage[ij]) { /* Bug valgrind */
        !          6298:                  fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
        !          6299:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
        !          6300:                  ij++;
        !          6301:                }
        !          6302:              }
        !          6303:              else
        !          6304:                fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
        !          6305:            }
        !          6306:          }else{
        !          6307:            i=i-ncovmodel;
        !          6308:            if(ng !=1 ) /* For logit formula of log p11 is more difficult to get */
        !          6309:              fprintf(ficgp," (1.");
        !          6310:          }
1.217     brouard  6311:           
1.223   ! brouard  6312:          if(ng != 1){
        !          6313:            fprintf(ficgp,")/(1");
1.126     brouard  6314:             
1.223   ! brouard  6315:            for(k1=1; k1 <=nlstate; k1++){ 
        !          6316:              if(nagesqr==0)
        !          6317:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
        !          6318:              else /* nagesqr =1 */
        !          6319:                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  6320:               
1.223   ! brouard  6321:              ij=1;
        !          6322:              for(j=3; j <=ncovmodel-nagesqr; j++){
        !          6323:                if(ij <=cptcovage) { /* Bug valgrind */
        !          6324:                  if((j-2)==Tage[ij]) { /* Bug valgrind */
        !          6325:                    fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
        !          6326:                    /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
        !          6327:                    ij++;
        !          6328:                  }
        !          6329:                }
        !          6330:                else
        !          6331:                  fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
        !          6332:              }
        !          6333:              fprintf(ficgp,")");
        !          6334:            }
        !          6335:            fprintf(ficgp,")");
        !          6336:            if(ng ==2)
        !          6337:              fprintf(ficgp," t \"p%d%d\" ", k2,k);
        !          6338:            else /* ng= 3 */
        !          6339:              fprintf(ficgp," t \"i%d%d\" ", k2,k);
        !          6340:          }else{ /* end ng <> 1 */
        !          6341:            if( k !=k2) /* logit p11 is hard to draw */
        !          6342:              fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
        !          6343:          }
        !          6344:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
        !          6345:            fprintf(ficgp,",");
        !          6346:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
        !          6347:            fprintf(ficgp,",");
        !          6348:          i=i+ncovmodel;
        !          6349:        } /* end k */
        !          6350:       } /* end k2 */
        !          6351:       fprintf(ficgp,"\n set out\n");
        !          6352:     } /* end jk */
        !          6353:   } /* end ng */
        !          6354:   /* avoid: */
        !          6355:   fflush(ficgp); 
1.126     brouard  6356: }  /* end gnuplot */
                   6357: 
                   6358: 
                   6359: /*************** Moving average **************/
1.219     brouard  6360: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  6361:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  6362:    
1.222     brouard  6363:    int i, cpt, cptcod;
                   6364:    int modcovmax =1;
                   6365:    int mobilavrange, mob;
                   6366:    int iage=0;
                   6367: 
                   6368:    double sum=0.;
                   6369:    double age;
                   6370:    double *sumnewp, *sumnewm;
                   6371:    double *agemingood, *agemaxgood; /* Currently identical for all covariates */
                   6372:   
                   6373:   
                   6374:    /* modcovmax=2*cptcoveff;/\* Max number of modalities. We suppose  */
                   6375:    /*             a covariate has 2 modalities, should be equal to ncovcombmax  *\/ */
                   6376: 
                   6377:    sumnewp = vector(1,ncovcombmax);
                   6378:    sumnewm = vector(1,ncovcombmax);
                   6379:    agemingood = vector(1,ncovcombmax); 
                   6380:    agemaxgood = vector(1,ncovcombmax);
                   6381: 
                   6382:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   6383:      sumnewm[cptcod]=0.;
                   6384:      sumnewp[cptcod]=0.;
                   6385:      agemingood[cptcod]=0;
                   6386:      agemaxgood[cptcod]=0;
                   6387:    }
                   6388:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   6389:   
                   6390:    if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   6391:      if(mobilav==1) mobilavrange=5; /* default */
                   6392:      else mobilavrange=mobilav;
                   6393:      for (age=bage; age<=fage; age++)
                   6394:        for (i=1; i<=nlstate;i++)
                   6395:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   6396:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   6397:      /* We keep the original values on the extreme ages bage, fage and for 
                   6398:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   6399:        we use a 5 terms etc. until the borders are no more concerned. 
                   6400:      */ 
                   6401:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   6402:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   6403:         for (i=1; i<=nlstate;i++){
                   6404:           for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   6405:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   6406:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   6407:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   6408:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   6409:             }
                   6410:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   6411:           }
                   6412:         }
                   6413:        }/* end age */
                   6414:      }/* end mob */
                   6415:    }else
                   6416:      return -1;
                   6417:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   6418:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   6419:      if(invalidvarcomb[cptcod]){
                   6420:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   6421:        continue;
                   6422:      }
1.219     brouard  6423: 
1.222     brouard  6424:      agemingood[cptcod]=fage-(mob-1)/2;
                   6425:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, finding the youngest wrong */
                   6426:        sumnewm[cptcod]=0.;
                   6427:        for (i=1; i<=nlstate;i++){
                   6428:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   6429:        }
                   6430:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   6431:         agemingood[cptcod]=age;
                   6432:        }else{ /* bad */
                   6433:         for (i=1; i<=nlstate;i++){
                   6434:           mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   6435:         } /* i */
                   6436:        } /* end bad */
                   6437:      }/* age */
                   6438:      sum=0.;
                   6439:      for (i=1; i<=nlstate;i++){
                   6440:        sum+=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   6441:      }
                   6442:      if(fabs(sum - 1.) > 1.e-3) { /* bad */
                   6443:        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);
                   6444:        /* for (i=1; i<=nlstate;i++){ */
                   6445:        /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   6446:        /* } /\* i *\/ */
                   6447:      } /* end bad */
                   6448:      /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   6449:      /* From youngest, finding the oldest wrong */
                   6450:      agemaxgood[cptcod]=bage+(mob-1)/2;
                   6451:      for (age=bage+(mob-1)/2; age<=fage; age++){
                   6452:        sumnewm[cptcod]=0.;
                   6453:        for (i=1; i<=nlstate;i++){
                   6454:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   6455:        }
                   6456:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   6457:         agemaxgood[cptcod]=age;
                   6458:        }else{ /* bad */
                   6459:         for (i=1; i<=nlstate;i++){
                   6460:           mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   6461:         } /* i */
                   6462:        } /* end bad */
                   6463:      }/* age */
                   6464:      sum=0.;
                   6465:      for (i=1; i<=nlstate;i++){
                   6466:        sum+=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   6467:      }
                   6468:      if(fabs(sum - 1.) > 1.e-3) { /* bad */
                   6469:        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);
                   6470:        /* for (i=1; i<=nlstate;i++){ */
                   6471:        /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   6472:        /* } /\* i *\/ */
                   6473:      } /* end bad */
                   6474:                
                   6475:      for (age=bage; age<=fage; age++){
                   6476:        printf("%d %d ", cptcod, (int)age);
                   6477:        sumnewp[cptcod]=0.;
                   6478:        sumnewm[cptcod]=0.;
                   6479:        for (i=1; i<=nlstate;i++){
                   6480:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   6481:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   6482:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   6483:        }
                   6484:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   6485:      }
                   6486:      /* printf("\n"); */
                   6487:      /* } */
                   6488:      /* brutal averaging */
                   6489:      for (i=1; i<=nlstate;i++){
                   6490:        for (age=1; age<=bage; age++){
                   6491:         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   6492:         /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
                   6493:        }       
                   6494:        for (age=fage; age<=AGESUP; age++){
                   6495:         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   6496:         /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
                   6497:        }
                   6498:      } /* end i status */
                   6499:      for (i=nlstate+1; i<=nlstate+ndeath;i++){
                   6500:        for (age=1; age<=AGESUP; age++){
                   6501:         /*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*/
                   6502:         mobaverage[(int)age][i][cptcod]=0.;
                   6503:        }
                   6504:      }
                   6505:    }/* end cptcod */
                   6506:    free_vector(sumnewm,1, ncovcombmax);
                   6507:    free_vector(sumnewp,1, ncovcombmax);
                   6508:    free_vector(agemaxgood,1, ncovcombmax);
                   6509:    free_vector(agemingood,1, ncovcombmax);
                   6510:    return 0;
                   6511:  }/* End movingaverage */
1.218     brouard  6512:  
1.126     brouard  6513: 
                   6514: /************** Forecasting ******************/
1.169     brouard  6515: void prevforecast(char fileres[], double anproj1, double mproj1, double jproj1, double ageminpar, double agemax, double dateprev1, double dateprev2, int mobilav, double bage, double fage, int firstpass, int lastpass, double anproj2, double p[], int cptcoveff){
1.126     brouard  6516:   /* proj1, year, month, day of starting projection 
                   6517:      agemin, agemax range of age
                   6518:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   6519:      anproj2 year of en of projection (same day and month as proj1).
                   6520:   */
1.164     brouard  6521:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126     brouard  6522:   double agec; /* generic age */
                   6523:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   6524:   double *popeffectif,*popcount;
                   6525:   double ***p3mat;
1.218     brouard  6526:   /* double ***mobaverage; */
1.126     brouard  6527:   char fileresf[FILENAMELENGTH];
                   6528: 
                   6529:   agelim=AGESUP;
1.211     brouard  6530:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   6531:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   6532:      We still use firstpass and lastpass as another selection.
                   6533:   */
1.214     brouard  6534:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   6535:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  6536:  
1.201     brouard  6537:   strcpy(fileresf,"F_"); 
                   6538:   strcat(fileresf,fileresu);
1.126     brouard  6539:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   6540:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   6541:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   6542:   }
1.215     brouard  6543:   printf("Computing forecasting: result on file '%s', please wait... \n", fileresf);
                   6544:   fprintf(ficlog,"Computing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  6545: 
                   6546:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   6547: 
                   6548: 
                   6549:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   6550:   if (stepm<=12) stepsize=1;
                   6551:   if(estepm < stepm){
                   6552:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6553:   }
                   6554:   else  hstepm=estepm;   
                   6555: 
                   6556:   hstepm=hstepm/stepm; 
                   6557:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   6558:                                fractional in yp1 */
                   6559:   anprojmean=yp;
                   6560:   yp2=modf((yp1*12),&yp);
                   6561:   mprojmean=yp;
                   6562:   yp1=modf((yp2*30.5),&yp);
                   6563:   jprojmean=yp;
                   6564:   if(jprojmean==0) jprojmean=1;
                   6565:   if(mprojmean==0) jprojmean=1;
                   6566: 
                   6567:   i1=cptcoveff;
                   6568:   if (cptcovn < 1){i1=1;}
                   6569:   
                   6570:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   6571:   
                   6572:   fprintf(ficresf,"#****** Routine prevforecast **\n");
                   6573: 
                   6574: /*           if (h==(int)(YEARM*yearp)){ */
                   6575:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
                   6576:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   6577:       k=k+1;
1.211     brouard  6578:       fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
1.126     brouard  6579:       for(j=1;j<=cptcoveff;j++) {
1.219     brouard  6580:                                fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  6581:       }
1.211     brouard  6582:       fprintf(ficresf," yearproj age");
1.126     brouard  6583:       for(j=1; j<=nlstate+ndeath;j++){ 
1.219     brouard  6584:                                for(i=1; i<=nlstate;i++)              
1.126     brouard  6585:           fprintf(ficresf," p%d%d",i,j);
1.219     brouard  6586:                                fprintf(ficresf," wp.%d",j);
1.126     brouard  6587:       }
1.217     brouard  6588:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
1.219     brouard  6589:                                fprintf(ficresf,"\n");
                   6590:                                fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   6591:                                for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   6592:                                        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   6593:                                        nhstepm = nhstepm/hstepm; 
                   6594:                                        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6595:                                        oldm=oldms;savm=savms;
                   6596:                                        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);
                   6597:                                        
                   6598:                                        for (h=0; h<=nhstepm; h++){
                   6599:                                                if (h*hstepm/YEARM*stepm ==yearp) {
1.126     brouard  6600:               fprintf(ficresf,"\n");
                   6601:               for(j=1;j<=cptcoveff;j++) 
1.198     brouard  6602:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.219     brouard  6603:                                                        fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   6604:                                                } 
                   6605:                                                for(j=1; j<=nlstate+ndeath;j++) {
                   6606:                                                        ppij=0.;
                   6607:                                                        for(i=1; i<=nlstate;i++) {
                   6608:                                                                if (mobilav==1) 
                   6609:                                                                        ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
                   6610:                                                                else {
                   6611:                                                                        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
                   6612:                                                                }
                   6613:                                                                if (h*hstepm/YEARM*stepm== yearp) {
                   6614:                                                                        fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   6615:                                                                }
                   6616:                                                        } /* end i */
                   6617:                                                        if (h*hstepm/YEARM*stepm==yearp) {
                   6618:                                                                fprintf(ficresf," %.3f", ppij);
                   6619:                                                        }
                   6620:                                                }/* end j */
                   6621:                                        } /* end h */
                   6622:                                        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6623:                                } /* end agec */
1.126     brouard  6624:       } /* end yearp */
                   6625:     } /* end cptcod */
                   6626:   } /* end  cptcov */
1.219     brouard  6627:        
1.126     brouard  6628:   fclose(ficresf);
1.215     brouard  6629:   printf("End of Computing forecasting \n");
                   6630:   fprintf(ficlog,"End of Computing forecasting\n");
                   6631: 
1.126     brouard  6632: }
                   6633: 
1.218     brouard  6634: /* /\************** Back Forecasting ******************\/ */
                   6635: /* void prevbackforecast(char fileres[], double anback1, double mback1, double jback1, double ageminpar, double agemax, double dateprev1, double dateprev2, int mobilav, double bage, double fage, int firstpass, int lastpass, double anback2, double p[], int cptcoveff){ */
                   6636: /*   /\* back1, year, month, day of starting backection  */
                   6637: /*      agemin, agemax range of age */
                   6638: /*      dateprev1 dateprev2 range of dates during which prevalence is computed */
                   6639: /*      anback2 year of en of backection (same day and month as back1). */
                   6640: /*   *\/ */
                   6641: /*   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1; */
                   6642: /*   double agec; /\* generic age *\/ */
                   6643: /*   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean; */
                   6644: /*   double *popeffectif,*popcount; */
                   6645: /*   double ***p3mat; */
                   6646: /*   /\* double ***mobaverage; *\/ */
                   6647: /*   char fileresfb[FILENAMELENGTH]; */
                   6648:        
                   6649: /*   agelim=AGESUP; */
                   6650: /*   /\* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people */
                   6651: /*      in each health status at the date of interview (if between dateprev1 and dateprev2). */
                   6652: /*      We still use firstpass and lastpass as another selection. */
                   6653: /*   *\/ */
                   6654: /*   /\* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ *\/ */
                   6655: /*   /\*             firstpass, lastpass,  stepm,  weightopt, model); *\/ */
                   6656: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   6657:        
                   6658: /*   strcpy(fileresfb,"FB_");  */
                   6659: /*   strcat(fileresfb,fileresu); */
                   6660: /*   if((ficresfb=fopen(fileresfb,"w"))==NULL) { */
                   6661: /*     printf("Problem with back forecast resultfile: %s\n", fileresfb); */
                   6662: /*     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb); */
                   6663: /*   } */
                   6664: /*   printf("Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
                   6665: /*   fprintf(ficlog,"Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
                   6666:        
                   6667: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
                   6668:        
                   6669: /*   /\* if (mobilav!=0) { *\/ */
                   6670: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   6671: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   6672: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   6673: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   6674: /*   /\*   } *\/ */
                   6675: /*   /\* } *\/ */
                   6676:        
                   6677: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   6678: /*   if (stepm<=12) stepsize=1; */
                   6679: /*   if(estepm < stepm){ */
                   6680: /*     printf ("Problem %d lower than %d\n",estepm, stepm); */
                   6681: /*   } */
                   6682: /*   else  hstepm=estepm;    */
                   6683:        
                   6684: /*   hstepm=hstepm/stepm;  */
                   6685: /*   yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   6686: /*                                fractional in yp1 *\/ */
                   6687: /*   anprojmean=yp; */
                   6688: /*   yp2=modf((yp1*12),&yp); */
                   6689: /*   mprojmean=yp; */
                   6690: /*   yp1=modf((yp2*30.5),&yp); */
                   6691: /*   jprojmean=yp; */
                   6692: /*   if(jprojmean==0) jprojmean=1; */
                   6693: /*   if(mprojmean==0) jprojmean=1; */
                   6694:        
                   6695: /*   i1=cptcoveff; */
                   6696: /*   if (cptcovn < 1){i1=1;} */
1.217     brouard  6697:   
1.218     brouard  6698: /*   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);  */
1.217     brouard  6699:   
1.218     brouard  6700: /*   fprintf(ficresfb,"#****** Routine prevbackforecast **\n"); */
                   6701:        
                   6702: /*     /\*           if (h==(int)(YEARM*yearp)){ *\/ */
                   6703: /*   for(cptcov=1, k=0;cptcov<=i1;cptcov++){ */
                   6704: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   6705: /*       k=k+1; */
                   6706: /*       fprintf(ficresfb,"\n#****** hbijx=probability over h years, hp.jx is weighted by observed prev \n#"); */
                   6707: /*       for(j=1;j<=cptcoveff;j++) { */
                   6708: /*                             fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   6709: /*       } */
                   6710: /*       fprintf(ficresfb," yearbproj age"); */
                   6711: /*       for(j=1; j<=nlstate+ndeath;j++){  */
                   6712: /*                             for(i=1; i<=nlstate;i++)               */
                   6713: /*           fprintf(ficresfb," p%d%d",i,j); */
                   6714: /*                             fprintf(ficresfb," p.%d",j); */
                   6715: /*       } */
                   6716: /*       for (yearp=0; yearp>=(anback2-anback1);yearp -=stepsize) {  */
                   6717: /*                             /\* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  *\/ */
                   6718: /*                             fprintf(ficresfb,"\n"); */
                   6719: /*                             fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp);    */
                   6720: /*                             for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   6721: /*                                     nhstepm=(int) rint((agelim-agec)*YEARM/stepm);  */
                   6722: /*                                     nhstepm = nhstepm/hstepm;  */
                   6723: /*                                     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   6724: /*                                     oldm=oldms;savm=savms; */
                   6725: /*                                     hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm,oldm,savm, dnewm, doldm, dsavm, k);       */
                   6726: /*                                     for (h=0; h<=nhstepm; h++){ */
                   6727: /*                                             if (h*hstepm/YEARM*stepm ==yearp) { */
                   6728: /*               fprintf(ficresfb,"\n"); */
                   6729: /*               for(j=1;j<=cptcoveff;j++)  */
                   6730: /*                 fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   6731: /*                                                     fprintf(ficresfb,"%.f %.f ",anback1+yearp,agec+h*hstepm/YEARM*stepm); */
                   6732: /*                                             }  */
                   6733: /*                                             for(j=1; j<=nlstate+ndeath;j++) { */
                   6734: /*                                                     ppij=0.; */
                   6735: /*                                                     for(i=1; i<=nlstate;i++) { */
                   6736: /*                                                             if (mobilav==1)  */
                   6737: /*                                                                     ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod]; */
                   6738: /*                                                             else { */
                   6739: /*                                                                     ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod]; */
                   6740: /*                                                             } */
                   6741: /*                                                             if (h*hstepm/YEARM*stepm== yearp) { */
                   6742: /*                                                                     fprintf(ficresfb," %.3f", p3mat[i][j][h]); */
                   6743: /*                                                             } */
                   6744: /*                                                     } /\* end i *\/ */
                   6745: /*                                                     if (h*hstepm/YEARM*stepm==yearp) { */
                   6746: /*                                                             fprintf(ficresfb," %.3f", ppij); */
                   6747: /*                                                     } */
                   6748: /*                                             }/\* end j *\/ */
                   6749: /*                                     } /\* end h *\/ */
                   6750: /*                                     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   6751: /*                             } /\* end agec *\/ */
                   6752: /*       } /\* end yearp *\/ */
                   6753: /*     } /\* end cptcod *\/ */
                   6754: /*   } /\* end  cptcov *\/ */
                   6755:        
                   6756: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   6757:        
                   6758: /*   fclose(ficresfb); */
                   6759: /*   printf("End of Computing Back forecasting \n"); */
                   6760: /*   fprintf(ficlog,"End of Computing Back forecasting\n"); */
1.217     brouard  6761:        
1.218     brouard  6762: /* } */
1.217     brouard  6763: 
1.126     brouard  6764: /************** Forecasting *****not tested NB*************/
1.169     brouard  6765: 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  6766:   
                   6767:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
                   6768:   int *popage;
                   6769:   double calagedatem, agelim, kk1, kk2;
                   6770:   double *popeffectif,*popcount;
                   6771:   double ***p3mat,***tabpop,***tabpopprev;
1.218     brouard  6772:   /* double ***mobaverage; */
1.126     brouard  6773:   char filerespop[FILENAMELENGTH];
                   6774: 
                   6775:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6776:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6777:   agelim=AGESUP;
                   6778:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
                   6779:   
                   6780:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   6781:   
                   6782:   
1.201     brouard  6783:   strcpy(filerespop,"POP_"); 
                   6784:   strcat(filerespop,fileresu);
1.126     brouard  6785:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
                   6786:     printf("Problem with forecast resultfile: %s\n", filerespop);
                   6787:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
                   6788:   }
                   6789:   printf("Computing forecasting: result on file '%s' \n", filerespop);
                   6790:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
                   6791: 
                   6792:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   6793: 
1.218     brouard  6794:   /* if (mobilav!=0) { */
                   6795:   /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6796:   /*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ */
                   6797:   /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   6798:   /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   6799:   /*   } */
                   6800:   /* } */
1.126     brouard  6801: 
                   6802:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   6803:   if (stepm<=12) stepsize=1;
                   6804:   
                   6805:   agelim=AGESUP;
                   6806:   
                   6807:   hstepm=1;
                   6808:   hstepm=hstepm/stepm; 
1.218     brouard  6809:        
1.126     brouard  6810:   if (popforecast==1) {
                   6811:     if((ficpop=fopen(popfile,"r"))==NULL) {
                   6812:       printf("Problem with population file : %s\n",popfile);exit(0);
                   6813:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
                   6814:     } 
                   6815:     popage=ivector(0,AGESUP);
                   6816:     popeffectif=vector(0,AGESUP);
                   6817:     popcount=vector(0,AGESUP);
                   6818:     
                   6819:     i=1;   
                   6820:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
1.218     brouard  6821:     
1.126     brouard  6822:     imx=i;
                   6823:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
                   6824:   }
1.218     brouard  6825:   
1.126     brouard  6826:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
1.218     brouard  6827:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
1.126     brouard  6828:       k=k+1;
                   6829:       fprintf(ficrespop,"\n#******");
                   6830:       for(j=1;j<=cptcoveff;j++) {
1.198     brouard  6831:        fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  6832:       }
                   6833:       fprintf(ficrespop,"******\n");
                   6834:       fprintf(ficrespop,"# Age");
                   6835:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
                   6836:       if (popforecast==1)  fprintf(ficrespop," [Population]");
                   6837:       
                   6838:       for (cpt=0; cpt<=0;cpt++) { 
                   6839:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   6840:        
1.218     brouard  6841:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
1.126     brouard  6842:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   6843:          nhstepm = nhstepm/hstepm; 
                   6844:          
                   6845:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6846:          oldm=oldms;savm=savms;
                   6847:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
1.218     brouard  6848:          
1.126     brouard  6849:          for (h=0; h<=nhstepm; h++){
                   6850:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   6851:              fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   6852:            } 
                   6853:            for(j=1; j<=nlstate+ndeath;j++) {
                   6854:              kk1=0.;kk2=0;
                   6855:              for(i=1; i<=nlstate;i++) {              
                   6856:                if (mobilav==1) 
                   6857:                  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
                   6858:                else {
                   6859:                  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
                   6860:                }
                   6861:              }
                   6862:              if (h==(int)(calagedatem+12*cpt)){
                   6863:                tabpop[(int)(agedeb)][j][cptcod]=kk1;
1.218     brouard  6864:                /*fprintf(ficrespop," %.3f", kk1);
                   6865:                  if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
1.126     brouard  6866:              }
                   6867:            }
                   6868:            for(i=1; i<=nlstate;i++){
                   6869:              kk1=0.;
1.218     brouard  6870:              for(j=1; j<=nlstate;j++){
                   6871:                kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
                   6872:              }
                   6873:              tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
1.126     brouard  6874:            }
1.218     brouard  6875:            
                   6876:            if (h==(int)(calagedatem+12*cpt))
                   6877:              for(j=1; j<=nlstate;j++) 
                   6878:                fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
1.126     brouard  6879:          }
                   6880:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6881:        }
                   6882:       }
1.218     brouard  6883:       
                   6884:       /******/
                   6885:       
1.126     brouard  6886:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
                   6887:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   6888:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   6889:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   6890:          nhstepm = nhstepm/hstepm; 
                   6891:          
                   6892:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6893:          oldm=oldms;savm=savms;
                   6894:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   6895:          for (h=0; h<=nhstepm; h++){
                   6896:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   6897:              fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   6898:            } 
                   6899:            for(j=1; j<=nlstate+ndeath;j++) {
                   6900:              kk1=0.;kk2=0;
                   6901:              for(i=1; i<=nlstate;i++) {              
                   6902:                kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
                   6903:              }
                   6904:              if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
                   6905:            }
                   6906:          }
                   6907:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6908:        }
                   6909:       }
1.218     brouard  6910:     } 
1.126     brouard  6911:   }
1.218     brouard  6912:   
                   6913:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6914:   
1.126     brouard  6915:   if (popforecast==1) {
                   6916:     free_ivector(popage,0,AGESUP);
                   6917:     free_vector(popeffectif,0,AGESUP);
                   6918:     free_vector(popcount,0,AGESUP);
                   6919:   }
                   6920:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6921:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6922:   fclose(ficrespop);
                   6923: } /* End of popforecast */
1.218     brouard  6924:  
1.126     brouard  6925: int fileappend(FILE *fichier, char *optionfich)
                   6926: {
                   6927:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   6928:     printf("Problem with file: %s\n", optionfich);
                   6929:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   6930:     return (0);
                   6931:   }
                   6932:   fflush(fichier);
                   6933:   return (1);
                   6934: }
                   6935: 
                   6936: 
                   6937: /**************** function prwizard **********************/
                   6938: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   6939: {
                   6940: 
                   6941:   /* Wizard to print covariance matrix template */
                   6942: 
1.164     brouard  6943:   char ca[32], cb[32];
                   6944:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  6945:   int numlinepar;
                   6946: 
                   6947:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   6948:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   6949:   for(i=1; i <=nlstate; i++){
                   6950:     jj=0;
                   6951:     for(j=1; j <=nlstate+ndeath; j++){
                   6952:       if(j==i) continue;
                   6953:       jj++;
                   6954:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   6955:       printf("%1d%1d",i,j);
                   6956:       fprintf(ficparo,"%1d%1d",i,j);
                   6957:       for(k=1; k<=ncovmodel;k++){
                   6958:        /*        printf(" %lf",param[i][j][k]); */
                   6959:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   6960:        printf(" 0.");
                   6961:        fprintf(ficparo," 0.");
                   6962:       }
                   6963:       printf("\n");
                   6964:       fprintf(ficparo,"\n");
                   6965:     }
                   6966:   }
                   6967:   printf("# Scales (for hessian or gradient estimation)\n");
                   6968:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   6969:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   6970:   for(i=1; i <=nlstate; i++){
                   6971:     jj=0;
                   6972:     for(j=1; j <=nlstate+ndeath; j++){
                   6973:       if(j==i) continue;
                   6974:       jj++;
                   6975:       fprintf(ficparo,"%1d%1d",i,j);
                   6976:       printf("%1d%1d",i,j);
                   6977:       fflush(stdout);
                   6978:       for(k=1; k<=ncovmodel;k++){
                   6979:        /*      printf(" %le",delti3[i][j][k]); */
                   6980:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   6981:        printf(" 0.");
                   6982:        fprintf(ficparo," 0.");
                   6983:       }
                   6984:       numlinepar++;
                   6985:       printf("\n");
                   6986:       fprintf(ficparo,"\n");
                   6987:     }
                   6988:   }
                   6989:   printf("# Covariance matrix\n");
                   6990: /* # 121 Var(a12)\n\ */
                   6991: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   6992: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   6993: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   6994: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   6995: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   6996: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   6997: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   6998:   fflush(stdout);
                   6999:   fprintf(ficparo,"# Covariance matrix\n");
                   7000:   /* # 121 Var(a12)\n\ */
                   7001:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   7002:   /* #   ...\n\ */
                   7003:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   7004:   
                   7005:   for(itimes=1;itimes<=2;itimes++){
                   7006:     jj=0;
                   7007:     for(i=1; i <=nlstate; i++){
                   7008:       for(j=1; j <=nlstate+ndeath; j++){
                   7009:        if(j==i) continue;
                   7010:        for(k=1; k<=ncovmodel;k++){
                   7011:          jj++;
                   7012:          ca[0]= k+'a'-1;ca[1]='\0';
                   7013:          if(itimes==1){
                   7014:            printf("#%1d%1d%d",i,j,k);
                   7015:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   7016:          }else{
                   7017:            printf("%1d%1d%d",i,j,k);
                   7018:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   7019:            /*  printf(" %.5le",matcov[i][j]); */
                   7020:          }
                   7021:          ll=0;
                   7022:          for(li=1;li <=nlstate; li++){
                   7023:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   7024:              if(lj==li) continue;
                   7025:              for(lk=1;lk<=ncovmodel;lk++){
                   7026:                ll++;
                   7027:                if(ll<=jj){
                   7028:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   7029:                  if(ll<jj){
                   7030:                    if(itimes==1){
                   7031:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7032:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7033:                    }else{
                   7034:                      printf(" 0.");
                   7035:                      fprintf(ficparo," 0.");
                   7036:                    }
                   7037:                  }else{
                   7038:                    if(itimes==1){
                   7039:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   7040:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   7041:                    }else{
                   7042:                      printf(" 0.");
                   7043:                      fprintf(ficparo," 0.");
                   7044:                    }
                   7045:                  }
                   7046:                }
                   7047:              } /* end lk */
                   7048:            } /* end lj */
                   7049:          } /* end li */
                   7050:          printf("\n");
                   7051:          fprintf(ficparo,"\n");
                   7052:          numlinepar++;
                   7053:        } /* end k*/
                   7054:       } /*end j */
                   7055:     } /* end i */
                   7056:   } /* end itimes */
                   7057: 
                   7058: } /* end of prwizard */
                   7059: /******************* Gompertz Likelihood ******************************/
                   7060: double gompertz(double x[])
                   7061: { 
                   7062:   double A,B,L=0.0,sump=0.,num=0.;
                   7063:   int i,n=0; /* n is the size of the sample */
                   7064: 
1.220     brouard  7065:   for (i=1;i<=imx ; i++) {
1.126     brouard  7066:     sump=sump+weight[i];
                   7067:     /*    sump=sump+1;*/
                   7068:     num=num+1;
                   7069:   }
                   7070:  
                   7071:  
                   7072:   /* for (i=0; i<=imx; i++) 
                   7073:      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]);*/
                   7074: 
                   7075:   for (i=1;i<=imx ; i++)
                   7076:     {
                   7077:       if (cens[i] == 1 && wav[i]>1)
                   7078:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   7079:       
                   7080:       if (cens[i] == 0 && wav[i]>1)
                   7081:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   7082:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   7083:       
                   7084:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   7085:       if (wav[i] > 1 ) { /* ??? */
                   7086:        L=L+A*weight[i];
                   7087:        /*      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]);*/
                   7088:       }
                   7089:     }
                   7090: 
                   7091:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   7092:  
                   7093:   return -2*L*num/sump;
                   7094: }
                   7095: 
1.136     brouard  7096: #ifdef GSL
                   7097: /******************* Gompertz_f Likelihood ******************************/
                   7098: double gompertz_f(const gsl_vector *v, void *params)
                   7099: { 
                   7100:   double A,B,LL=0.0,sump=0.,num=0.;
                   7101:   double *x= (double *) v->data;
                   7102:   int i,n=0; /* n is the size of the sample */
                   7103: 
                   7104:   for (i=0;i<=imx-1 ; i++) {
                   7105:     sump=sump+weight[i];
                   7106:     /*    sump=sump+1;*/
                   7107:     num=num+1;
                   7108:   }
                   7109:  
                   7110:  
                   7111:   /* for (i=0; i<=imx; i++) 
                   7112:      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]);*/
                   7113:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   7114:   for (i=1;i<=imx ; i++)
                   7115:     {
                   7116:       if (cens[i] == 1 && wav[i]>1)
                   7117:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   7118:       
                   7119:       if (cens[i] == 0 && wav[i]>1)
                   7120:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   7121:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   7122:       
                   7123:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   7124:       if (wav[i] > 1 ) { /* ??? */
                   7125:        LL=LL+A*weight[i];
                   7126:        /*      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]);*/
                   7127:       }
                   7128:     }
                   7129: 
                   7130:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   7131:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   7132:  
                   7133:   return -2*LL*num/sump;
                   7134: }
                   7135: #endif
                   7136: 
1.126     brouard  7137: /******************* Printing html file ***********/
1.201     brouard  7138: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  7139:                  int lastpass, int stepm, int weightopt, char model[],\
                   7140:                  int imx,  double p[],double **matcov,double agemortsup){
                   7141:   int i,k;
                   7142: 
                   7143:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   7144:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   7145:   for (i=1;i<=2;i++) 
                   7146:     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  7147:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  7148:   fprintf(fichtm,"</ul>");
                   7149: 
                   7150: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   7151: 
                   7152:  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>");
                   7153: 
                   7154:  for (k=agegomp;k<(agemortsup-2);k++) 
                   7155:    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]);
                   7156: 
                   7157:  
                   7158:   fflush(fichtm);
                   7159: }
                   7160: 
                   7161: /******************* Gnuplot file **************/
1.201     brouard  7162: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  7163: 
                   7164:   char dirfileres[132],optfileres[132];
1.164     brouard  7165: 
1.126     brouard  7166:   int ng;
                   7167: 
                   7168: 
                   7169:   /*#ifdef windows */
                   7170:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   7171:     /*#endif */
                   7172: 
                   7173: 
                   7174:   strcpy(dirfileres,optionfilefiname);
                   7175:   strcpy(optfileres,"vpl");
1.199     brouard  7176:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  7177:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  7178:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  7179:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  7180:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   7181: 
                   7182: } 
                   7183: 
1.136     brouard  7184: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   7185: {
1.126     brouard  7186: 
1.136     brouard  7187:   /*-------- data file ----------*/
                   7188:   FILE *fic;
                   7189:   char dummy[]="                         ";
1.223   ! brouard  7190:   int i=0, j=0, n=0, iv=0;
        !          7191:   int lstra;
1.136     brouard  7192:   int linei, month, year,iout;
                   7193:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  7194:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  7195:   char *stratrunc;
1.223   ! brouard  7196: 
1.126     brouard  7197: 
                   7198: 
1.136     brouard  7199:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  7200:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   7201:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  7202:   }
1.126     brouard  7203: 
1.136     brouard  7204:   i=1;
                   7205:   linei=0;
                   7206:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   7207:     linei=linei+1;
                   7208:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   7209:       if(line[j] == '\t')
                   7210:        line[j] = ' ';
                   7211:     }
                   7212:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   7213:       ;
                   7214:     };
                   7215:     line[j+1]=0;  /* Trims blanks at end of line */
                   7216:     if(line[0]=='#'){
                   7217:       fprintf(ficlog,"Comment line\n%s\n",line);
                   7218:       printf("Comment line\n%s\n",line);
                   7219:       continue;
                   7220:     }
                   7221:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  7222:     strcpy(line, linetmp);
1.223   ! brouard  7223:     
        !          7224:     /* Loops on waves */
        !          7225:     for (j=maxwav;j>=1;j--){
        !          7226:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
        !          7227:                                cutv(stra, strb, line, ' '); 
        !          7228:                                if(strb[0]=='.') { /* Missing value */
        !          7229:                                        lval=-1;
        !          7230:                                }else{
        !          7231:                                        errno=0;
        !          7232:                                        /* what_kind_of_number(strb); */
        !          7233:                                        dval=strtod(strb,&endptr); 
        !          7234:                                        /* if( strb[0]=='\0' || (*endptr != '\0')){ */
        !          7235:                                        /* if(strb != endptr && *endptr == '\0') */
        !          7236:                                        /*    dval=dlval; */
        !          7237:                                        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
        !          7238:                                        if( strb[0]=='\0' || (*endptr != '\0')){
        !          7239:                                                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);
        !          7240:                                                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);
        !          7241:                                                return 1;
        !          7242:                                        }
        !          7243:                                        cotqvar[j][iv][i]=dval; 
        !          7244:                                }
        !          7245:                                strcpy(line,stra);
        !          7246:       }/* end loop ntqv */
        !          7247:                        
        !          7248:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
        !          7249:                                cutv(stra, strb, line, ' '); 
        !          7250:                                if(strb[0]=='.') { /* Missing value */
        !          7251:                                        lval=-1;
        !          7252:                                }else{
        !          7253:                                        errno=0;
        !          7254:                                        lval=strtol(strb,&endptr,10); 
        !          7255:                                        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
        !          7256:                                        if( strb[0]=='\0' || (*endptr != '\0')){
        !          7257:                                                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);
        !          7258:                                                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);
        !          7259:                                                return 1;
        !          7260:                                        }
        !          7261:                                }
        !          7262:                                if(lval <-1 || lval >1){
        !          7263:                                        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
        !          7264:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
        !          7265:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
        !          7266:  For example, for multinomial values like 1, 2 and 3,\n                                                                        \
        !          7267:  build V1=0 V2=0 for the reference value (1),\n                                                                                                        \
        !          7268:         V1=1 V2=0 for (2) \n                                                                                                                                                                           \
        !          7269:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
        !          7270:  output of IMaCh is often meaningless.\n                                                                                                                               \
        !          7271:  Exiting.\n",lval,linei, i,line,j);
        !          7272:                                        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
        !          7273:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
        !          7274:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
        !          7275:  For example, for multinomial values like 1, 2 and 3,\n                                                                        \
        !          7276:  build V1=0 V2=0 for the reference value (1),\n                                                                                                        \
        !          7277:         V1=1 V2=0 for (2) \n                                                                                                                                                                           \
        !          7278:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
        !          7279:  output of IMaCh is often meaningless.\n                               \
        !          7280:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
        !          7281:                                        return 1;
        !          7282:                                }
        !          7283:                                cotvar[j][iv][i]=(double)(lval);
        !          7284:                                strcpy(line,stra);
        !          7285:       }/* end loop ntv */
1.126     brouard  7286: 
1.223   ! brouard  7287:       /* Statuses  at wave */
1.137     brouard  7288:       cutv(stra, strb, line, ' '); 
1.223   ! brouard  7289:       if(strb[0]=='.') { /* Missing value */
        !          7290:                                lval=-1;
1.136     brouard  7291:       }else{
1.223   ! brouard  7292:                                errno=0;
        !          7293:                                lval=strtol(strb,&endptr,10); 
        !          7294:                                /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
        !          7295:                                if( strb[0]=='\0' || (*endptr != '\0')){
        !          7296:                                        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);
        !          7297:                                        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);
        !          7298:                                        return 1;
        !          7299:                                }
1.136     brouard  7300:       }
1.223   ! brouard  7301:      
1.136     brouard  7302:       s[j][i]=lval;
1.223   ! brouard  7303: 
        !          7304:       /* Date of Interview */
1.136     brouard  7305:       strcpy(line,stra);
                   7306:       cutv(stra, strb,line,' ');
1.169     brouard  7307:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  7308:       }
1.169     brouard  7309:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.223   ! brouard  7310:                                month=99;
        !          7311:                                year=9999;
1.136     brouard  7312:       }else{
1.223   ! brouard  7313:                                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);
        !          7314:                                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);
        !          7315:                                return 1;
1.136     brouard  7316:       }
                   7317:       anint[j][i]= (double) year; 
                   7318:       mint[j][i]= (double)month; 
                   7319:       strcpy(line,stra);
1.223   ! brouard  7320:     } /* End loop on waves */
        !          7321: 
        !          7322:     /* Date of death */
1.136     brouard  7323:     cutv(stra, strb,line,' '); 
1.169     brouard  7324:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  7325:     }
1.169     brouard  7326:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  7327:       month=99;
                   7328:       year=9999;
                   7329:     }else{
1.141     brouard  7330:       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  7331:                        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);
        !          7332:                        return 1;
1.136     brouard  7333:     }
                   7334:     andc[i]=(double) year; 
                   7335:     moisdc[i]=(double) month; 
                   7336:     strcpy(line,stra);
                   7337:     
1.223   ! brouard  7338:     /* Date of birth */
1.136     brouard  7339:     cutv(stra, strb,line,' '); 
1.169     brouard  7340:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  7341:     }
1.169     brouard  7342:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  7343:       month=99;
                   7344:       year=9999;
                   7345:     }else{
1.141     brouard  7346:       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);
                   7347:       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  7348:                        return 1;
1.136     brouard  7349:     }
                   7350:     if (year==9999) {
1.141     brouard  7351:       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);
                   7352:       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  7353:                        return 1;
1.126     brouard  7354: 
1.136     brouard  7355:     }
                   7356:     annais[i]=(double)(year);
                   7357:     moisnais[i]=(double)(month); 
                   7358:     strcpy(line,stra);
1.223   ! brouard  7359: 
        !          7360:     /* Sample weight */
1.136     brouard  7361:     cutv(stra, strb,line,' '); 
                   7362:     errno=0;
                   7363:     dval=strtod(strb,&endptr); 
                   7364:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  7365:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   7366:       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  7367:       fflush(ficlog);
                   7368:       return 1;
                   7369:     }
                   7370:     weight[i]=dval; 
                   7371:     strcpy(line,stra);
1.223   ! brouard  7372: 
        !          7373:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
        !          7374:       cutv(stra, strb, line, ' '); 
        !          7375:       if(strb[0]=='.') { /* Missing value */
        !          7376:                                lval=-1;
        !          7377:       }else{
        !          7378:                                errno=0;
        !          7379:                                /* what_kind_of_number(strb); */
        !          7380:                                dval=strtod(strb,&endptr);
        !          7381:                                /* if(strb != endptr && *endptr == '\0') */
        !          7382:                                /*   dval=dlval; */
        !          7383:                                /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
        !          7384:                                if( strb[0]=='\0' || (*endptr != '\0')){
        !          7385:                                        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);
        !          7386:                                        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);
        !          7387:                                        return 1;
        !          7388:                                }
        !          7389:                                coqvar[iv][i]=dval; 
        !          7390:       }
        !          7391:       strcpy(line,stra);
        !          7392:     }/* end loop nqv */
1.136     brouard  7393:     
1.223   ! brouard  7394:     /* Covariate values */
1.136     brouard  7395:     for (j=ncovcol;j>=1;j--){
                   7396:       cutv(stra, strb,line,' '); 
1.223   ! brouard  7397:       if(strb[0]=='.') { /* Missing covariate value */
        !          7398:                                lval=-1;
1.136     brouard  7399:       }else{
1.223   ! brouard  7400:                                errno=0;
        !          7401:                                lval=strtol(strb,&endptr,10); 
        !          7402:                                if( strb[0]=='\0' || (*endptr != '\0')){
        !          7403:                                        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);
        !          7404:                                        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);
        !          7405:                                        return 1;
        !          7406:                                }
1.136     brouard  7407:       }
                   7408:       if(lval <-1 || lval >1){
1.223   ! brouard  7409:                                printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  7410:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   7411:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   7412:  For example, for multinomial values like 1, 2 and 3,\n \
                   7413:  build V1=0 V2=0 for the reference value (1),\n \
                   7414:         V1=1 V2=0 for (2) \n \
                   7415:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   7416:  output of IMaCh is often meaningless.\n \
                   7417:  Exiting.\n",lval,linei, i,line,j);
1.223   ! brouard  7418:                                fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  7419:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   7420:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   7421:  For example, for multinomial values like 1, 2 and 3,\n \
                   7422:  build V1=0 V2=0 for the reference value (1),\n \
                   7423:         V1=1 V2=0 for (2) \n \
                   7424:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   7425:  output of IMaCh is often meaningless.\n \
                   7426:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.223   ! brouard  7427:                                return 1;
1.136     brouard  7428:       }
                   7429:       covar[j][i]=(double)(lval);
                   7430:       strcpy(line,stra);
                   7431:     }  
                   7432:     lstra=strlen(stra);
                   7433:      
                   7434:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   7435:       stratrunc = &(stra[lstra-9]);
                   7436:       num[i]=atol(stratrunc);
                   7437:     }
                   7438:     else
                   7439:       num[i]=atol(stra);
                   7440:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   7441:       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;}*/
                   7442:     
                   7443:     i=i+1;
                   7444:   } /* End loop reading  data */
1.126     brouard  7445: 
1.136     brouard  7446:   *imax=i-1; /* Number of individuals */
                   7447:   fclose(fic);
                   7448:  
                   7449:   return (0);
1.164     brouard  7450:   /* endread: */
1.223   ! brouard  7451:        printf("Exiting readdata: ");
        !          7452:        fclose(fic);
        !          7453:        return (1);
        !          7454: }
1.126     brouard  7455: 
1.145     brouard  7456: void removespace(char *str) {
                   7457:   char *p1 = str, *p2 = str;
                   7458:   do
                   7459:     while (*p2 == ' ')
                   7460:       p2++;
1.169     brouard  7461:   while (*p1++ == *p2++);
1.145     brouard  7462: }
                   7463: 
                   7464: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
1.187     brouard  7465:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   7466:    * - nagesqr = 1 if age*age in the model, otherwise 0.
                   7467:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   7468:    * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
1.145     brouard  7469:    * - cptcovage number of covariates with age*products =2
                   7470:    * - cptcovs number of simple covariates
                   7471:    * - 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
                   7472:    *     which is a new column after the 9 (ncovcol) variables. 
                   7473:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   7474:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   7475:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   7476:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   7477:  */
1.136     brouard  7478: {
1.145     brouard  7479:   int i, j, k, ks;
1.164     brouard  7480:   int  j1, k1, k2;
1.136     brouard  7481:   char modelsav[80];
1.145     brouard  7482:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  7483:   char *strpt;
1.136     brouard  7484: 
1.145     brouard  7485:   /*removespace(model);*/
1.136     brouard  7486:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  7487:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  7488:     if (strstr(model,"AGE") !=0){
1.192     brouard  7489:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   7490:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  7491:       return 1;
                   7492:     }
1.141     brouard  7493:     if (strstr(model,"v") !=0){
                   7494:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   7495:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   7496:       return 1;
                   7497:     }
1.187     brouard  7498:     strcpy(modelsav,model); 
                   7499:     if ((strpt=strstr(model,"age*age")) !=0){
                   7500:       printf(" strpt=%s, model=%s\n",strpt, model);
                   7501:       if(strpt != model){
                   7502:       printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  7503:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  7504:  corresponding column of parameters.\n",model);
                   7505:       fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  7506:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  7507:  corresponding column of parameters.\n",model); fflush(ficlog);
                   7508:       return 1;
                   7509:     }
                   7510: 
                   7511:       nagesqr=1;
                   7512:       if (strstr(model,"+age*age") !=0)
                   7513:        substrchaine(modelsav, model, "+age*age");
                   7514:       else if (strstr(model,"age*age+") !=0)
                   7515:        substrchaine(modelsav, model, "age*age+");
                   7516:       else 
                   7517:        substrchaine(modelsav, model, "age*age");
                   7518:     }else
                   7519:       nagesqr=0;
                   7520:     if (strlen(modelsav) >1){
                   7521:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   7522:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
                   7523:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2  */
                   7524:       cptcovt= j+1; /* Number of total covariates in the model, not including
                   7525:                   * cst, age and age*age 
                   7526:                   * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
                   7527:                   /* including age products which are counted in cptcovage.
                   7528:                  * but the covariates which are products must be treated 
                   7529:                  * separately: ncovn=4- 2=2 (V1+V3). */
                   7530:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   7531:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
                   7532: 
                   7533:     
                   7534:       /*   Design
                   7535:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   7536:        *  <          ncovcol=8                >
                   7537:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   7538:        *   k=  1    2      3       4     5       6      7        8
                   7539:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   7540:        *  covar[k,i], value of kth covariate if not including age for individual i:
                   7541:        *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
                   7542:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
                   7543:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   7544:        *  Tage[++cptcovage]=k
                   7545:        *       if products, new covar are created after ncovcol with k1
                   7546:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   7547:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   7548:        *  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
                   7549:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   7550:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   7551:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   7552:        *  <          ncovcol=8                >
                   7553:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   7554:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   7555:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   7556:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   7557:        * p Tprod[1]@2={                         6, 5}
                   7558:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   7559:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   7560:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   7561:        *How to reorganize?
                   7562:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   7563:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   7564:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   7565:        * Struct []
                   7566:        */
1.145     brouard  7567: 
1.187     brouard  7568:       /* This loop fills the array Tvar from the string 'model'.*/
                   7569:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   7570:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   7571:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   7572:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   7573:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   7574:       /*       k=1 Tvar[1]=2 (from V2) */
                   7575:       /*       k=5 Tvar[5] */
                   7576:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  7577:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  7578:       /*       } */
1.198     brouard  7579:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  7580:       /*
                   7581:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
                   7582:       for(k=cptcovt; k>=1;k--) /**< Number of covariates */
1.145     brouard  7583:         Tvar[k]=0;
1.187     brouard  7584:       cptcovage=0;
                   7585:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
1.223   ! brouard  7586:                                cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
        !          7587:                                                                                                                                                                 modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
        !          7588:                                if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
        !          7589:                                /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
        !          7590:                                /*scanf("%d",i);*/
        !          7591:                                if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
        !          7592:                                        cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
        !          7593:                                        if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
        !          7594:                                                /* covar is not filled and then is empty */
        !          7595:                                                cptcovprod--;
        !          7596:                                                cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
        !          7597:                                                Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
        !          7598:                                                cptcovage++; /* Sums the number of covariates which include age as a product */
        !          7599:                                                Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
        !          7600:                                                /*printf("stre=%s ", stre);*/
        !          7601:                                        } else if (strcmp(strd,"age")==0) { /* or age*Vn */
        !          7602:                                                cptcovprod--;
        !          7603:                                                cutl(stre,strb,strc,'V');
        !          7604:                                                Tvar[k]=atoi(stre);
        !          7605:                                                cptcovage++;
        !          7606:                                                Tage[cptcovage]=k;
        !          7607:                                        } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
        !          7608:                                                /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
        !          7609:                                                cptcovn++;
        !          7610:                                                cptcovprodnoage++;k1++;
        !          7611:                                                cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
        !          7612:                                                Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
        !          7613:                                                                                                                                         because this model-covariate is a construction we invent a new column
        !          7614:                                                                                                                                         ncovcol + k1
        !          7615:                                                                                                                                         If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
        !          7616:                                                                                                                                         Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
        !          7617:                                                cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
        !          7618:                                                Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
        !          7619:                                                Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
        !          7620:                                                Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
        !          7621:                                                k2=k2+2;
        !          7622:                                                Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
        !          7623:                                                Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
        !          7624:                                                for (i=1; i<=lastobs;i++){
        !          7625:                                                        /* Computes the new covariate which is a product of
        !          7626:                                                                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
        !          7627:                                                        covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
        !          7628:                                                }
        !          7629:                                        } /* End age is not in the model */
        !          7630:                                } /* End if model includes a product */
        !          7631:                                else { /* no more sum */
        !          7632:                                        /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
        !          7633:                                        /*  scanf("%d",i);*/
        !          7634:                                        cutl(strd,strc,strb,'V');
        !          7635:                                        ks++; /**< Number of simple covariates */
        !          7636:                                        cptcovn++;
        !          7637:                                        Tvar[k]=atoi(strd);
        !          7638:                                }
        !          7639:                                strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
        !          7640:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
        !          7641:                                        scanf("%d",i);*/
1.187     brouard  7642:       } /* end of loop + on total covariates */
                   7643:     } /* end if strlen(modelsave == 0) age*age might exist */
                   7644:   } /* end if strlen(model == 0) */
1.136     brouard  7645:   
                   7646:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   7647:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
                   7648: 
                   7649:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
                   7650:   printf("cptcovprod=%d ", cptcovprod);
                   7651:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   7652: 
                   7653:   scanf("%d ",i);*/
                   7654: 
                   7655: 
1.137     brouard  7656:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  7657:   /*endread:*/
1.136     brouard  7658:     printf("Exiting decodemodel: ");
                   7659:     return (1);
                   7660: }
                   7661: 
1.169     brouard  7662: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136     brouard  7663: {
                   7664:   int i, m;
1.218     brouard  7665:   int firstone=0;
                   7666:   
1.136     brouard  7667:   for (i=1; i<=imx; i++) {
                   7668:     for(m=2; (m<= maxwav); m++) {
                   7669:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   7670:        anint[m][i]=9999;
1.216     brouard  7671:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   7672:          s[m][i]=-1;
1.136     brouard  7673:       }
                   7674:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169     brouard  7675:        *nberr = *nberr + 1;
1.218     brouard  7676:        if(firstone == 0){
                   7677:          firstone=1;
                   7678:        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);
                   7679:        }
                   7680:        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  7681:        s[m][i]=-1;
                   7682:       }
                   7683:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  7684:        (*nberr)++;
1.136     brouard  7685:        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]); 
                   7686:        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]); 
                   7687:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   7688:       }
                   7689:     }
                   7690:   }
                   7691: 
                   7692:   for (i=1; i<=imx; i++)  {
                   7693:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   7694:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  7695:       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  7696:        if (s[m][i] >= nlstate+1) {
1.169     brouard  7697:          if(agedc[i]>0){
                   7698:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  7699:              agev[m][i]=agedc[i];
1.214     brouard  7700:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  7701:            }else {
1.136     brouard  7702:              if ((int)andc[i]!=9999){
                   7703:                nbwarn++;
                   7704:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   7705:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   7706:                agev[m][i]=-1;
                   7707:              }
                   7708:            }
1.169     brouard  7709:          } /* agedc > 0 */
1.214     brouard  7710:        } /* end if */
1.136     brouard  7711:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   7712:                                 years but with the precision of a month */
                   7713:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   7714:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   7715:            agev[m][i]=1;
                   7716:          else if(agev[m][i] < *agemin){ 
                   7717:            *agemin=agev[m][i];
                   7718:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   7719:          }
                   7720:          else if(agev[m][i] >*agemax){
                   7721:            *agemax=agev[m][i];
1.156     brouard  7722:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  7723:          }
                   7724:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   7725:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  7726:        } /* en if 9*/
1.136     brouard  7727:        else { /* =9 */
1.214     brouard  7728:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  7729:          agev[m][i]=1;
                   7730:          s[m][i]=-1;
                   7731:        }
                   7732:       }
1.214     brouard  7733:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  7734:        agev[m][i]=1;
1.214     brouard  7735:       else{
                   7736:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   7737:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   7738:        agev[m][i]=0;
                   7739:       }
                   7740:     } /* End for lastpass */
                   7741:   }
1.136     brouard  7742:     
                   7743:   for (i=1; i<=imx; i++)  {
                   7744:     for(m=firstpass; (m<=lastpass); m++){
                   7745:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  7746:        (*nberr)++;
1.136     brouard  7747:        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);     
                   7748:        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);     
                   7749:        return 1;
                   7750:       }
                   7751:     }
                   7752:   }
                   7753: 
                   7754:   /*for (i=1; i<=imx; i++){
                   7755:   for (m=firstpass; (m<lastpass); m++){
                   7756:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   7757: }
                   7758: 
                   7759: }*/
                   7760: 
                   7761: 
1.139     brouard  7762:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   7763:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  7764: 
                   7765:   return (0);
1.164     brouard  7766:  /* endread:*/
1.136     brouard  7767:     printf("Exiting calandcheckages: ");
                   7768:     return (1);
                   7769: }
                   7770: 
1.172     brouard  7771: #if defined(_MSC_VER)
                   7772: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   7773: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   7774: //#include "stdafx.h"
                   7775: //#include <stdio.h>
                   7776: //#include <tchar.h>
                   7777: //#include <windows.h>
                   7778: //#include <iostream>
                   7779: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   7780: 
                   7781: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   7782: 
                   7783: BOOL IsWow64()
                   7784: {
                   7785:        BOOL bIsWow64 = FALSE;
                   7786: 
                   7787:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   7788:        //  (HANDLE, PBOOL);
                   7789: 
                   7790:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   7791: 
                   7792:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   7793:        const char funcName[] = "IsWow64Process";
                   7794:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   7795:                GetProcAddress(module, funcName);
                   7796: 
                   7797:        if (NULL != fnIsWow64Process)
                   7798:        {
                   7799:                if (!fnIsWow64Process(GetCurrentProcess(),
                   7800:                        &bIsWow64))
                   7801:                        //throw std::exception("Unknown error");
                   7802:                        printf("Unknown error\n");
                   7803:        }
                   7804:        return bIsWow64 != FALSE;
                   7805: }
                   7806: #endif
1.177     brouard  7807: 
1.191     brouard  7808: void syscompilerinfo(int logged)
1.167     brouard  7809:  {
                   7810:    /* #include "syscompilerinfo.h"*/
1.185     brouard  7811:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   7812:    /* /GS /W3 /Gy
                   7813:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   7814:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   7815:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  7816:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   7817:    */ 
                   7818:    /* 64 bits */
1.185     brouard  7819:    /*
                   7820:      /GS /W3 /Gy
                   7821:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   7822:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   7823:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   7824:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   7825:    /* Optimization are useless and O3 is slower than O2 */
                   7826:    /*
                   7827:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   7828:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   7829:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   7830:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   7831:    */
1.186     brouard  7832:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  7833:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   7834:       /PDB:"visual studio
                   7835:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   7836:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   7837:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   7838:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   7839:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   7840:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   7841:       uiAccess='false'"
                   7842:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   7843:       /NOLOGO /TLBID:1
                   7844:    */
1.177     brouard  7845: #if defined __INTEL_COMPILER
1.178     brouard  7846: #if defined(__GNUC__)
                   7847:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   7848: #endif
1.177     brouard  7849: #elif defined(__GNUC__) 
1.179     brouard  7850: #ifndef  __APPLE__
1.174     brouard  7851: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  7852: #endif
1.177     brouard  7853:    struct utsname sysInfo;
1.178     brouard  7854:    int cross = CROSS;
                   7855:    if (cross){
                   7856:           printf("Cross-");
1.191     brouard  7857:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  7858:    }
1.174     brouard  7859: #endif
                   7860: 
1.171     brouard  7861: #include <stdint.h>
1.178     brouard  7862: 
1.191     brouard  7863:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  7864: #if defined(__clang__)
1.191     brouard  7865:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  7866: #endif
                   7867: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  7868:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  7869: #endif
                   7870: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  7871:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  7872: #endif
                   7873: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  7874:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  7875: #endif
                   7876: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  7877:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  7878: #endif
                   7879: #if defined(_MSC_VER)
1.191     brouard  7880:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  7881: #endif
                   7882: #if defined(__PGI)
1.191     brouard  7883:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  7884: #endif
                   7885: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  7886:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  7887: #endif
1.191     brouard  7888:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  7889:    
1.167     brouard  7890: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   7891: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   7892:     // Windows (x64 and x86)
1.191     brouard  7893:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  7894: #elif __unix__ // all unices, not all compilers
                   7895:     // Unix
1.191     brouard  7896:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  7897: #elif __linux__
                   7898:     // linux
1.191     brouard  7899:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  7900: #elif __APPLE__
1.174     brouard  7901:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  7902:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  7903: #endif
                   7904: 
                   7905: /*  __MINGW32__          */
                   7906: /*  __CYGWIN__  */
                   7907: /* __MINGW64__  */
                   7908: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   7909: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   7910: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   7911: /* _WIN64  // Defined for applications for Win64. */
                   7912: /* _M_X64 // Defined for compilations that target x64 processors. */
                   7913: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  7914: 
1.167     brouard  7915: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  7916:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  7917: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  7918:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  7919: #else
1.191     brouard  7920:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  7921: #endif
                   7922: 
1.169     brouard  7923: #if defined(__GNUC__)
                   7924: # if defined(__GNUC_PATCHLEVEL__)
                   7925: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   7926:                             + __GNUC_MINOR__ * 100 \
                   7927:                             + __GNUC_PATCHLEVEL__)
                   7928: # else
                   7929: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   7930:                             + __GNUC_MINOR__ * 100)
                   7931: # endif
1.174     brouard  7932:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  7933:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  7934: 
                   7935:    if (uname(&sysInfo) != -1) {
                   7936:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  7937:         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  7938:    }
                   7939:    else
                   7940:       perror("uname() error");
1.179     brouard  7941:    //#ifndef __INTEL_COMPILER 
                   7942: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  7943:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  7944:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  7945: #endif
1.169     brouard  7946: #endif
1.172     brouard  7947: 
                   7948:    //   void main()
                   7949:    //   {
1.169     brouard  7950: #if defined(_MSC_VER)
1.174     brouard  7951:    if (IsWow64()){
1.191     brouard  7952:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   7953:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  7954:    }
                   7955:    else{
1.191     brouard  7956:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   7957:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  7958:    }
1.172     brouard  7959:    //     printf("\nPress Enter to continue...");
                   7960:    //     getchar();
                   7961:    //   }
                   7962: 
1.169     brouard  7963: #endif
                   7964:    
1.167     brouard  7965: 
1.219     brouard  7966: }
1.136     brouard  7967: 
1.219     brouard  7968: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.180     brouard  7969:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
                   7970:   int i, j, k, i1 ;
1.202     brouard  7971:   /* double ftolpl = 1.e-10; */
1.180     brouard  7972:   double age, agebase, agelim;
1.203     brouard  7973:   double tot;
1.180     brouard  7974: 
1.202     brouard  7975:   strcpy(filerespl,"PL_");
                   7976:   strcat(filerespl,fileresu);
                   7977:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
                   7978:     printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   7979:     fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   7980:   }
                   7981:   printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   7982:   fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   7983:   pstamp(ficrespl);
1.203     brouard  7984:   fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  7985:   fprintf(ficrespl,"#Age ");
                   7986:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   7987:   fprintf(ficrespl,"\n");
1.180     brouard  7988:   
1.219     brouard  7989:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  7990: 
1.219     brouard  7991:   agebase=ageminpar;
                   7992:   agelim=agemaxpar;
1.180     brouard  7993: 
1.219     brouard  7994:   i1=pow(2,cptcoveff);
                   7995:   if (cptcovn < 1){i1=1;}
1.180     brouard  7996: 
1.220     brouard  7997:   for(k=1; k<=i1;k++){
                   7998:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
1.180     brouard  7999:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
1.219     brouard  8000:     //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
1.220     brouard  8001:     /* k=k+1; */
1.219     brouard  8002:     /* to clean */
                   8003:     //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   8004:     fprintf(ficrespl,"#******");
                   8005:     printf("#******");
                   8006:     fprintf(ficlog,"#******");
                   8007:     for(j=1;j<=cptcoveff;j++) {
                   8008:       fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8009:       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8010:       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8011:     }
                   8012:     fprintf(ficrespl,"******\n");
                   8013:     printf("******\n");
                   8014:     fprintf(ficlog,"******\n");
1.220     brouard  8015:                if(invalidvarcomb[k]){
                   8016:                                                printf("\nCombination (%d) ignored because no cases \n",k); 
                   8017:                                                fprintf(ficrespl,"#Combination (%d) ignored because no cases \n",k); 
                   8018:                                                fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   8019:                                                continue;
                   8020:                }
1.219     brouard  8021: 
                   8022:     fprintf(ficrespl,"#Age ");
                   8023:     for(j=1;j<=cptcoveff;j++) {
                   8024:       fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8025:     }
                   8026:     for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   8027:     fprintf(ficrespl,"Total Years_to_converge\n");
                   8028:        
                   8029:     for (age=agebase; age<=agelim; age++){
                   8030:       /* for (age=agebase; age<=agebase; age++){ */
                   8031:       prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k);
                   8032:       fprintf(ficrespl,"%.0f ",age );
                   8033:       for(j=1;j<=cptcoveff;j++)
1.220     brouard  8034:                                                        fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.219     brouard  8035:       tot=0.;
                   8036:       for(i=1; i<=nlstate;i++){
1.220     brouard  8037:                                                        tot +=  prlim[i][i];
                   8038:                                                        fprintf(ficrespl," %.5f", prlim[i][i]);
1.219     brouard  8039:       }
                   8040:       fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   8041:     } /* Age */
                   8042:     /* was end of cptcod */
                   8043:   } /* cptcov */
                   8044:   return 0;
1.180     brouard  8045: }
                   8046: 
1.218     brouard  8047: 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){
                   8048:        /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   8049:        
                   8050:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   8051:    * at any age between ageminpar and agemaxpar
                   8052:         */
1.217     brouard  8053:   int i, j, k, i1 ;
                   8054:   /* double ftolpl = 1.e-10; */
                   8055:   double age, agebase, agelim;
                   8056:   double tot;
1.218     brouard  8057:   /* double ***mobaverage; */
                   8058:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  8059: 
                   8060:   strcpy(fileresplb,"PLB_");
                   8061:   strcat(fileresplb,fileresu);
                   8062:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
                   8063:     printf("Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
                   8064:     fprintf(ficlog,"Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
                   8065:   }
                   8066:   printf("Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
                   8067:   fprintf(ficlog,"Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
                   8068:   pstamp(ficresplb);
                   8069:   fprintf(ficresplb,"# Period (stable) back prevalence. Precision given by ftolpl=%g \n", ftolpl);
                   8070:   fprintf(ficresplb,"#Age ");
                   8071:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   8072:   fprintf(ficresplb,"\n");
                   8073:   
1.218     brouard  8074:   
                   8075:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   8076:   
                   8077:   agebase=ageminpar;
                   8078:   agelim=agemaxpar;
                   8079:   
                   8080:   
                   8081:   i1=pow(2,cptcoveff);
                   8082:   if (cptcovn < 1){i1=1;}
1.220     brouard  8083: 
                   8084:        for(k=1; k<=i1;k++){ 
                   8085:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
1.217     brouard  8086:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
1.218     brouard  8087:     //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
1.220     brouard  8088:     /* k=k+1; */
1.218     brouard  8089:     /* to clean */
                   8090:     //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   8091:     fprintf(ficresplb,"#******");
                   8092:     printf("#******");
                   8093:     fprintf(ficlog,"#******");
                   8094:     for(j=1;j<=cptcoveff;j++) {
                   8095:       fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8096:       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8097:       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8098:     }
                   8099:     fprintf(ficresplb,"******\n");
                   8100:     printf("******\n");
                   8101:     fprintf(ficlog,"******\n");
1.220     brouard  8102:                if(invalidvarcomb[k]){
                   8103:                                                printf("\nCombination (%d) ignored because no cases \n",k); 
                   8104:                                                fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   8105:                                                fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   8106:                                                continue;
                   8107:                }
1.218     brouard  8108:     
                   8109:     fprintf(ficresplb,"#Age ");
                   8110:     for(j=1;j<=cptcoveff;j++) {
                   8111:       fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8112:     }
                   8113:     for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   8114:     fprintf(ficresplb,"Total Years_to_converge\n");
                   8115:     
                   8116:     
                   8117:     for (age=agebase; age<=agelim; age++){
                   8118:       /* for (age=agebase; age<=agebase; age++){ */
                   8119:       if(mobilavproj > 0){
                   8120:        /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   8121:        /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.219     brouard  8122:                                bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k);
1.218     brouard  8123:       }else if (mobilavproj == 0){
1.219     brouard  8124:                                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);
                   8125:                                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);
                   8126:                                exit(1);
1.218     brouard  8127:       }else{
1.219     brouard  8128:                                /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   8129:                                bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k);
1.218     brouard  8130:       }
                   8131:       fprintf(ficresplb,"%.0f ",age );
                   8132:       for(j=1;j<=cptcoveff;j++)
1.219     brouard  8133:                                fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.218     brouard  8134:       tot=0.;
                   8135:       for(i=1; i<=nlstate;i++){
1.219     brouard  8136:                                tot +=  bprlim[i][i];
                   8137:                                fprintf(ficresplb," %.5f", bprlim[i][i]);
1.218     brouard  8138:       }
                   8139:       fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   8140:     } /* Age */
                   8141:     /* was end of cptcod */
                   8142:   } /* cptcov */
                   8143:   
                   8144:   /* hBijx(p, bage, fage); */
                   8145:   /* fclose(ficrespijb); */
                   8146:   
                   8147:   return 0;
1.217     brouard  8148: }
1.218     brouard  8149:  
1.180     brouard  8150: int hPijx(double *p, int bage, int fage){
                   8151:     /*------------- h Pij x at various ages ------------*/
                   8152: 
                   8153:   int stepsize;
                   8154:   int agelim;
                   8155:   int hstepm;
                   8156:   int nhstepm;
                   8157:   int h, i, i1, j, k;
                   8158: 
                   8159:   double agedeb;
                   8160:   double ***p3mat;
                   8161: 
1.201     brouard  8162:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  8163:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   8164:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   8165:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   8166:     }
                   8167:     printf("Computing pij: result on file '%s' \n", filerespij);
                   8168:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   8169:   
                   8170:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   8171:     /*if (stepm<=24) stepsize=2;*/
                   8172: 
                   8173:     agelim=AGESUP;
                   8174:     hstepm=stepsize*YEARM; /* Every year of age */
                   8175:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
1.218     brouard  8176:                
1.180     brouard  8177:     /* hstepm=1;   aff par mois*/
                   8178:     pstamp(ficrespij);
                   8179:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   8180:     i1= pow(2,cptcoveff);
1.218     brouard  8181:                /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   8182:                /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   8183:                /*      k=k+1;  */
1.183     brouard  8184:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   8185:       fprintf(ficrespij,"\n#****** ");
                   8186:       for(j=1;j<=cptcoveff;j++) 
1.198     brouard  8187:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.183     brouard  8188:       fprintf(ficrespij,"******\n");
                   8189:       
                   8190:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   8191:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   8192:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   8193:        
                   8194:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  8195:        
1.183     brouard  8196:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8197:        oldm=oldms;savm=savms;
                   8198:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   8199:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   8200:        for(i=1; i<=nlstate;i++)
                   8201:          for(j=1; j<=nlstate+ndeath;j++)
                   8202:            fprintf(ficrespij," %1d-%1d",i,j);
                   8203:        fprintf(ficrespij,"\n");
                   8204:        for (h=0; h<=nhstepm; h++){
                   8205:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   8206:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  8207:          for(i=1; i<=nlstate;i++)
                   8208:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  8209:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  8210:          fprintf(ficrespij,"\n");
                   8211:        }
1.183     brouard  8212:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8213:        fprintf(ficrespij,"\n");
                   8214:       }
1.180     brouard  8215:       /*}*/
                   8216:     }
1.218     brouard  8217:     return 0;
1.180     brouard  8218: }
1.218     brouard  8219:  
                   8220:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  8221:     /*------------- h Bij x at various ages ------------*/
                   8222: 
                   8223:   int stepsize;
1.218     brouard  8224:   /* int agelim; */
                   8225:        int ageminl;
1.217     brouard  8226:   int hstepm;
                   8227:   int nhstepm;
                   8228:   int h, i, i1, j, k;
1.218     brouard  8229:        
1.217     brouard  8230:   double agedeb;
                   8231:   double ***p3mat;
1.218     brouard  8232:        
                   8233:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   8234:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   8235:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   8236:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   8237:   }
                   8238:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   8239:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   8240:   
                   8241:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   8242:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  8243:   
1.218     brouard  8244:   /* agelim=AGESUP; */
                   8245:   ageminl=30;
                   8246:   hstepm=stepsize*YEARM; /* Every year of age */
                   8247:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   8248:   
                   8249:   /* hstepm=1;   aff par mois*/
                   8250:   pstamp(ficrespijb);
                   8251:   fprintf(ficrespijb,"#****** h Pij x Back Probability to be in state i at age x-h being in j at x ");
                   8252:   i1= pow(2,cptcoveff);
                   8253:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   8254:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   8255:   /*   k=k+1;  */
                   8256:   for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   8257:     fprintf(ficrespijb,"\n#****** ");
                   8258:     for(j=1;j<=cptcoveff;j++)
                   8259:       fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8260:     fprintf(ficrespijb,"******\n");
1.222     brouard  8261:     if(invalidvarcomb[k]){
                   8262:       fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   8263:       continue;
                   8264:     }
1.218     brouard  8265:     
                   8266:     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   8267:     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   8268:       /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   8269:       nhstepm=(int) rint((agedeb-ageminl)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
                   8270:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 */
                   8271:       
                   8272:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   8273:       
                   8274:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8275:       /* oldm=oldms;savm=savms; */
                   8276:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   8277:       hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k);
                   8278:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
                   8279:       fprintf(ficrespijb,"# Cov Agex agex-h hpijx with i,j=");
                   8280:       for(i=1; i<=nlstate;i++)
                   8281:        for(j=1; j<=nlstate+ndeath;j++)
                   8282:          fprintf(ficrespijb," %1d-%1d",i,j);
                   8283:       fprintf(ficrespijb,"\n");
                   8284:       for (h=0; h<=nhstepm; h++){
                   8285:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   8286:        fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   8287:        /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
1.217     brouard  8288:        for(i=1; i<=nlstate;i++)
                   8289:          for(j=1; j<=nlstate+ndeath;j++)
1.218     brouard  8290:            fprintf(ficrespijb," %.5f", p3mat[i][j][h]);
1.217     brouard  8291:        fprintf(ficrespijb,"\n");
                   8292:       }
1.218     brouard  8293:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8294:       fprintf(ficrespijb,"\n");
1.217     brouard  8295:     }
1.218     brouard  8296:     /*}*/
                   8297:   }
                   8298:   return 0;
                   8299:  } /*  hBijx */
1.217     brouard  8300: 
1.180     brouard  8301: 
1.136     brouard  8302: /***********************************************/
                   8303: /**************** Main Program *****************/
                   8304: /***********************************************/
                   8305: 
                   8306: int main(int argc, char *argv[])
                   8307: {
                   8308: #ifdef GSL
                   8309:   const gsl_multimin_fminimizer_type *T;
                   8310:   size_t iteri = 0, it;
                   8311:   int rval = GSL_CONTINUE;
                   8312:   int status = GSL_SUCCESS;
                   8313:   double ssval;
                   8314: #endif
                   8315:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164     brouard  8316:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
1.209     brouard  8317:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  8318:   int jj, ll, li, lj, lk;
1.136     brouard  8319:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  8320:   int num_filled;
1.136     brouard  8321:   int itimes;
                   8322:   int NDIM=2;
                   8323:   int vpopbased=0;
                   8324: 
1.164     brouard  8325:   char ca[32], cb[32];
1.136     brouard  8326:   /*  FILE *fichtm; *//* Html File */
                   8327:   /* FILE *ficgp;*/ /*Gnuplot File */
                   8328:   struct stat info;
1.191     brouard  8329:   double agedeb=0.;
1.194     brouard  8330: 
                   8331:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  8332:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  8333: 
1.165     brouard  8334:   double fret;
1.191     brouard  8335:   double dum=0.; /* Dummy variable */
1.136     brouard  8336:   double ***p3mat;
1.218     brouard  8337:   /* double ***mobaverage; */
1.164     brouard  8338: 
                   8339:   char line[MAXLINE];
1.197     brouard  8340:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   8341: 
                   8342:   char model[MAXLINE], modeltemp[MAXLINE];
1.136     brouard  8343:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  8344:   char *tok, *val; /* pathtot */
1.136     brouard  8345:   int firstobs=1, lastobs=10;
1.195     brouard  8346:   int c,  h , cpt, c2;
1.191     brouard  8347:   int jl=0;
                   8348:   int i1, j1, jk, stepsize=0;
1.194     brouard  8349:   int count=0;
                   8350: 
1.164     brouard  8351:   int *tab; 
1.136     brouard  8352:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.217     brouard  8353:   int backcast=0;
1.136     brouard  8354:   int mobilav=0,popforecast=0;
1.191     brouard  8355:   int hstepm=0, nhstepm=0;
1.136     brouard  8356:   int agemortsup;
                   8357:   float  sumlpop=0.;
                   8358:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   8359:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   8360: 
1.191     brouard  8361:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  8362:   double ftolpl=FTOL;
                   8363:   double **prlim;
1.217     brouard  8364:   double **bprlim;
1.136     brouard  8365:   double ***param; /* Matrix of parameters */
                   8366:   double  *p;
                   8367:   double **matcov; /* Matrix of covariance */
1.203     brouard  8368:   double **hess; /* Hessian matrix */
1.136     brouard  8369:   double ***delti3; /* Scale */
                   8370:   double *delti; /* Scale */
                   8371:   double ***eij, ***vareij;
                   8372:   double **varpl; /* Variances of prevalence limits by age */
                   8373:   double *epj, vepp;
1.164     brouard  8374: 
1.136     brouard  8375:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
1.217     brouard  8376:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000;
                   8377: 
1.136     brouard  8378:   double **ximort;
1.145     brouard  8379:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  8380:   int *dcwave;
                   8381: 
1.164     brouard  8382:   char z[1]="c";
1.136     brouard  8383: 
                   8384:   /*char  *strt;*/
                   8385:   char strtend[80];
1.126     brouard  8386: 
1.164     brouard  8387: 
1.126     brouard  8388: /*   setlocale (LC_ALL, ""); */
                   8389: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   8390: /*   textdomain (PACKAGE); */
                   8391: /*   setlocale (LC_CTYPE, ""); */
                   8392: /*   setlocale (LC_MESSAGES, ""); */
                   8393: 
                   8394:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  8395:   rstart_time = time(NULL);  
                   8396:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   8397:   start_time = *localtime(&rstart_time);
1.126     brouard  8398:   curr_time=start_time;
1.157     brouard  8399:   /*tml = *localtime(&start_time.tm_sec);*/
                   8400:   /* strcpy(strstart,asctime(&tml)); */
                   8401:   strcpy(strstart,asctime(&start_time));
1.126     brouard  8402: 
                   8403: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  8404: /*  tp.tm_sec = tp.tm_sec +86400; */
                   8405: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  8406: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   8407: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   8408: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  8409: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  8410: /*   strt=asctime(&tmg); */
                   8411: /*   printf("Time(after) =%s",strstart);  */
                   8412: /*  (void) time (&time_value);
                   8413: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   8414: *  tm = *localtime(&time_value);
                   8415: *  strstart=asctime(&tm);
                   8416: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   8417: */
                   8418: 
                   8419:   nberr=0; /* Number of errors and warnings */
                   8420:   nbwarn=0;
1.184     brouard  8421: #ifdef WIN32
                   8422:   _getcwd(pathcd, size);
                   8423: #else
1.126     brouard  8424:   getcwd(pathcd, size);
1.184     brouard  8425: #endif
1.191     brouard  8426:   syscompilerinfo(0);
1.196     brouard  8427:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  8428:   if(argc <=1){
                   8429:     printf("\nEnter the parameter file name: ");
1.205     brouard  8430:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   8431:       printf("ERROR Empty parameter file name\n");
                   8432:       goto end;
                   8433:     }
1.126     brouard  8434:     i=strlen(pathr);
                   8435:     if(pathr[i-1]=='\n')
                   8436:       pathr[i-1]='\0';
1.156     brouard  8437:     i=strlen(pathr);
1.205     brouard  8438:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  8439:       pathr[i-1]='\0';
1.205     brouard  8440:     }
                   8441:     i=strlen(pathr);
                   8442:     if( i==0 ){
                   8443:       printf("ERROR Empty parameter file name\n");
                   8444:       goto end;
                   8445:     }
                   8446:     for (tok = pathr; tok != NULL; ){
1.126     brouard  8447:       printf("Pathr |%s|\n",pathr);
                   8448:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   8449:       printf("val= |%s| pathr=%s\n",val,pathr);
                   8450:       strcpy (pathtot, val);
                   8451:       if(pathr[0] == '\0') break; /* Dirty */
                   8452:     }
                   8453:   }
                   8454:   else{
                   8455:     strcpy(pathtot,argv[1]);
                   8456:   }
                   8457:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   8458:   /*cygwin_split_path(pathtot,path,optionfile);
                   8459:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   8460:   /* cutv(path,optionfile,pathtot,'\\');*/
                   8461: 
                   8462:   /* Split argv[0], imach program to get pathimach */
                   8463:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   8464:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   8465:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   8466:  /*   strcpy(pathimach,argv[0]); */
                   8467:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   8468:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   8469:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  8470: #ifdef WIN32
                   8471:   _chdir(path); /* Can be a relative path */
                   8472:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   8473: #else
1.126     brouard  8474:   chdir(path); /* Can be a relative path */
1.184     brouard  8475:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   8476: #endif
                   8477:   printf("Current directory %s!\n",pathcd);
1.126     brouard  8478:   strcpy(command,"mkdir ");
                   8479:   strcat(command,optionfilefiname);
                   8480:   if((outcmd=system(command)) != 0){
1.169     brouard  8481:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  8482:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   8483:     /* fclose(ficlog); */
                   8484: /*     exit(1); */
                   8485:   }
                   8486: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   8487: /*     perror("mkdir"); */
                   8488: /*   } */
                   8489: 
                   8490:   /*-------- arguments in the command line --------*/
                   8491: 
1.186     brouard  8492:   /* Main Log file */
1.126     brouard  8493:   strcat(filelog, optionfilefiname);
                   8494:   strcat(filelog,".log");    /* */
                   8495:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   8496:     printf("Problem with logfile %s\n",filelog);
                   8497:     goto end;
                   8498:   }
                   8499:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  8500:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  8501:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   8502:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   8503:  path=%s \n\
                   8504:  optionfile=%s\n\
                   8505:  optionfilext=%s\n\
1.156     brouard  8506:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  8507: 
1.197     brouard  8508:   syscompilerinfo(1);
1.167     brouard  8509: 
1.126     brouard  8510:   printf("Local time (at start):%s",strstart);
                   8511:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   8512:   fflush(ficlog);
                   8513: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  8514: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  8515: 
                   8516:   /* */
                   8517:   strcpy(fileres,"r");
                   8518:   strcat(fileres, optionfilefiname);
1.201     brouard  8519:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  8520:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  8521:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  8522: 
1.186     brouard  8523:   /* Main ---------arguments file --------*/
1.126     brouard  8524: 
                   8525:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  8526:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   8527:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  8528:     fflush(ficlog);
1.149     brouard  8529:     /* goto end; */
                   8530:     exit(70); 
1.126     brouard  8531:   }
                   8532: 
                   8533: 
                   8534: 
                   8535:   strcpy(filereso,"o");
1.201     brouard  8536:   strcat(filereso,fileresu);
1.126     brouard  8537:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   8538:     printf("Problem with Output resultfile: %s\n", filereso);
                   8539:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   8540:     fflush(ficlog);
                   8541:     goto end;
                   8542:   }
                   8543: 
                   8544:   /* Reads comments: lines beginning with '#' */
                   8545:   numlinepar=0;
1.197     brouard  8546: 
                   8547:     /* First parameter line */
                   8548:   while(fgets(line, MAXLINE, ficpar)) {
                   8549:     /* If line starts with a # it is a comment */
                   8550:     if (line[0] == '#') {
                   8551:       numlinepar++;
                   8552:       fputs(line,stdout);
                   8553:       fputs(line,ficparo);
                   8554:       fputs(line,ficlog);
                   8555:       continue;
                   8556:     }else
                   8557:       break;
                   8558:   }
                   8559:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   8560:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   8561:     if (num_filled != 5) {
                   8562:       printf("Should be 5 parameters\n");
                   8563:     }
1.126     brouard  8564:     numlinepar++;
1.197     brouard  8565:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   8566:   }
                   8567:   /* Second parameter line */
                   8568:   while(fgets(line, MAXLINE, ficpar)) {
                   8569:     /* If line starts with a # it is a comment */
                   8570:     if (line[0] == '#') {
                   8571:       numlinepar++;
                   8572:       fputs(line,stdout);
                   8573:       fputs(line,ficparo);
                   8574:       fputs(line,ficlog);
                   8575:       continue;
                   8576:     }else
                   8577:       break;
                   8578:   }
1.223   ! brouard  8579:   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", \
        !          8580:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
        !          8581:     if (num_filled != 11) {
        !          8582:       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  8583:       printf("but line=%s\n",line);
1.197     brouard  8584:     }
1.223   ! brouard  8585:     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  8586:   }
1.203     brouard  8587:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  8588:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  8589:   /* Third parameter line */
                   8590:   while(fgets(line, MAXLINE, ficpar)) {
                   8591:     /* If line starts with a # it is a comment */
                   8592:     if (line[0] == '#') {
                   8593:       numlinepar++;
                   8594:       fputs(line,stdout);
                   8595:       fputs(line,ficparo);
                   8596:       fputs(line,ficlog);
                   8597:       continue;
                   8598:     }else
                   8599:       break;
                   8600:   }
1.201     brouard  8601:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
                   8602:     if (num_filled == 0)
                   8603:             model[0]='\0';
                   8604:     else if (num_filled != 1){
1.197     brouard  8605:       printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   8606:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   8607:       model[0]='\0';
                   8608:       goto end;
                   8609:     }
                   8610:     else{
                   8611:       if (model[0]=='+'){
                   8612:        for(i=1; i<=strlen(model);i++)
                   8613:          modeltemp[i-1]=model[i];
1.201     brouard  8614:        strcpy(model,modeltemp); 
1.197     brouard  8615:       }
                   8616:     }
1.199     brouard  8617:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  8618:     printf("model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  8619:   }
                   8620:   /* 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); */
                   8621:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   8622:   /* 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  8623:   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);
        !          8624:   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  8625:   fflush(ficlog);
1.190     brouard  8626:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   8627:   if(model[0]=='#'){
1.187     brouard  8628:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
                   8629:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
                   8630:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");         \
                   8631:     if(mle != -1){
                   8632:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
                   8633:       exit(1);
                   8634:     }
                   8635:   }
1.126     brouard  8636:   while((c=getc(ficpar))=='#' && c!= EOF){
                   8637:     ungetc(c,ficpar);
                   8638:     fgets(line, MAXLINE, ficpar);
                   8639:     numlinepar++;
1.195     brouard  8640:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   8641:       z[0]=line[1];
                   8642:     }
                   8643:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  8644:     fputs(line, stdout);
                   8645:     //puts(line);
1.126     brouard  8646:     fputs(line,ficparo);
                   8647:     fputs(line,ficlog);
                   8648:   }
                   8649:   ungetc(c,ficpar);
                   8650: 
                   8651:    
1.145     brouard  8652:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
1.223   ! brouard  8653:   coqvar=matrix(1,nqv,1,n);  /**< used in readdata */
        !          8654:   cotvar=ma3x(1,maxwav,1,ntv,1,n);  /**< used in readdata */
        !          8655:   cotqvar=ma3x(1,maxwav,1,ntqv,1,n);  /**< used in readdata */
1.136     brouard  8656:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   8657:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   8658:      v1+v2*age+v2*v3 makes cptcovn = 3
                   8659:   */
                   8660:   if (strlen(model)>1) 
1.187     brouard  8661:     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  8662:   else
1.187     brouard  8663:     ncovmodel=2; /* Constant and age */
1.133     brouard  8664:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   8665:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  8666:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   8667:     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);
                   8668:     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);
                   8669:     fflush(stdout);
                   8670:     fclose (ficlog);
                   8671:     goto end;
                   8672:   }
1.126     brouard  8673:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   8674:   delti=delti3[1][1];
                   8675:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   8676:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   8677:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  8678:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   8679:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  8680:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   8681:     fclose (ficparo);
                   8682:     fclose (ficlog);
                   8683:     goto end;
                   8684:     exit(0);
1.220     brouard  8685:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  8686:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  8687:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   8688:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  8689:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   8690:     matcov=matrix(1,npar,1,npar);
1.203     brouard  8691:     hess=matrix(1,npar,1,npar);
1.220     brouard  8692:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  8693:     /* Read guessed parameters */
1.126     brouard  8694:     /* Reads comments: lines beginning with '#' */
                   8695:     while((c=getc(ficpar))=='#' && c!= EOF){
                   8696:       ungetc(c,ficpar);
                   8697:       fgets(line, MAXLINE, ficpar);
                   8698:       numlinepar++;
1.141     brouard  8699:       fputs(line,stdout);
1.126     brouard  8700:       fputs(line,ficparo);
                   8701:       fputs(line,ficlog);
                   8702:     }
                   8703:     ungetc(c,ficpar);
                   8704:     
                   8705:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   8706:     for(i=1; i <=nlstate; i++){
1.220     brouard  8707:                        j=0;
1.126     brouard  8708:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.220     brouard  8709:                                if(jj==i) continue;
                   8710:                                j++;
                   8711:                                fscanf(ficpar,"%1d%1d",&i1,&j1);
                   8712:                                if ((i1 != i) || (j1 != jj)){
                   8713:                                        printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  8714: It might be a problem of design; if ncovcol and the model are correct\n \
                   8715: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.220     brouard  8716:                                        exit(1);
                   8717:                                }
                   8718:                                fprintf(ficparo,"%1d%1d",i1,j1);
                   8719:                                if(mle==1)
                   8720:                                        printf("%1d%1d",i,jj);
                   8721:                                fprintf(ficlog,"%1d%1d",i,jj);
                   8722:                                for(k=1; k<=ncovmodel;k++){
                   8723:                                        fscanf(ficpar," %lf",&param[i][j][k]);
                   8724:                                        if(mle==1){
                   8725:                                                printf(" %lf",param[i][j][k]);
                   8726:                                                fprintf(ficlog," %lf",param[i][j][k]);
                   8727:                                        }
                   8728:                                        else
                   8729:                                                fprintf(ficlog," %lf",param[i][j][k]);
                   8730:                                        fprintf(ficparo," %lf",param[i][j][k]);
                   8731:                                }
                   8732:                                fscanf(ficpar,"\n");
                   8733:                                numlinepar++;
                   8734:                                if(mle==1)
                   8735:                                        printf("\n");
                   8736:                                fprintf(ficlog,"\n");
                   8737:                                fprintf(ficparo,"\n");
1.126     brouard  8738:       }
                   8739:     }  
                   8740:     fflush(ficlog);
                   8741: 
1.145     brouard  8742:     /* Reads scales values */
1.126     brouard  8743:     p=param[1][1];
                   8744:     
                   8745:     /* Reads comments: lines beginning with '#' */
                   8746:     while((c=getc(ficpar))=='#' && c!= EOF){
                   8747:       ungetc(c,ficpar);
                   8748:       fgets(line, MAXLINE, ficpar);
                   8749:       numlinepar++;
1.141     brouard  8750:       fputs(line,stdout);
1.126     brouard  8751:       fputs(line,ficparo);
                   8752:       fputs(line,ficlog);
                   8753:     }
                   8754:     ungetc(c,ficpar);
                   8755: 
                   8756:     for(i=1; i <=nlstate; i++){
                   8757:       for(j=1; j <=nlstate+ndeath-1; j++){
1.220     brouard  8758:                                fscanf(ficpar,"%1d%1d",&i1,&j1);
                   8759:                                if ( (i1-i) * (j1-j) != 0){
                   8760:                                        printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   8761:                                        exit(1);
                   8762:                                }
                   8763:                                printf("%1d%1d",i,j);
                   8764:                                fprintf(ficparo,"%1d%1d",i1,j1);
                   8765:                                fprintf(ficlog,"%1d%1d",i1,j1);
                   8766:                                for(k=1; k<=ncovmodel;k++){
                   8767:                                        fscanf(ficpar,"%le",&delti3[i][j][k]);
                   8768:                                        printf(" %le",delti3[i][j][k]);
                   8769:                                        fprintf(ficparo," %le",delti3[i][j][k]);
                   8770:                                        fprintf(ficlog," %le",delti3[i][j][k]);
                   8771:                                }
                   8772:                                fscanf(ficpar,"\n");
                   8773:                                numlinepar++;
                   8774:                                printf("\n");
                   8775:                                fprintf(ficparo,"\n");
                   8776:                                fprintf(ficlog,"\n");
1.126     brouard  8777:       }
                   8778:     }
                   8779:     fflush(ficlog);
1.220     brouard  8780:                
1.145     brouard  8781:     /* Reads covariance matrix */
1.126     brouard  8782:     delti=delti3[1][1];
1.220     brouard  8783:                
                   8784:                
1.126     brouard  8785:     /* 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  8786:                
1.126     brouard  8787:     /* Reads comments: lines beginning with '#' */
                   8788:     while((c=getc(ficpar))=='#' && c!= EOF){
                   8789:       ungetc(c,ficpar);
                   8790:       fgets(line, MAXLINE, ficpar);
                   8791:       numlinepar++;
1.141     brouard  8792:       fputs(line,stdout);
1.126     brouard  8793:       fputs(line,ficparo);
                   8794:       fputs(line,ficlog);
                   8795:     }
                   8796:     ungetc(c,ficpar);
1.220     brouard  8797:                
1.126     brouard  8798:     matcov=matrix(1,npar,1,npar);
1.203     brouard  8799:     hess=matrix(1,npar,1,npar);
1.131     brouard  8800:     for(i=1; i <=npar; i++)
                   8801:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  8802:                
1.194     brouard  8803:     /* Scans npar lines */
1.126     brouard  8804:     for(i=1; i <=npar; i++){
1.194     brouard  8805:       count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);
                   8806:       if(count != 3){
1.220     brouard  8807:                                printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  8808: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   8809: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.220     brouard  8810:                                fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  8811: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   8812: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.220     brouard  8813:                                exit(1);
                   8814:       }else{
                   8815:                                if(mle==1)
                   8816:                                        printf("%1d%1d%1d",i1,j1,jk);
                   8817:                        }
1.194     brouard  8818:       fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);
                   8819:       fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);
1.126     brouard  8820:       for(j=1; j <=i; j++){
1.220     brouard  8821:                                fscanf(ficpar," %le",&matcov[i][j]);
                   8822:                                if(mle==1){
                   8823:                                        printf(" %.5le",matcov[i][j]);
                   8824:                                }
                   8825:                                fprintf(ficlog," %.5le",matcov[i][j]);
                   8826:                                fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  8827:       }
                   8828:       fscanf(ficpar,"\n");
                   8829:       numlinepar++;
                   8830:       if(mle==1)
1.220     brouard  8831:                                printf("\n");
1.126     brouard  8832:       fprintf(ficlog,"\n");
                   8833:       fprintf(ficparo,"\n");
                   8834:     }
1.194     brouard  8835:     /* End of read covariance matrix npar lines */
1.126     brouard  8836:     for(i=1; i <=npar; i++)
                   8837:       for(j=i+1;j<=npar;j++)
1.220     brouard  8838:                                matcov[i][j]=matcov[j][i];
1.126     brouard  8839:     
                   8840:     if(mle==1)
                   8841:       printf("\n");
                   8842:     fprintf(ficlog,"\n");
                   8843:     
                   8844:     fflush(ficlog);
                   8845:     
                   8846:     /*-------- Rewriting parameter file ----------*/
                   8847:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   8848:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   8849:     strcat(rfileres,".");    /* */
                   8850:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   8851:     if((ficres =fopen(rfileres,"w"))==NULL) {
1.201     brouard  8852:       printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   8853:       fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
1.126     brouard  8854:     }
                   8855:     fprintf(ficres,"#%s\n",version);
                   8856:   }    /* End of mle != -3 */
1.218     brouard  8857:   
1.186     brouard  8858:   /*  Main data
                   8859:    */
1.126     brouard  8860:   n= lastobs;
                   8861:   num=lvector(1,n);
                   8862:   moisnais=vector(1,n);
                   8863:   annais=vector(1,n);
                   8864:   moisdc=vector(1,n);
                   8865:   andc=vector(1,n);
1.220     brouard  8866:   weight=vector(1,n);
1.126     brouard  8867:   agedc=vector(1,n);
                   8868:   cod=ivector(1,n);
1.220     brouard  8869:   for(i=1;i<=n;i++){
                   8870:                num[i]=0;
                   8871:                moisnais[i]=0;
                   8872:                annais[i]=0;
                   8873:                moisdc[i]=0;
                   8874:                andc[i]=0;
                   8875:                agedc[i]=0;
                   8876:                cod[i]=0;
                   8877:                weight[i]=1.0; /* Equal weights, 1 by default */
                   8878:        }
1.126     brouard  8879:   mint=matrix(1,maxwav,1,n);
                   8880:   anint=matrix(1,maxwav,1,n);
1.131     brouard  8881:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  8882:   tab=ivector(1,NCOVMAX);
1.144     brouard  8883:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  8884:   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  8885: 
1.136     brouard  8886:   /* Reads data from file datafile */
                   8887:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   8888:     goto end;
                   8889: 
                   8890:   /* Calculation of the number of parameters from char model */
1.137     brouard  8891:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
                   8892:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   8893:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   8894:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   8895:        k=1 Tvar[1]=2 (from V2)
                   8896:     */
                   8897:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   8898:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   8899:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   8900:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   8901:   */
                   8902:   /* For model-covariate k tells which data-covariate to use but
                   8903:     because this model-covariate is a construction we invent a new column
                   8904:     ncovcol + k1
                   8905:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   8906:     Tvar[3=V1*V4]=4+1 etc */
1.145     brouard  8907:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137     brouard  8908:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   8909:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
                   8910:   */
1.145     brouard  8911:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   8912:   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  8913:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   8914:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  8915:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  8916:                         4 covariates (3 plus signs)
                   8917:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   8918:                      */  
1.136     brouard  8919: 
1.186     brouard  8920: /* Main decodemodel */
                   8921: 
1.187     brouard  8922: 
1.223   ! brouard  8923:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  8924:     goto end;
                   8925: 
1.137     brouard  8926:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   8927:     nbwarn++;
                   8928:     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); 
                   8929:     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); 
                   8930:   }
1.136     brouard  8931:     /*  if(mle==1){*/
1.137     brouard  8932:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   8933:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  8934:   }
                   8935: 
                   8936:     /*-calculation of age at interview from date of interview and age at death -*/
                   8937:   agev=matrix(1,maxwav,1,imx);
                   8938: 
                   8939:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   8940:     goto end;
                   8941: 
1.126     brouard  8942: 
1.136     brouard  8943:   agegomp=(int)agemin;
                   8944:   free_vector(moisnais,1,n);
                   8945:   free_vector(annais,1,n);
1.126     brouard  8946:   /* free_matrix(mint,1,maxwav,1,n);
                   8947:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  8948:   /* free_vector(moisdc,1,n); */
                   8949:   /* free_vector(andc,1,n); */
1.145     brouard  8950:   /* */
                   8951:   
1.126     brouard  8952:   wav=ivector(1,imx);
1.214     brouard  8953:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   8954:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   8955:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   8956:   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.*/
                   8957:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   8958:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  8959:    
                   8960:   /* Concatenates waves */
1.214     brouard  8961:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   8962:      Death is a valid wave (if date is known).
                   8963:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   8964:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   8965:      and mw[mi+1][i]. dh depends on stepm.
                   8966:   */
                   8967: 
1.126     brouard  8968:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.145     brouard  8969:   /* */
                   8970:  
1.215     brouard  8971:   free_vector(moisdc,1,n);
                   8972:   free_vector(andc,1,n);
                   8973: 
1.126     brouard  8974:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   8975:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   8976:   ncodemax[1]=1;
1.145     brouard  8977:   Ndum =ivector(-1,NCOVMAX);  
1.220     brouard  8978:        cptcoveff=0;
                   8979:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
                   8980:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
                   8981:        }
                   8982:        
                   8983:        ncovcombmax=pow(2,cptcoveff);
                   8984:        invalidvarcomb=ivector(1, ncovcombmax); 
                   8985:        for(i=1;i<ncovcombmax;i++)
                   8986:                invalidvarcomb[i]=0;
                   8987: 
1.211     brouard  8988:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  8989:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  8990:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.145     brouard  8991: 
1.200     brouard  8992:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  8993:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  8994:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  8995:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   8996:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   8997:    * (currently 0 or 1) in the data.
                   8998:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   8999:    * corresponding modality (h,j).
                   9000:    */
                   9001: 
1.145     brouard  9002:   h=0;
                   9003:   /*if (cptcovn > 0) */
1.126     brouard  9004:   m=pow(2,cptcoveff);
                   9005:  
1.144     brouard  9006:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  9007:           * For k=4 covariates, h goes from 1 to m=2**k
                   9008:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   9009:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.186     brouard  9010:           *     h\k   1     2     3     4
1.143     brouard  9011:           *______________________________  
                   9012:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   9013:           *     2     2     1     1     1
                   9014:           *     3 i=2 1     2     1     1
                   9015:           *     4     2     2     1     1
                   9016:           *     5 i=3 1 i=2 1     2     1
                   9017:           *     6     2     1     2     1
                   9018:           *     7 i=4 1     2     2     1
                   9019:           *     8     2     2     2     1
1.197     brouard  9020:           *     9 i=5 1 i=3 1 i=2 1     2
                   9021:           *    10     2     1     1     2
                   9022:           *    11 i=6 1     2     1     2
                   9023:           *    12     2     2     1     2
                   9024:           *    13 i=7 1 i=4 1     2     2    
                   9025:           *    14     2     1     2     2
                   9026:           *    15 i=8 1     2     2     2
                   9027:           *    16     2     2     2     2
1.143     brouard  9028:           */
1.212     brouard  9029:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  9030:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   9031:      * and the value of each covariate?
                   9032:      * V1=1, V2=1, V3=2, V4=1 ?
                   9033:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   9034:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   9035:      * In order to get the real value in the data, we use nbcode
                   9036:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   9037:      * We are keeping this crazy system in order to be able (in the future?) 
                   9038:      * to have more than 2 values (0 or 1) for a covariate.
                   9039:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   9040:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   9041:      *              bbbbbbbb
                   9042:      *              76543210     
                   9043:      *   h-1        00000101 (6-1=5)
1.219     brouard  9044:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  9045:      *           &
                   9046:      *     1        00000001 (1)
1.219     brouard  9047:      *              00000000        = 1 & ((h-1) >> (k-1))
                   9048:      *          +1= 00000001 =1 
1.211     brouard  9049:      *
                   9050:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   9051:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   9052:      *    >>k'            11
                   9053:      *          &   00000001
                   9054:      *            = 00000001
                   9055:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   9056:      * Reverse h=6 and m=16?
                   9057:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   9058:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   9059:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   9060:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   9061:      * V3=decodtabm(14,3,2**4)=2
                   9062:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   9063:      *(h-1) >> (j-1)    0011 =13 >> 2
                   9064:      *          &1 000000001
                   9065:      *           = 000000001
                   9066:      *         +1= 000000010 =2
                   9067:      *                  2211
                   9068:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   9069:      *                  V3=2
1.220     brouard  9070:                 * codtabm and decodtabm are identical
1.211     brouard  9071:      */
                   9072: 
1.145     brouard  9073: 
                   9074:  free_ivector(Ndum,-1,NCOVMAX);
                   9075: 
                   9076: 
1.126     brouard  9077:     
1.186     brouard  9078:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  9079:   strcpy(optionfilegnuplot,optionfilefiname);
                   9080:   if(mle==-3)
1.201     brouard  9081:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  9082:   strcat(optionfilegnuplot,".gp");
                   9083: 
                   9084:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   9085:     printf("Problem with file %s",optionfilegnuplot);
                   9086:   }
                   9087:   else{
1.204     brouard  9088:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  9089:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  9090:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   9091:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  9092:   }
                   9093:   /*  fclose(ficgp);*/
1.186     brouard  9094: 
                   9095: 
                   9096:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  9097: 
                   9098:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   9099:   if(mle==-3)
1.201     brouard  9100:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  9101:   strcat(optionfilehtm,".htm");
                   9102:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  9103:     printf("Problem with %s \n",optionfilehtm);
                   9104:     exit(0);
1.126     brouard  9105:   }
                   9106: 
                   9107:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   9108:   strcat(optionfilehtmcov,"-cov.htm");
                   9109:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   9110:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   9111:   }
                   9112:   else{
                   9113:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   9114: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  9115: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  9116:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   9117:   }
                   9118: 
1.213     brouard  9119:   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  9120: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   9121: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  9122: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  9123: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  9124: \n\
                   9125: <hr  size=\"2\" color=\"#EC5E5E\">\
                   9126:  <ul><li><h4>Parameter files</h4>\n\
                   9127:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   9128:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   9129:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   9130:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   9131:  - Date and time at start: %s</ul>\n",\
                   9132:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   9133:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   9134:          fileres,fileres,\
                   9135:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   9136:   fflush(fichtm);
                   9137: 
                   9138:   strcpy(pathr,path);
                   9139:   strcat(pathr,optionfilefiname);
1.184     brouard  9140: #ifdef WIN32
                   9141:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   9142: #else
1.126     brouard  9143:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  9144: #endif
                   9145:          
1.126     brouard  9146:   
1.220     brouard  9147:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   9148:                 and for any valid combination of covariates
1.126     brouard  9149:      and prints on file fileres'p'. */
1.220     brouard  9150:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart,   \
1.223   ! brouard  9151:                                                        firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  9152: 
                   9153:   fprintf(fichtm,"\n");
                   9154:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   9155: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   9156: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   9157:          imx,agemin,agemax,jmin,jmax,jmean);
                   9158:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.220     brouard  9159:        oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   9160:        newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   9161:        savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   9162:        oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  9163: 
1.126     brouard  9164:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   9165:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   9166:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   9167: 
                   9168:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  9169:   /* For mortality only */
1.126     brouard  9170:   if (mle==-3){
1.136     brouard  9171:     ximort=matrix(1,NDIM,1,NDIM); 
1.220     brouard  9172:                for(i=1;i<=NDIM;i++)
                   9173:                        for(j=1;j<=NDIM;j++)
                   9174:                                ximort[i][j]=0.;
1.186     brouard  9175:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  9176:     cens=ivector(1,n);
                   9177:     ageexmed=vector(1,n);
                   9178:     agecens=vector(1,n);
                   9179:     dcwave=ivector(1,n);
1.223   ! brouard  9180:                
1.126     brouard  9181:     for (i=1; i<=imx; i++){
                   9182:       dcwave[i]=-1;
                   9183:       for (m=firstpass; m<=lastpass; m++)
1.218     brouard  9184:                                if (s[m][i]>nlstate) {
                   9185:                                        dcwave[i]=m;
                   9186:                                        /*      printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   9187:                                        break;
                   9188:                                }
1.126     brouard  9189:     }
1.218     brouard  9190:                
1.126     brouard  9191:     for (i=1; i<=imx; i++) {
                   9192:       if (wav[i]>0){
1.218     brouard  9193:                                ageexmed[i]=agev[mw[1][i]][i];
                   9194:                                j=wav[i];
                   9195:                                agecens[i]=1.; 
                   9196:                                
                   9197:                                if (ageexmed[i]> 1 && wav[i] > 0){
                   9198:                                        agecens[i]=agev[mw[j][i]][i];
                   9199:                                        cens[i]= 1;
                   9200:                                }else if (ageexmed[i]< 1) 
                   9201:                                        cens[i]= -1;
                   9202:                                if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   9203:                                        cens[i]=0 ;
1.126     brouard  9204:       }
                   9205:       else cens[i]=-1;
                   9206:     }
                   9207:     
                   9208:     for (i=1;i<=NDIM;i++) {
                   9209:       for (j=1;j<=NDIM;j++)
1.218     brouard  9210:                                ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  9211:     }
                   9212:     
1.145     brouard  9213:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  9214:     /*printf("%lf %lf", p[1], p[2]);*/
                   9215:     
                   9216:     
1.136     brouard  9217: #ifdef GSL
                   9218:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  9219: #else
1.126     brouard  9220:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  9221: #endif
1.201     brouard  9222:     strcpy(filerespow,"POW-MORT_"); 
                   9223:     strcat(filerespow,fileresu);
1.126     brouard  9224:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   9225:       printf("Problem with resultfile: %s\n", filerespow);
                   9226:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   9227:     }
1.136     brouard  9228: #ifdef GSL
                   9229:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  9230: #else
1.126     brouard  9231:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  9232: #endif
1.126     brouard  9233:     /*  for (i=1;i<=nlstate;i++)
                   9234:        for(j=1;j<=nlstate+ndeath;j++)
                   9235:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   9236:     */
                   9237:     fprintf(ficrespow,"\n");
1.136     brouard  9238: #ifdef GSL
                   9239:     /* gsl starts here */ 
                   9240:     T = gsl_multimin_fminimizer_nmsimplex;
                   9241:     gsl_multimin_fminimizer *sfm = NULL;
                   9242:     gsl_vector *ss, *x;
                   9243:     gsl_multimin_function minex_func;
                   9244: 
                   9245:     /* Initial vertex size vector */
                   9246:     ss = gsl_vector_alloc (NDIM);
                   9247:     
                   9248:     if (ss == NULL){
                   9249:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   9250:     }
                   9251:     /* Set all step sizes to 1 */
                   9252:     gsl_vector_set_all (ss, 0.001);
                   9253: 
                   9254:     /* Starting point */
1.126     brouard  9255:     
1.136     brouard  9256:     x = gsl_vector_alloc (NDIM);
                   9257:     
                   9258:     if (x == NULL){
                   9259:       gsl_vector_free(ss);
                   9260:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   9261:     }
                   9262:   
                   9263:     /* Initialize method and iterate */
                   9264:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  9265:     /*     gsl_vector_set(x, 0, 0.0268); */
                   9266:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  9267:     gsl_vector_set(x, 0, p[1]);
                   9268:     gsl_vector_set(x, 1, p[2]);
                   9269: 
                   9270:     minex_func.f = &gompertz_f;
                   9271:     minex_func.n = NDIM;
                   9272:     minex_func.params = (void *)&p; /* ??? */
                   9273:     
                   9274:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   9275:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   9276:     
                   9277:     printf("Iterations beginning .....\n\n");
                   9278:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   9279: 
                   9280:     iteri=0;
                   9281:     while (rval == GSL_CONTINUE){
                   9282:       iteri++;
                   9283:       status = gsl_multimin_fminimizer_iterate(sfm);
                   9284:       
                   9285:       if (status) printf("error: %s\n", gsl_strerror (status));
                   9286:       fflush(0);
                   9287:       
                   9288:       if (status) 
                   9289:         break;
                   9290:       
                   9291:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   9292:       ssval = gsl_multimin_fminimizer_size (sfm);
                   9293:       
                   9294:       if (rval == GSL_SUCCESS)
                   9295:         printf ("converged to a local maximum at\n");
                   9296:       
                   9297:       printf("%5d ", iteri);
                   9298:       for (it = 0; it < NDIM; it++){
                   9299:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   9300:       }
                   9301:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   9302:     }
                   9303:     
                   9304:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   9305:     
                   9306:     gsl_vector_free(x); /* initial values */
                   9307:     gsl_vector_free(ss); /* inital step size */
                   9308:     for (it=0; it<NDIM; it++){
                   9309:       p[it+1]=gsl_vector_get(sfm->x,it);
                   9310:       fprintf(ficrespow," %.12lf", p[it]);
                   9311:     }
                   9312:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   9313: #endif
                   9314: #ifdef POWELL
                   9315:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   9316: #endif  
1.126     brouard  9317:     fclose(ficrespow);
                   9318:     
1.203     brouard  9319:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  9320: 
                   9321:     for(i=1; i <=NDIM; i++)
                   9322:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  9323:                                matcov[i][j]=matcov[j][i];
1.126     brouard  9324:     
                   9325:     printf("\nCovariance matrix\n ");
1.203     brouard  9326:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  9327:     for(i=1; i <=NDIM; i++) {
                   9328:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  9329:                                printf("%f ",matcov[i][j]);
                   9330:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  9331:       }
1.203     brouard  9332:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  9333:     }
                   9334:     
                   9335:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  9336:     for (i=1;i<=NDIM;i++) {
1.126     brouard  9337:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  9338:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   9339:     }
1.126     brouard  9340:     lsurv=vector(1,AGESUP);
                   9341:     lpop=vector(1,AGESUP);
                   9342:     tpop=vector(1,AGESUP);
                   9343:     lsurv[agegomp]=100000;
                   9344:     
                   9345:     for (k=agegomp;k<=AGESUP;k++) {
                   9346:       agemortsup=k;
                   9347:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   9348:     }
                   9349:     
                   9350:     for (k=agegomp;k<agemortsup;k++)
                   9351:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   9352:     
                   9353:     for (k=agegomp;k<agemortsup;k++){
                   9354:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   9355:       sumlpop=sumlpop+lpop[k];
                   9356:     }
                   9357:     
                   9358:     tpop[agegomp]=sumlpop;
                   9359:     for (k=agegomp;k<(agemortsup-3);k++){
                   9360:       /*  tpop[k+1]=2;*/
                   9361:       tpop[k+1]=tpop[k]-lpop[k];
                   9362:     }
                   9363:     
                   9364:     
                   9365:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   9366:     for (k=agegomp;k<(agemortsup-2);k++) 
                   9367:       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]);
                   9368:     
                   9369:     
                   9370:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  9371:                ageminpar=50;
                   9372:                agemaxpar=100;
1.194     brouard  9373:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   9374:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   9375: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   9376: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   9377:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   9378: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   9379: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  9380:     }else{
                   9381:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   9382:                        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  9383:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  9384:                }
1.201     brouard  9385:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  9386:                     stepm, weightopt,\
                   9387:                     model,imx,p,matcov,agemortsup);
                   9388:     
                   9389:     free_vector(lsurv,1,AGESUP);
                   9390:     free_vector(lpop,1,AGESUP);
                   9391:     free_vector(tpop,1,AGESUP);
1.220     brouard  9392:     free_matrix(ximort,1,NDIM,1,NDIM);
1.136     brouard  9393:     free_ivector(cens,1,n);
                   9394:     free_vector(agecens,1,n);
                   9395:     free_ivector(dcwave,1,n);
1.220     brouard  9396: #ifdef GSL
1.136     brouard  9397: #endif
1.186     brouard  9398:   } /* Endof if mle==-3 mortality only */
1.205     brouard  9399:   /* Standard  */
                   9400:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   9401:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   9402:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  9403:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  9404:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   9405:     for (k=1; k<=npar;k++)
                   9406:       printf(" %d %8.5f",k,p[k]);
                   9407:     printf("\n");
1.205     brouard  9408:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   9409:       /* mlikeli uses func not funcone */
                   9410:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   9411:     }
                   9412:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   9413:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   9414:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   9415:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   9416:     }
                   9417:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  9418:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   9419:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   9420:     for (k=1; k<=npar;k++)
                   9421:       printf(" %d %8.5f",k,p[k]);
                   9422:     printf("\n");
                   9423:     
                   9424:     /*--------- results files --------------*/
1.192     brouard  9425:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle= 0 weight=%d\nmodel=1+age+%s.\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate, ndeath, maxwav, weightopt,model);
1.126     brouard  9426:     
                   9427:     
                   9428:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9429:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9430:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9431:     for(i=1,jk=1; i <=nlstate; i++){
                   9432:       for(k=1; k <=(nlstate+ndeath); k++){
1.220     brouard  9433:                                if (k != i) {
                   9434:                                        printf("%d%d ",i,k);
                   9435:                                        fprintf(ficlog,"%d%d ",i,k);
                   9436:                                        fprintf(ficres,"%1d%1d ",i,k);
                   9437:                                        for(j=1; j <=ncovmodel; j++){
                   9438:                                                printf("%12.7f ",p[jk]);
                   9439:                                                fprintf(ficlog,"%12.7f ",p[jk]);
                   9440:                                                fprintf(ficres,"%12.7f ",p[jk]);
                   9441:                                                jk++; 
                   9442:                                        }
                   9443:                                        printf("\n");
                   9444:                                        fprintf(ficlog,"\n");
                   9445:                                        fprintf(ficres,"\n");
                   9446:                                }
1.126     brouard  9447:       }
                   9448:     }
1.203     brouard  9449:     if(mle != 0){
                   9450:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  9451:       ftolhess=ftol; /* Usually correct */
1.203     brouard  9452:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   9453:       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");
                   9454:       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");
                   9455:       for(i=1,jk=1; i <=nlstate; i++){
1.220     brouard  9456:                                for(k=1; k <=(nlstate+ndeath); k++){
                   9457:                                        if (k != i) {
                   9458:                                                printf("%d%d ",i,k);
                   9459:                                                fprintf(ficlog,"%d%d ",i,k);
                   9460:                                                for(j=1; j <=ncovmodel; j++){
                   9461:                                                        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]));
                   9462:                                                        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]));
                   9463:                                                        jk++; 
                   9464:                                                }
                   9465:                                                printf("\n");
                   9466:                                                fprintf(ficlog,"\n");
                   9467:                                        }
                   9468:                                }
1.193     brouard  9469:       }
1.203     brouard  9470:     } /* end of hesscov and Wald tests */
1.220     brouard  9471:                
1.203     brouard  9472:     /*  */
1.126     brouard  9473:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   9474:     printf("# Scales (for hessian or gradient estimation)\n");
                   9475:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   9476:     for(i=1,jk=1; i <=nlstate; i++){
                   9477:       for(j=1; j <=nlstate+ndeath; j++){
1.220     brouard  9478:                                if (j!=i) {
                   9479:                                        fprintf(ficres,"%1d%1d",i,j);
                   9480:                                        printf("%1d%1d",i,j);
                   9481:                                        fprintf(ficlog,"%1d%1d",i,j);
                   9482:                                        for(k=1; k<=ncovmodel;k++){
                   9483:                                                printf(" %.5e",delti[jk]);
                   9484:                                                fprintf(ficlog," %.5e",delti[jk]);
                   9485:                                                fprintf(ficres," %.5e",delti[jk]);
                   9486:                                                jk++;
                   9487:                                        }
                   9488:                                        printf("\n");
                   9489:                                        fprintf(ficlog,"\n");
                   9490:                                        fprintf(ficres,"\n");
                   9491:                                }
1.126     brouard  9492:       }
                   9493:     }
                   9494:     
                   9495:     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  9496:     if(mle >= 1) /* To big for the screen */
1.126     brouard  9497:       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");
                   9498:     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");
                   9499:     /* # 121 Var(a12)\n\ */
                   9500:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   9501:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   9502:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   9503:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   9504:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   9505:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   9506:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   9507:     
                   9508:     
                   9509:     /* Just to have a covariance matrix which will be more understandable
                   9510:        even is we still don't want to manage dictionary of variables
                   9511:     */
                   9512:     for(itimes=1;itimes<=2;itimes++){
                   9513:       jj=0;
                   9514:       for(i=1; i <=nlstate; i++){
1.220     brouard  9515:                                for(j=1; j <=nlstate+ndeath; j++){
                   9516:                                        if(j==i) continue;
                   9517:                                        for(k=1; k<=ncovmodel;k++){
                   9518:                                                jj++;
                   9519:                                                ca[0]= k+'a'-1;ca[1]='\0';
                   9520:                                                if(itimes==1){
                   9521:                                                        if(mle>=1)
                   9522:                                                                printf("#%1d%1d%d",i,j,k);
                   9523:                                                        fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   9524:                                                        fprintf(ficres,"#%1d%1d%d",i,j,k);
                   9525:                                                }else{
                   9526:                                                        if(mle>=1)
                   9527:                                                                printf("%1d%1d%d",i,j,k);
                   9528:                                                        fprintf(ficlog,"%1d%1d%d",i,j,k);
                   9529:                                                        fprintf(ficres,"%1d%1d%d",i,j,k);
                   9530:                                                }
                   9531:                                                ll=0;
                   9532:                                                for(li=1;li <=nlstate; li++){
                   9533:                                                        for(lj=1;lj <=nlstate+ndeath; lj++){
                   9534:                                                                if(lj==li) continue;
                   9535:                                                                for(lk=1;lk<=ncovmodel;lk++){
                   9536:                                                                        ll++;
                   9537:                                                                        if(ll<=jj){
                   9538:                                                                                cb[0]= lk +'a'-1;cb[1]='\0';
                   9539:                                                                                if(ll<jj){
                   9540:                                                                                        if(itimes==1){
                   9541:                                                                                                if(mle>=1)
                   9542:                                                                                                        printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9543:                                                                                                fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9544:                                                                                                fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   9545:                                                                                        }else{
                   9546:                                                                                                if(mle>=1)
                   9547:                                                                                                        printf(" %.5e",matcov[jj][ll]); 
                   9548:                                                                                                fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   9549:                                                                                                fprintf(ficres," %.5e",matcov[jj][ll]); 
                   9550:                                                                                        }
                   9551:                                                                                }else{
                   9552:                                                                                        if(itimes==1){
                   9553:                                                                                                if(mle>=1)
                   9554:                                                                                                        printf(" Var(%s%1d%1d)",ca,i,j);
                   9555:                                                                                                fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   9556:                                                                                                fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   9557:                                                                                        }else{
                   9558:                                                                                                if(mle>=1)
                   9559:                                                                                                        printf(" %.7e",matcov[jj][ll]); 
                   9560:                                                                                                fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   9561:                                                                                                fprintf(ficres," %.7e",matcov[jj][ll]); 
                   9562:                                                                                        }
                   9563:                                                                                }
                   9564:                                                                        }
                   9565:                                                                } /* end lk */
                   9566:                                                        } /* end lj */
                   9567:                                                } /* end li */
                   9568:                                                if(mle>=1)
                   9569:                                                        printf("\n");
                   9570:                                                fprintf(ficlog,"\n");
                   9571:                                                fprintf(ficres,"\n");
                   9572:                                                numlinepar++;
                   9573:                                        } /* end k*/
                   9574:                                } /*end j */
1.126     brouard  9575:       } /* end i */
                   9576:     } /* end itimes */
                   9577:     
                   9578:     fflush(ficlog);
                   9579:     fflush(ficres);
1.220     brouard  9580:                while(fgets(line, MAXLINE, ficpar)) {
                   9581:                        /* If line starts with a # it is a comment */
                   9582:                        if (line[0] == '#') {
                   9583:                                numlinepar++;
                   9584:                                fputs(line,stdout);
                   9585:                                fputs(line,ficparo);
                   9586:                                fputs(line,ficlog);
                   9587:                                continue;
                   9588:                        }else
                   9589:                                break;
                   9590:                }
                   9591:                
1.209     brouard  9592:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   9593:     /*   ungetc(c,ficpar); */
                   9594:     /*   fgets(line, MAXLINE, ficpar); */
                   9595:     /*   fputs(line,stdout); */
                   9596:     /*   fputs(line,ficparo); */
                   9597:     /* } */
                   9598:     /* ungetc(c,ficpar); */
1.126     brouard  9599:     
                   9600:     estepm=0;
1.209     brouard  9601:     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  9602:                        
                   9603:                        if (num_filled != 6) {
                   9604:                                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);
                   9605:                                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);
                   9606:                                goto end;
                   9607:                        }
                   9608:                        printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   9609:                }
                   9610:                /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   9611:                /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   9612:                
1.209     brouard  9613:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  9614:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   9615:     if (fage <= 2) {
                   9616:       bage = ageminpar;
                   9617:       fage = agemaxpar;
                   9618:     }
                   9619:     
                   9620:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  9621:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   9622:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  9623:                
1.186     brouard  9624:     /* Other stuffs, more or less useful */    
1.126     brouard  9625:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9626:       ungetc(c,ficpar);
                   9627:       fgets(line, MAXLINE, ficpar);
1.141     brouard  9628:       fputs(line,stdout);
1.126     brouard  9629:       fputs(line,ficparo);
                   9630:     }
                   9631:     ungetc(c,ficpar);
                   9632:     
                   9633:     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);
                   9634:     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);
                   9635:     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);
                   9636:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   9637:     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);
                   9638:     
                   9639:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9640:       ungetc(c,ficpar);
                   9641:       fgets(line, MAXLINE, ficpar);
1.141     brouard  9642:       fputs(line,stdout);
1.126     brouard  9643:       fputs(line,ficparo);
                   9644:     }
                   9645:     ungetc(c,ficpar);
                   9646:     
                   9647:     
                   9648:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   9649:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   9650:     
                   9651:     fscanf(ficpar,"pop_based=%d\n",&popbased);
1.193     brouard  9652:     fprintf(ficlog,"pop_based=%d\n",popbased);
1.126     brouard  9653:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   9654:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   9655:     
                   9656:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9657:       ungetc(c,ficpar);
                   9658:       fgets(line, MAXLINE, ficpar);
1.141     brouard  9659:       fputs(line,stdout);
1.126     brouard  9660:       fputs(line,ficparo);
                   9661:     }
                   9662:     ungetc(c,ficpar);
                   9663:     
                   9664:     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);
                   9665:     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);
                   9666:     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);
                   9667:     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);
                   9668:     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);
                   9669:     /* day and month of proj2 are not used but only year anproj2.*/
                   9670:     
1.217     brouard  9671:     while((c=getc(ficpar))=='#' && c!= EOF){
                   9672:       ungetc(c,ficpar);
                   9673:       fgets(line, MAXLINE, ficpar);
                   9674:       fputs(line,stdout);
                   9675:       fputs(line,ficparo);
                   9676:     }
                   9677:     ungetc(c,ficpar);
                   9678:     
                   9679:     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  9680:     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);
        !          9681:     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);
        !          9682:     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  9683:     /* day and month of proj2 are not used but only year anproj2.*/
1.126     brouard  9684:     
                   9685:     
1.220     brouard  9686:                /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  9687:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  9688:     
                   9689:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  9690:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.220     brouard  9691:                        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  9692: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   9693: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  9694:                        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  9695: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   9696: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  9697:     }else{
1.218     brouard  9698:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p);
1.220     brouard  9699:     }
                   9700:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
                   9701:                                                                 model,imx,jmin,jmax,jmean,rfileres,popforecast,prevfcast,backcast, estepm, \
                   9702:                                                                 jprev1,mprev1,anprev1,dateprev1,jprev2,mprev2,anprev2,dateprev2);
                   9703:                
                   9704:                /*------------ free_vector  -------------*/
                   9705:                /*  chdir(path); */
                   9706:                
1.215     brouard  9707:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   9708:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   9709:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   9710:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.126     brouard  9711:     free_lvector(num,1,n);
                   9712:     free_vector(agedc,1,n);
                   9713:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   9714:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   9715:     fclose(ficparo);
                   9716:     fclose(ficres);
1.220     brouard  9717:                
                   9718:                
1.186     brouard  9719:     /* Other results (useful)*/
1.220     brouard  9720:                
                   9721:                
1.126     brouard  9722:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  9723:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   9724:     prlim=matrix(1,nlstate,1,nlstate);
1.209     brouard  9725:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  9726:     fclose(ficrespl);
                   9727: 
                   9728:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  9729:     /*#include "hpijx.h"*/
                   9730:     hPijx(p, bage, fage);
1.145     brouard  9731:     fclose(ficrespij);
1.126     brouard  9732: 
1.220     brouard  9733:     /* ncovcombmax=  pow(2,cptcoveff); */
1.219     brouard  9734:     /*-------------- Variance of one-step probabilities---*/
1.145     brouard  9735:     k=1;
1.126     brouard  9736:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
                   9737: 
1.219     brouard  9738:     /* Prevalence for each covariates in probs[age][status][cov] */
1.218     brouard  9739:     probs= ma3x(1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.126     brouard  9740:     for(i=1;i<=AGESUP;i++)
1.219     brouard  9741:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.218     brouard  9742:                                for(k=1;k<=ncovcombmax;k++)
                   9743:                                        probs[i][j][k]=0.;
1.219     brouard  9744:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   9745:     if (mobilav!=0 ||mobilavproj !=0 ) {
                   9746:       mobaverages= ma3x(1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   9747:                        for(i=1;i<=AGESUP;i++)
                   9748:                                for(j=1;j<=nlstate;j++)
                   9749:                                        for(k=1;k<=ncovcombmax;k++)
                   9750:                                                mobaverages[i][j][k]=0.;
                   9751:       mobaverage=mobaverages;
                   9752:       if (mobilav!=0) {
1.218     brouard  9753:                                if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   9754:                                        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   9755:                                        printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   9756:                                }
1.219     brouard  9757:       }
                   9758:       /* /\* Prevalence for each covariates in probs[age][status][cov] *\/ */
                   9759:       /* prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   9760:       else if (mobilavproj !=0) {
1.218     brouard  9761:                                if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   9762:                                        fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   9763:                                        printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   9764:                                }
1.219     brouard  9765:       }
                   9766:     }/* end if moving average */
                   9767:                
1.126     brouard  9768:     /*---------- Forecasting ------------------*/
                   9769:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   9770:     if(prevfcast==1){
                   9771:       /*    if(stepm ==1){*/
1.201     brouard  9772:       prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
1.126     brouard  9773:     }
1.217     brouard  9774:     if(backcast==1){
1.219     brouard  9775:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   9776:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   9777:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   9778: 
                   9779:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   9780: 
                   9781:       bprlim=matrix(1,nlstate,1,nlstate);
                   9782:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   9783:       fclose(ficresplb);
                   9784: 
1.222     brouard  9785:       hBijx(p, bage, fage, mobaverage);
                   9786:       fclose(ficrespijb);
1.219     brouard  9787:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   9788: 
                   9789:       /* prevbackforecast(fileresu, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, mobilavproj,
                   9790:         bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   9791:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   9792:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   9793:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   9794:     }
1.217     brouard  9795:     
1.186     brouard  9796:  
                   9797:     /* ------ Other prevalence ratios------------ */
1.126     brouard  9798: 
1.215     brouard  9799:     free_ivector(wav,1,imx);
                   9800:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   9801:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   9802:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  9803:                
                   9804:                
1.127     brouard  9805:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  9806:                
1.201     brouard  9807:     strcpy(filerese,"E_");
                   9808:     strcat(filerese,fileresu);
1.126     brouard  9809:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   9810:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   9811:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   9812:     }
1.208     brouard  9813:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   9814:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.219     brouard  9815:                
1.145     brouard  9816:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.219     brouard  9817:       fprintf(ficreseij,"\n#****** ");
                   9818:       for(j=1;j<=cptcoveff;j++) {
1.220     brouard  9819:                                fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.219     brouard  9820:       }
                   9821:       fprintf(ficreseij,"******\n");
                   9822:       
                   9823:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   9824:       oldm=oldms;savm=savms;
                   9825:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
1.127     brouard  9826:       
1.219     brouard  9827:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  9828:     }
                   9829:     fclose(ficreseij);
1.208     brouard  9830:     printf("done evsij\n");fflush(stdout);
                   9831:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.218     brouard  9832:                
1.127     brouard  9833:     /*---------- Health expectancies and variances ------------*/
1.218     brouard  9834:                
                   9835:                
1.201     brouard  9836:     strcpy(filerest,"T_");
                   9837:     strcat(filerest,fileresu);
1.127     brouard  9838:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   9839:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   9840:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   9841:     }
1.208     brouard  9842:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   9843:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.218     brouard  9844:                
1.126     brouard  9845: 
1.201     brouard  9846:     strcpy(fileresstde,"STDE_");
                   9847:     strcat(fileresstde,fileresu);
1.126     brouard  9848:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
                   9849:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   9850:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   9851:     }
1.208     brouard  9852:     printf("  Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   9853:     fprintf(ficlog,"  Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  9854: 
1.201     brouard  9855:     strcpy(filerescve,"CVE_");
                   9856:     strcat(filerescve,fileresu);
1.126     brouard  9857:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
                   9858:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   9859:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   9860:     }
1.208     brouard  9861:     printf("    Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   9862:     fprintf(ficlog,"    Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  9863: 
1.201     brouard  9864:     strcpy(fileresv,"V_");
                   9865:     strcat(fileresv,fileresu);
1.126     brouard  9866:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   9867:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   9868:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   9869:     }
1.208     brouard  9870:     printf("      Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(stdout);
                   9871:     fprintf(ficlog,"      Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  9872: 
1.145     brouard  9873:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   9874:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   9875:           
                   9876:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.208     brouard  9877:       fprintf(ficrest,"\n#****** ");
                   9878:       for(j=1;j<=cptcoveff;j++) 
1.218     brouard  9879:                                fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.208     brouard  9880:       fprintf(ficrest,"******\n");
                   9881:       
                   9882:       fprintf(ficresstdeij,"\n#****** ");
                   9883:       fprintf(ficrescveij,"\n#****** ");
                   9884:       for(j=1;j<=cptcoveff;j++) {
1.218     brouard  9885:                                fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9886:                                fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.208     brouard  9887:       }
                   9888:       fprintf(ficresstdeij,"******\n");
                   9889:       fprintf(ficrescveij,"******\n");
                   9890:       
                   9891:       fprintf(ficresvij,"\n#****** ");
                   9892:       for(j=1;j<=cptcoveff;j++) 
1.218     brouard  9893:                                fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.208     brouard  9894:       fprintf(ficresvij,"******\n");
                   9895:       
                   9896:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   9897:       oldm=oldms;savm=savms;
                   9898:       printf(" cvevsij %d, ",k);
                   9899:       fprintf(ficlog, " cvevsij %d, ",k);
                   9900:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
                   9901:       printf(" end cvevsij \n ");
                   9902:       fprintf(ficlog, " end cvevsij \n ");
                   9903:       
                   9904:       /*
                   9905:        */
                   9906:       /* goto endfree; */
                   9907:       
                   9908:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   9909:       pstamp(ficrest);
                   9910:       
                   9911:       
                   9912:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.220     brouard  9913:                                oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   9914:                                cptcod= 0; /* To be deleted */
                   9915:                                printf("varevsij %d \n",vpopbased);
                   9916:                                fprintf(ficlog, "varevsij %d \n",vpopbased);
                   9917:                                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 */
                   9918:                                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 ");
                   9919:                                if(vpopbased==1)
                   9920:                                        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);
                   9921:                                else
                   9922:                                        fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
                   9923:                                fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
                   9924:                                for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   9925:                                fprintf(ficrest,"\n");
                   9926:                                /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
                   9927:                                epj=vector(1,nlstate+1);
                   9928:                                printf("Computing age specific period (stable) prevalences in each health state \n");
                   9929:                                fprintf(ficlog,"Computing age specific period (stable) prevalences in each health state \n");
                   9930:                                for(age=bage; age <=fage ;age++){
                   9931:                                        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k); /*ZZ Is it the correct prevalim */
                   9932:                                        if (vpopbased==1) {
                   9933:                                                if(mobilav ==0){
                   9934:                                                        for(i=1; i<=nlstate;i++)
                   9935:                                                                prlim[i][i]=probs[(int)age][i][k];
                   9936:                                                }else{ /* mobilav */ 
                   9937:                                                        for(i=1; i<=nlstate;i++)
                   9938:                                                                prlim[i][i]=mobaverage[(int)age][i][k];
                   9939:                                                }
                   9940:                                        }
1.219     brouard  9941:          
1.220     brouard  9942:                                        fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   9943:                                        /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   9944:                                        /* printf(" age %4.0f ",age); */
                   9945:                                        for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   9946:                                                for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   9947:                                                        epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   9948:                                                        /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   9949:                                                        /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   9950:                                                }
                   9951:                                                epj[nlstate+1] +=epj[j];
                   9952:                                        }
                   9953:                                        /* printf(" age %4.0f \n",age); */
1.219     brouard  9954:          
1.220     brouard  9955:                                        for(i=1, vepp=0.;i <=nlstate;i++)
                   9956:                                                for(j=1;j <=nlstate;j++)
                   9957:                                                        vepp += vareij[i][j][(int)age];
                   9958:                                        fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   9959:                                        for(j=1;j <=nlstate;j++){
                   9960:                                                fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   9961:                                        }
                   9962:                                        fprintf(ficrest,"\n");
                   9963:                                }
1.208     brouard  9964:       } /* End vpopbased */
                   9965:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   9966:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   9967:       free_vector(epj,1,nlstate+1);
                   9968:       printf("done \n");fflush(stdout);
                   9969:       fprintf(ficlog,"done\n");fflush(ficlog);
                   9970:       
1.145     brouard  9971:       /*}*/
1.208     brouard  9972:     } /* End k */
1.126     brouard  9973:     free_vector(weight,1,n);
1.145     brouard  9974:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126     brouard  9975:     free_imatrix(s,1,maxwav+1,1,n);
                   9976:     free_matrix(anint,1,maxwav,1,n); 
                   9977:     free_matrix(mint,1,maxwav,1,n);
                   9978:     free_ivector(cod,1,n);
                   9979:     free_ivector(tab,1,NCOVMAX);
                   9980:     fclose(ficresstdeij);
                   9981:     fclose(ficrescveij);
                   9982:     fclose(ficresvij);
                   9983:     fclose(ficrest);
1.208     brouard  9984:     printf("done Health expectancies\n");fflush(stdout);
                   9985:     fprintf(ficlog,"done Health expectancies\n");fflush(ficlog);
1.126     brouard  9986:     fclose(ficpar);
                   9987:   
                   9988:     /*------- Variance of period (stable) prevalence------*/   
                   9989: 
1.201     brouard  9990:     strcpy(fileresvpl,"VPL_");
                   9991:     strcat(fileresvpl,fileresu);
1.126     brouard  9992:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   9993:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   9994:       exit(0);
                   9995:     }
1.208     brouard  9996:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   9997:     fprintf(ficlog, "Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.126     brouard  9998: 
1.145     brouard  9999:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   10000:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   10001:           
                   10002:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   10003:        fprintf(ficresvpl,"\n#****** ");
1.218     brouard  10004:                        for(j=1;j<=cptcoveff;j++) 
                   10005:                                fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   10006:                        fprintf(ficresvpl,"******\n");
                   10007:       
                   10008:                        varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   10009:                        oldm=oldms;savm=savms;
                   10010:                        varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, strstart);
                   10011:                        free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145     brouard  10012:       /*}*/
1.126     brouard  10013:     }
1.218     brouard  10014:                
1.126     brouard  10015:     fclose(ficresvpl);
1.208     brouard  10016:     printf("done variance-covariance of period prevalence\n");fflush(stdout);
                   10017:     fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
1.126     brouard  10018: 
                   10019:     /*---------- End : free ----------------*/
1.219     brouard  10020:     if (mobilav!=0 ||mobilavproj !=0)
                   10021:       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  10022:     free_ma3x(probs,1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  10023:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   10024:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  10025:   }  /* mle==-3 arrives here for freeing */
1.164     brouard  10026:  /* endfree:*/
1.126     brouard  10027:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   10028:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   10029:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.223   ! brouard  10030:     free_ma3x(cotqvar,1,maxwav,1,ntqv,1,n);
        !          10031:     free_ma3x(cotvar,1,maxwav,1,ntv,1,n);
        !          10032:     free_matrix(coqvar,1,maxwav,1,n);
1.126     brouard  10033:     free_matrix(covar,0,NCOVMAX,1,n);
                   10034:     free_matrix(matcov,1,npar,1,npar);
1.203     brouard  10035:     free_matrix(hess,1,npar,1,npar);
1.126     brouard  10036:     /*free_vector(delti,1,npar);*/
                   10037:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   10038:     free_matrix(agev,1,maxwav,1,imx);
                   10039:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   10040: 
1.145     brouard  10041:     free_ivector(ncodemax,1,NCOVMAX);
1.192     brouard  10042:     free_ivector(ncodemaxwundef,1,NCOVMAX);
1.145     brouard  10043:     free_ivector(Tvar,1,NCOVMAX);
                   10044:     free_ivector(Tprod,1,NCOVMAX);
                   10045:     free_ivector(Tvaraff,1,NCOVMAX);
1.220     brouard  10046:     free_ivector(invalidvarcomb,1,ncovcombmax);
1.145     brouard  10047:     free_ivector(Tage,1,NCOVMAX);
1.126     brouard  10048: 
                   10049:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
1.200     brouard  10050:     /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  10051:   fflush(fichtm);
                   10052:   fflush(ficgp);
                   10053:   
                   10054: 
                   10055:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  10056:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   10057:     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  10058:   }else{
                   10059:     printf("End of Imach\n");
                   10060:     fprintf(ficlog,"End of Imach\n");
                   10061:   }
                   10062:   printf("See log file on %s\n",filelog);
                   10063:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  10064:   /*(void) gettimeofday(&end_time,&tzp);*/
                   10065:   rend_time = time(NULL);  
                   10066:   end_time = *localtime(&rend_time);
                   10067:   /* tml = *localtime(&end_time.tm_sec); */
                   10068:   strcpy(strtend,asctime(&end_time));
1.126     brouard  10069:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   10070:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  10071:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126     brouard  10072: 
1.157     brouard  10073:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   10074:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   10075:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  10076:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   10077: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   10078:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   10079:   fclose(fichtm);
                   10080:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   10081:   fclose(fichtmcov);
                   10082:   fclose(ficgp);
                   10083:   fclose(ficlog);
                   10084:   /*------ End -----------*/
                   10085: 
                   10086: 
                   10087:    printf("Before Current directory %s!\n",pathcd);
1.184     brouard  10088: #ifdef WIN32
                   10089:    if (_chdir(pathcd) != 0)
                   10090:           printf("Can't move to directory %s!\n",path);
                   10091:    if(_getcwd(pathcd,MAXLINE) > 0)
                   10092: #else
1.126     brouard  10093:    if(chdir(pathcd) != 0)
1.184     brouard  10094:           printf("Can't move to directory %s!\n", path);
                   10095:    if (getcwd(pathcd, MAXLINE) > 0)
                   10096: #endif 
1.126     brouard  10097:     printf("Current directory %s!\n",pathcd);
                   10098:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   10099:   sprintf(plotcmd,"gnuplot");
1.157     brouard  10100: #ifdef _WIN32
1.126     brouard  10101:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   10102: #endif
                   10103:   if(!stat(plotcmd,&info)){
1.158     brouard  10104:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  10105:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  10106:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  10107:     }else
                   10108:       strcpy(pplotcmd,plotcmd);
1.157     brouard  10109: #ifdef __unix
1.126     brouard  10110:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   10111:     if(!stat(plotcmd,&info)){
1.158     brouard  10112:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  10113:     }else
                   10114:       strcpy(pplotcmd,plotcmd);
                   10115: #endif
                   10116:   }else
                   10117:     strcpy(pplotcmd,plotcmd);
                   10118:   
                   10119:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  10120:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  10121: 
                   10122:   if((outcmd=system(plotcmd)) != 0){
1.158     brouard  10123:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  10124:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  10125:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150     brouard  10126:     if((outcmd=system(plotcmd)) != 0)
1.153     brouard  10127:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126     brouard  10128:   }
1.158     brouard  10129:   printf(" Successful, please wait...");
1.126     brouard  10130:   while (z[0] != 'q') {
                   10131:     /* chdir(path); */
1.154     brouard  10132:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  10133:     scanf("%s",z);
                   10134: /*     if (z[0] == 'c') system("./imach"); */
                   10135:     if (z[0] == 'e') {
1.158     brouard  10136: #ifdef __APPLE__
1.152     brouard  10137:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  10138: #elif __linux
                   10139:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  10140: #else
1.152     brouard  10141:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  10142: #endif
                   10143:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   10144:       system(pplotcmd);
1.126     brouard  10145:     }
                   10146:     else if (z[0] == 'g') system(plotcmd);
                   10147:     else if (z[0] == 'q') exit(0);
                   10148:   }
                   10149:   end:
                   10150:   while (z[0] != 'q') {
1.195     brouard  10151:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  10152:     scanf("%s",z);
                   10153:   }
                   10154: }

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