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

1.216   ! brouard     1: /* $Id: imach.c,v 1.215 2015/12/16 08:52:24 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.216   ! brouard     4:   Revision 1.215  2015/12/16 08:52:24  brouard
        !             5:   Summary: 0.98r4 working
        !             6: 
1.215     brouard     7:   Revision 1.214  2015/12/16 06:57:54  brouard
                      8:   Summary: temporary not working
                      9: 
1.214     brouard    10:   Revision 1.213  2015/12/11 18:22:17  brouard
                     11:   Summary: 0.98r4
                     12: 
1.213     brouard    13:   Revision 1.212  2015/11/21 12:47:24  brouard
                     14:   Summary: minor typo
                     15: 
1.212     brouard    16:   Revision 1.211  2015/11/21 12:41:11  brouard
                     17:   Summary: 0.98r3 with some graph of projected cross-sectional
                     18: 
                     19:   Author: Nicolas Brouard
                     20: 
1.211     brouard    21:   Revision 1.210  2015/11/18 17:41:20  brouard
                     22:   Summary: Start working on projected prevalences
                     23: 
1.210     brouard    24:   Revision 1.209  2015/11/17 22:12:03  brouard
                     25:   Summary: Adding ftolpl parameter
                     26:   Author: N Brouard
                     27: 
                     28:   We had difficulties to get smoothed confidence intervals. It was due
                     29:   to the period prevalence which wasn't computed accurately. The inner
                     30:   parameter ftolpl is now an outer parameter of the .imach parameter
                     31:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                     32:   computation are long.
                     33: 
1.209     brouard    34:   Revision 1.208  2015/11/17 14:31:57  brouard
                     35:   Summary: temporary
                     36: 
1.208     brouard    37:   Revision 1.207  2015/10/27 17:36:57  brouard
                     38:   *** empty log message ***
                     39: 
1.207     brouard    40:   Revision 1.206  2015/10/24 07:14:11  brouard
                     41:   *** empty log message ***
                     42: 
1.206     brouard    43:   Revision 1.205  2015/10/23 15:50:53  brouard
                     44:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                     45: 
1.205     brouard    46:   Revision 1.204  2015/10/01 16:20:26  brouard
                     47:   Summary: Some new graphs of contribution to likelihood
                     48: 
1.204     brouard    49:   Revision 1.203  2015/09/30 17:45:14  brouard
                     50:   Summary: looking at better estimation of the hessian
                     51: 
                     52:   Also a better criteria for convergence to the period prevalence And
                     53:   therefore adding the number of years needed to converge. (The
                     54:   prevalence in any alive state shold sum to one
                     55: 
1.203     brouard    56:   Revision 1.202  2015/09/22 19:45:16  brouard
                     57:   Summary: Adding some overall graph on contribution to likelihood. Might change
                     58: 
1.202     brouard    59:   Revision 1.201  2015/09/15 17:34:58  brouard
                     60:   Summary: 0.98r0
                     61: 
                     62:   - Some new graphs like suvival functions
                     63:   - Some bugs fixed like model=1+age+V2.
                     64: 
1.201     brouard    65:   Revision 1.200  2015/09/09 16:53:55  brouard
                     66:   Summary: Big bug thanks to Flavia
                     67: 
                     68:   Even model=1+age+V2. did not work anymore
                     69: 
1.200     brouard    70:   Revision 1.199  2015/09/07 14:09:23  brouard
                     71:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                     72: 
1.199     brouard    73:   Revision 1.198  2015/09/03 07:14:39  brouard
                     74:   Summary: 0.98q5 Flavia
                     75: 
1.198     brouard    76:   Revision 1.197  2015/09/01 18:24:39  brouard
                     77:   *** empty log message ***
                     78: 
1.197     brouard    79:   Revision 1.196  2015/08/18 23:17:52  brouard
                     80:   Summary: 0.98q5
                     81: 
1.196     brouard    82:   Revision 1.195  2015/08/18 16:28:39  brouard
                     83:   Summary: Adding a hack for testing purpose
                     84: 
                     85:   After reading the title, ftol and model lines, if the comment line has
                     86:   a q, starting with #q, the answer at the end of the run is quit. It
                     87:   permits to run test files in batch with ctest. The former workaround was
                     88:   $ echo q | imach foo.imach
                     89: 
1.195     brouard    90:   Revision 1.194  2015/08/18 13:32:00  brouard
                     91:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                     92: 
1.194     brouard    93:   Revision 1.193  2015/08/04 07:17:42  brouard
                     94:   Summary: 0.98q4
                     95: 
1.193     brouard    96:   Revision 1.192  2015/07/16 16:49:02  brouard
                     97:   Summary: Fixing some outputs
                     98: 
1.192     brouard    99:   Revision 1.191  2015/07/14 10:00:33  brouard
                    100:   Summary: Some fixes
                    101: 
1.191     brouard   102:   Revision 1.190  2015/05/05 08:51:13  brouard
                    103:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    104: 
                    105:   Fix 1+age+.
                    106: 
1.190     brouard   107:   Revision 1.189  2015/04/30 14:45:16  brouard
                    108:   Summary: 0.98q2
                    109: 
1.189     brouard   110:   Revision 1.188  2015/04/30 08:27:53  brouard
                    111:   *** empty log message ***
                    112: 
1.188     brouard   113:   Revision 1.187  2015/04/29 09:11:15  brouard
                    114:   *** empty log message ***
                    115: 
1.187     brouard   116:   Revision 1.186  2015/04/23 12:01:52  brouard
                    117:   Summary: V1*age is working now, version 0.98q1
                    118: 
                    119:   Some codes had been disabled in order to simplify and Vn*age was
                    120:   working in the optimization phase, ie, giving correct MLE parameters,
                    121:   but, as usual, outputs were not correct and program core dumped.
                    122: 
1.186     brouard   123:   Revision 1.185  2015/03/11 13:26:42  brouard
                    124:   Summary: Inclusion of compile and links command line for Intel Compiler
                    125: 
1.185     brouard   126:   Revision 1.184  2015/03/11 11:52:39  brouard
                    127:   Summary: Back from Windows 8. Intel Compiler
                    128: 
1.184     brouard   129:   Revision 1.183  2015/03/10 20:34:32  brouard
                    130:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    131: 
                    132:   We use directest instead of original Powell test; probably no
                    133:   incidence on the results, but better justifications;
                    134:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    135:   wrong results.
                    136: 
1.183     brouard   137:   Revision 1.182  2015/02/12 08:19:57  brouard
                    138:   Summary: Trying to keep directest which seems simpler and more general
                    139:   Author: Nicolas Brouard
                    140: 
1.182     brouard   141:   Revision 1.181  2015/02/11 23:22:24  brouard
                    142:   Summary: Comments on Powell added
                    143: 
                    144:   Author:
                    145: 
1.181     brouard   146:   Revision 1.180  2015/02/11 17:33:45  brouard
                    147:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    148: 
1.180     brouard   149:   Revision 1.179  2015/01/04 09:57:06  brouard
                    150:   Summary: back to OS/X
                    151: 
1.179     brouard   152:   Revision 1.178  2015/01/04 09:35:48  brouard
                    153:   *** empty log message ***
                    154: 
1.178     brouard   155:   Revision 1.177  2015/01/03 18:40:56  brouard
                    156:   Summary: Still testing ilc32 on OSX
                    157: 
1.177     brouard   158:   Revision 1.176  2015/01/03 16:45:04  brouard
                    159:   *** empty log message ***
                    160: 
1.176     brouard   161:   Revision 1.175  2015/01/03 16:33:42  brouard
                    162:   *** empty log message ***
                    163: 
1.175     brouard   164:   Revision 1.174  2015/01/03 16:15:49  brouard
                    165:   Summary: Still in cross-compilation
                    166: 
1.174     brouard   167:   Revision 1.173  2015/01/03 12:06:26  brouard
                    168:   Summary: trying to detect cross-compilation
                    169: 
1.173     brouard   170:   Revision 1.172  2014/12/27 12:07:47  brouard
                    171:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    172: 
1.172     brouard   173:   Revision 1.171  2014/12/23 13:26:59  brouard
                    174:   Summary: Back from Visual C
                    175: 
                    176:   Still problem with utsname.h on Windows
                    177: 
1.171     brouard   178:   Revision 1.170  2014/12/23 11:17:12  brouard
                    179:   Summary: Cleaning some \%% back to %%
                    180: 
                    181:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    182: 
1.170     brouard   183:   Revision 1.169  2014/12/22 23:08:31  brouard
                    184:   Summary: 0.98p
                    185: 
                    186:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    187: 
1.169     brouard   188:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   189:   Summary: update
1.169     brouard   190: 
1.168     brouard   191:   Revision 1.167  2014/12/22 13:50:56  brouard
                    192:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    193: 
                    194:   Testing on Linux 64
                    195: 
1.167     brouard   196:   Revision 1.166  2014/12/22 11:40:47  brouard
                    197:   *** empty log message ***
                    198: 
1.166     brouard   199:   Revision 1.165  2014/12/16 11:20:36  brouard
                    200:   Summary: After compiling on Visual C
                    201: 
                    202:   * imach.c (Module): Merging 1.61 to 1.162
                    203: 
1.165     brouard   204:   Revision 1.164  2014/12/16 10:52:11  brouard
                    205:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    206: 
                    207:   * imach.c (Module): Merging 1.61 to 1.162
                    208: 
1.164     brouard   209:   Revision 1.163  2014/12/16 10:30:11  brouard
                    210:   * imach.c (Module): Merging 1.61 to 1.162
                    211: 
1.163     brouard   212:   Revision 1.162  2014/09/25 11:43:39  brouard
                    213:   Summary: temporary backup 0.99!
                    214: 
1.162     brouard   215:   Revision 1.1  2014/09/16 11:06:58  brouard
                    216:   Summary: With some code (wrong) for nlopt
                    217: 
                    218:   Author:
                    219: 
                    220:   Revision 1.161  2014/09/15 20:41:41  brouard
                    221:   Summary: Problem with macro SQR on Intel compiler
                    222: 
1.161     brouard   223:   Revision 1.160  2014/09/02 09:24:05  brouard
                    224:   *** empty log message ***
                    225: 
1.160     brouard   226:   Revision 1.159  2014/09/01 10:34:10  brouard
                    227:   Summary: WIN32
                    228:   Author: Brouard
                    229: 
1.159     brouard   230:   Revision 1.158  2014/08/27 17:11:51  brouard
                    231:   *** empty log message ***
                    232: 
1.158     brouard   233:   Revision 1.157  2014/08/27 16:26:55  brouard
                    234:   Summary: Preparing windows Visual studio version
                    235:   Author: Brouard
                    236: 
                    237:   In order to compile on Visual studio, time.h is now correct and time_t
                    238:   and tm struct should be used. difftime should be used but sometimes I
                    239:   just make the differences in raw time format (time(&now).
                    240:   Trying to suppress #ifdef LINUX
                    241:   Add xdg-open for __linux in order to open default browser.
                    242: 
1.157     brouard   243:   Revision 1.156  2014/08/25 20:10:10  brouard
                    244:   *** empty log message ***
                    245: 
1.156     brouard   246:   Revision 1.155  2014/08/25 18:32:34  brouard
                    247:   Summary: New compile, minor changes
                    248:   Author: Brouard
                    249: 
1.155     brouard   250:   Revision 1.154  2014/06/20 17:32:08  brouard
                    251:   Summary: Outputs now all graphs of convergence to period prevalence
                    252: 
1.154     brouard   253:   Revision 1.153  2014/06/20 16:45:46  brouard
                    254:   Summary: If 3 live state, convergence to period prevalence on same graph
                    255:   Author: Brouard
                    256: 
1.153     brouard   257:   Revision 1.152  2014/06/18 17:54:09  brouard
                    258:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    259: 
1.152     brouard   260:   Revision 1.151  2014/06/18 16:43:30  brouard
                    261:   *** empty log message ***
                    262: 
1.151     brouard   263:   Revision 1.150  2014/06/18 16:42:35  brouard
                    264:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    265:   Author: brouard
                    266: 
1.150     brouard   267:   Revision 1.149  2014/06/18 15:51:14  brouard
                    268:   Summary: Some fixes in parameter files errors
                    269:   Author: Nicolas Brouard
                    270: 
1.149     brouard   271:   Revision 1.148  2014/06/17 17:38:48  brouard
                    272:   Summary: Nothing new
                    273:   Author: Brouard
                    274: 
                    275:   Just a new packaging for OS/X version 0.98nS
                    276: 
1.148     brouard   277:   Revision 1.147  2014/06/16 10:33:11  brouard
                    278:   *** empty log message ***
                    279: 
1.147     brouard   280:   Revision 1.146  2014/06/16 10:20:28  brouard
                    281:   Summary: Merge
                    282:   Author: Brouard
                    283: 
                    284:   Merge, before building revised version.
                    285: 
1.146     brouard   286:   Revision 1.145  2014/06/10 21:23:15  brouard
                    287:   Summary: Debugging with valgrind
                    288:   Author: Nicolas Brouard
                    289: 
                    290:   Lot of changes in order to output the results with some covariates
                    291:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    292:   improve the code.
                    293:   No more memory valgrind error but a lot has to be done in order to
                    294:   continue the work of splitting the code into subroutines.
                    295:   Also, decodemodel has been improved. Tricode is still not
                    296:   optimal. nbcode should be improved. Documentation has been added in
                    297:   the source code.
                    298: 
1.144     brouard   299:   Revision 1.143  2014/01/26 09:45:38  brouard
                    300:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    301: 
                    302:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    303:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    304: 
1.143     brouard   305:   Revision 1.142  2014/01/26 03:57:36  brouard
                    306:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    307: 
                    308:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    309: 
1.142     brouard   310:   Revision 1.141  2014/01/26 02:42:01  brouard
                    311:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    312: 
1.141     brouard   313:   Revision 1.140  2011/09/02 10:37:54  brouard
                    314:   Summary: times.h is ok with mingw32 now.
                    315: 
1.140     brouard   316:   Revision 1.139  2010/06/14 07:50:17  brouard
                    317:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    318:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    319: 
1.139     brouard   320:   Revision 1.138  2010/04/30 18:19:40  brouard
                    321:   *** empty log message ***
                    322: 
1.138     brouard   323:   Revision 1.137  2010/04/29 18:11:38  brouard
                    324:   (Module): Checking covariates for more complex models
                    325:   than V1+V2. A lot of change to be done. Unstable.
                    326: 
1.137     brouard   327:   Revision 1.136  2010/04/26 20:30:53  brouard
                    328:   (Module): merging some libgsl code. Fixing computation
                    329:   of likelione (using inter/intrapolation if mle = 0) in order to
                    330:   get same likelihood as if mle=1.
                    331:   Some cleaning of code and comments added.
                    332: 
1.136     brouard   333:   Revision 1.135  2009/10/29 15:33:14  brouard
                    334:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    335: 
1.135     brouard   336:   Revision 1.134  2009/10/29 13:18:53  brouard
                    337:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    338: 
1.134     brouard   339:   Revision 1.133  2009/07/06 10:21:25  brouard
                    340:   just nforces
                    341: 
1.133     brouard   342:   Revision 1.132  2009/07/06 08:22:05  brouard
                    343:   Many tings
                    344: 
1.132     brouard   345:   Revision 1.131  2009/06/20 16:22:47  brouard
                    346:   Some dimensions resccaled
                    347: 
1.131     brouard   348:   Revision 1.130  2009/05/26 06:44:34  brouard
                    349:   (Module): Max Covariate is now set to 20 instead of 8. A
                    350:   lot of cleaning with variables initialized to 0. Trying to make
                    351:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    352: 
1.130     brouard   353:   Revision 1.129  2007/08/31 13:49:27  lievre
                    354:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    355: 
1.129     lievre    356:   Revision 1.128  2006/06/30 13:02:05  brouard
                    357:   (Module): Clarifications on computing e.j
                    358: 
1.128     brouard   359:   Revision 1.127  2006/04/28 18:11:50  brouard
                    360:   (Module): Yes the sum of survivors was wrong since
                    361:   imach-114 because nhstepm was no more computed in the age
                    362:   loop. Now we define nhstepma in the age loop.
                    363:   (Module): In order to speed up (in case of numerous covariates) we
                    364:   compute health expectancies (without variances) in a first step
                    365:   and then all the health expectancies with variances or standard
                    366:   deviation (needs data from the Hessian matrices) which slows the
                    367:   computation.
                    368:   In the future we should be able to stop the program is only health
                    369:   expectancies and graph are needed without standard deviations.
                    370: 
1.127     brouard   371:   Revision 1.126  2006/04/28 17:23:28  brouard
                    372:   (Module): Yes the sum of survivors was wrong since
                    373:   imach-114 because nhstepm was no more computed in the age
                    374:   loop. Now we define nhstepma in the age loop.
                    375:   Version 0.98h
                    376: 
1.126     brouard   377:   Revision 1.125  2006/04/04 15:20:31  lievre
                    378:   Errors in calculation of health expectancies. Age was not initialized.
                    379:   Forecasting file added.
                    380: 
                    381:   Revision 1.124  2006/03/22 17:13:53  lievre
                    382:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    383:   The log-likelihood is printed in the log file
                    384: 
                    385:   Revision 1.123  2006/03/20 10:52:43  brouard
                    386:   * imach.c (Module): <title> changed, corresponds to .htm file
                    387:   name. <head> headers where missing.
                    388: 
                    389:   * imach.c (Module): Weights can have a decimal point as for
                    390:   English (a comma might work with a correct LC_NUMERIC environment,
                    391:   otherwise the weight is truncated).
                    392:   Modification of warning when the covariates values are not 0 or
                    393:   1.
                    394:   Version 0.98g
                    395: 
                    396:   Revision 1.122  2006/03/20 09:45:41  brouard
                    397:   (Module): Weights can have a decimal point as for
                    398:   English (a comma might work with a correct LC_NUMERIC environment,
                    399:   otherwise the weight is truncated).
                    400:   Modification of warning when the covariates values are not 0 or
                    401:   1.
                    402:   Version 0.98g
                    403: 
                    404:   Revision 1.121  2006/03/16 17:45:01  lievre
                    405:   * imach.c (Module): Comments concerning covariates added
                    406: 
                    407:   * imach.c (Module): refinements in the computation of lli if
                    408:   status=-2 in order to have more reliable computation if stepm is
                    409:   not 1 month. Version 0.98f
                    410: 
                    411:   Revision 1.120  2006/03/16 15:10:38  lievre
                    412:   (Module): refinements in the computation of lli if
                    413:   status=-2 in order to have more reliable computation if stepm is
                    414:   not 1 month. Version 0.98f
                    415: 
                    416:   Revision 1.119  2006/03/15 17:42:26  brouard
                    417:   (Module): Bug if status = -2, the loglikelihood was
                    418:   computed as likelihood omitting the logarithm. Version O.98e
                    419: 
                    420:   Revision 1.118  2006/03/14 18:20:07  brouard
                    421:   (Module): varevsij Comments added explaining the second
                    422:   table of variances if popbased=1 .
                    423:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    424:   (Module): Function pstamp added
                    425:   (Module): Version 0.98d
                    426: 
                    427:   Revision 1.117  2006/03/14 17:16:22  brouard
                    428:   (Module): varevsij Comments added explaining the second
                    429:   table of variances if popbased=1 .
                    430:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    431:   (Module): Function pstamp added
                    432:   (Module): Version 0.98d
                    433: 
                    434:   Revision 1.116  2006/03/06 10:29:27  brouard
                    435:   (Module): Variance-covariance wrong links and
                    436:   varian-covariance of ej. is needed (Saito).
                    437: 
                    438:   Revision 1.115  2006/02/27 12:17:45  brouard
                    439:   (Module): One freematrix added in mlikeli! 0.98c
                    440: 
                    441:   Revision 1.114  2006/02/26 12:57:58  brouard
                    442:   (Module): Some improvements in processing parameter
                    443:   filename with strsep.
                    444: 
                    445:   Revision 1.113  2006/02/24 14:20:24  brouard
                    446:   (Module): Memory leaks checks with valgrind and:
                    447:   datafile was not closed, some imatrix were not freed and on matrix
                    448:   allocation too.
                    449: 
                    450:   Revision 1.112  2006/01/30 09:55:26  brouard
                    451:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    452: 
                    453:   Revision 1.111  2006/01/25 20:38:18  brouard
                    454:   (Module): Lots of cleaning and bugs added (Gompertz)
                    455:   (Module): Comments can be added in data file. Missing date values
                    456:   can be a simple dot '.'.
                    457: 
                    458:   Revision 1.110  2006/01/25 00:51:50  brouard
                    459:   (Module): Lots of cleaning and bugs added (Gompertz)
                    460: 
                    461:   Revision 1.109  2006/01/24 19:37:15  brouard
                    462:   (Module): Comments (lines starting with a #) are allowed in data.
                    463: 
                    464:   Revision 1.108  2006/01/19 18:05:42  lievre
                    465:   Gnuplot problem appeared...
                    466:   To be fixed
                    467: 
                    468:   Revision 1.107  2006/01/19 16:20:37  brouard
                    469:   Test existence of gnuplot in imach path
                    470: 
                    471:   Revision 1.106  2006/01/19 13:24:36  brouard
                    472:   Some cleaning and links added in html output
                    473: 
                    474:   Revision 1.105  2006/01/05 20:23:19  lievre
                    475:   *** empty log message ***
                    476: 
                    477:   Revision 1.104  2005/09/30 16:11:43  lievre
                    478:   (Module): sump fixed, loop imx fixed, and simplifications.
                    479:   (Module): If the status is missing at the last wave but we know
                    480:   that the person is alive, then we can code his/her status as -2
                    481:   (instead of missing=-1 in earlier versions) and his/her
                    482:   contributions to the likelihood is 1 - Prob of dying from last
                    483:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    484:   the healthy state at last known wave). Version is 0.98
                    485: 
                    486:   Revision 1.103  2005/09/30 15:54:49  lievre
                    487:   (Module): sump fixed, loop imx fixed, and simplifications.
                    488: 
                    489:   Revision 1.102  2004/09/15 17:31:30  brouard
                    490:   Add the possibility to read data file including tab characters.
                    491: 
                    492:   Revision 1.101  2004/09/15 10:38:38  brouard
                    493:   Fix on curr_time
                    494: 
                    495:   Revision 1.100  2004/07/12 18:29:06  brouard
                    496:   Add version for Mac OS X. Just define UNIX in Makefile
                    497: 
                    498:   Revision 1.99  2004/06/05 08:57:40  brouard
                    499:   *** empty log message ***
                    500: 
                    501:   Revision 1.98  2004/05/16 15:05:56  brouard
                    502:   New version 0.97 . First attempt to estimate force of mortality
                    503:   directly from the data i.e. without the need of knowing the health
                    504:   state at each age, but using a Gompertz model: log u =a + b*age .
                    505:   This is the basic analysis of mortality and should be done before any
                    506:   other analysis, in order to test if the mortality estimated from the
                    507:   cross-longitudinal survey is different from the mortality estimated
                    508:   from other sources like vital statistic data.
                    509: 
                    510:   The same imach parameter file can be used but the option for mle should be -3.
                    511: 
1.133     brouard   512:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   513:   former routines in order to include the new code within the former code.
                    514: 
                    515:   The output is very simple: only an estimate of the intercept and of
                    516:   the slope with 95% confident intervals.
                    517: 
                    518:   Current limitations:
                    519:   A) Even if you enter covariates, i.e. with the
                    520:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    521:   B) There is no computation of Life Expectancy nor Life Table.
                    522: 
                    523:   Revision 1.97  2004/02/20 13:25:42  lievre
                    524:   Version 0.96d. Population forecasting command line is (temporarily)
                    525:   suppressed.
                    526: 
                    527:   Revision 1.96  2003/07/15 15:38:55  brouard
                    528:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    529:   rewritten within the same printf. Workaround: many printfs.
                    530: 
                    531:   Revision 1.95  2003/07/08 07:54:34  brouard
                    532:   * imach.c (Repository):
                    533:   (Repository): Using imachwizard code to output a more meaningful covariance
                    534:   matrix (cov(a12,c31) instead of numbers.
                    535: 
                    536:   Revision 1.94  2003/06/27 13:00:02  brouard
                    537:   Just cleaning
                    538: 
                    539:   Revision 1.93  2003/06/25 16:33:55  brouard
                    540:   (Module): On windows (cygwin) function asctime_r doesn't
                    541:   exist so I changed back to asctime which exists.
                    542:   (Module): Version 0.96b
                    543: 
                    544:   Revision 1.92  2003/06/25 16:30:45  brouard
                    545:   (Module): On windows (cygwin) function asctime_r doesn't
                    546:   exist so I changed back to asctime which exists.
                    547: 
                    548:   Revision 1.91  2003/06/25 15:30:29  brouard
                    549:   * imach.c (Repository): Duplicated warning errors corrected.
                    550:   (Repository): Elapsed time after each iteration is now output. It
                    551:   helps to forecast when convergence will be reached. Elapsed time
                    552:   is stamped in powell.  We created a new html file for the graphs
                    553:   concerning matrix of covariance. It has extension -cov.htm.
                    554: 
                    555:   Revision 1.90  2003/06/24 12:34:15  brouard
                    556:   (Module): Some bugs corrected for windows. Also, when
                    557:   mle=-1 a template is output in file "or"mypar.txt with the design
                    558:   of the covariance matrix to be input.
                    559: 
                    560:   Revision 1.89  2003/06/24 12:30:52  brouard
                    561:   (Module): Some bugs corrected for windows. Also, when
                    562:   mle=-1 a template is output in file "or"mypar.txt with the design
                    563:   of the covariance matrix to be input.
                    564: 
                    565:   Revision 1.88  2003/06/23 17:54:56  brouard
                    566:   * 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.
                    567: 
                    568:   Revision 1.87  2003/06/18 12:26:01  brouard
                    569:   Version 0.96
                    570: 
                    571:   Revision 1.86  2003/06/17 20:04:08  brouard
                    572:   (Module): Change position of html and gnuplot routines and added
                    573:   routine fileappend.
                    574: 
                    575:   Revision 1.85  2003/06/17 13:12:43  brouard
                    576:   * imach.c (Repository): Check when date of death was earlier that
                    577:   current date of interview. It may happen when the death was just
                    578:   prior to the death. In this case, dh was negative and likelihood
                    579:   was wrong (infinity). We still send an "Error" but patch by
                    580:   assuming that the date of death was just one stepm after the
                    581:   interview.
                    582:   (Repository): Because some people have very long ID (first column)
                    583:   we changed int to long in num[] and we added a new lvector for
                    584:   memory allocation. But we also truncated to 8 characters (left
                    585:   truncation)
                    586:   (Repository): No more line truncation errors.
                    587: 
                    588:   Revision 1.84  2003/06/13 21:44:43  brouard
                    589:   * imach.c (Repository): Replace "freqsummary" at a correct
                    590:   place. It differs from routine "prevalence" which may be called
                    591:   many times. Probs is memory consuming and must be used with
                    592:   parcimony.
                    593:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    594: 
                    595:   Revision 1.83  2003/06/10 13:39:11  lievre
                    596:   *** empty log message ***
                    597: 
                    598:   Revision 1.82  2003/06/05 15:57:20  brouard
                    599:   Add log in  imach.c and  fullversion number is now printed.
                    600: 
                    601: */
                    602: /*
                    603:    Interpolated Markov Chain
                    604: 
                    605:   Short summary of the programme:
                    606:   
                    607:   This program computes Healthy Life Expectancies from
                    608:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
                    609:   first survey ("cross") where individuals from different ages are
                    610:   interviewed on their health status or degree of disability (in the
                    611:   case of a health survey which is our main interest) -2- at least a
                    612:   second wave of interviews ("longitudinal") which measure each change
                    613:   (if any) in individual health status.  Health expectancies are
                    614:   computed from the time spent in each health state according to a
                    615:   model. More health states you consider, more time is necessary to reach the
                    616:   Maximum Likelihood of the parameters involved in the model.  The
                    617:   simplest model is the multinomial logistic model where pij is the
                    618:   probability to be observed in state j at the second wave
                    619:   conditional to be observed in state i at the first wave. Therefore
                    620:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
                    621:   'age' is age and 'sex' is a covariate. If you want to have a more
                    622:   complex model than "constant and age", you should modify the program
                    623:   where the markup *Covariates have to be included here again* invites
                    624:   you to do it.  More covariates you add, slower the
                    625:   convergence.
                    626: 
                    627:   The advantage of this computer programme, compared to a simple
                    628:   multinomial logistic model, is clear when the delay between waves is not
                    629:   identical for each individual. Also, if a individual missed an
                    630:   intermediate interview, the information is lost, but taken into
                    631:   account using an interpolation or extrapolation.  
                    632: 
                    633:   hPijx is the probability to be observed in state i at age x+h
                    634:   conditional to the observed state i at age x. The delay 'h' can be
                    635:   split into an exact number (nh*stepm) of unobserved intermediate
                    636:   states. This elementary transition (by month, quarter,
                    637:   semester or year) is modelled as a multinomial logistic.  The hPx
                    638:   matrix is simply the matrix product of nh*stepm elementary matrices
                    639:   and the contribution of each individual to the likelihood is simply
                    640:   hPijx.
                    641: 
                    642:   Also this programme outputs the covariance matrix of the parameters but also
                    643:   of the life expectancies. It also computes the period (stable) prevalence. 
                    644:   
1.133     brouard   645:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    646:            Institut national d'études démographiques, Paris.
1.126     brouard   647:   This software have been partly granted by Euro-REVES, a concerted action
                    648:   from the European Union.
                    649:   It is copyrighted identically to a GNU software product, ie programme and
                    650:   software can be distributed freely for non commercial use. Latest version
                    651:   can be accessed at http://euroreves.ined.fr/imach .
                    652: 
                    653:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    654:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    655:   
                    656:   **********************************************************************/
                    657: /*
                    658:   main
                    659:   read parameterfile
                    660:   read datafile
                    661:   concatwav
                    662:   freqsummary
                    663:   if (mle >= 1)
                    664:     mlikeli
                    665:   print results files
                    666:   if mle==1 
                    667:      computes hessian
                    668:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    669:       begin-prev-date,...
                    670:   open gnuplot file
                    671:   open html file
1.145     brouard   672:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    673:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    674:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    675:     freexexit2 possible for memory heap.
                    676: 
                    677:   h Pij x                         | pij_nom  ficrestpij
                    678:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    679:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    680:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    681: 
                    682:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    683:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    684:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    685:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    686:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    687: 
1.126     brouard   688:   forecasting if prevfcast==1 prevforecast call prevalence()
                    689:   health expectancies
                    690:   Variance-covariance of DFLE
                    691:   prevalence()
                    692:    movingaverage()
                    693:   varevsij() 
                    694:   if popbased==1 varevsij(,popbased)
                    695:   total life expectancies
                    696:   Variance of period (stable) prevalence
                    697:  end
                    698: */
                    699: 
1.187     brouard   700: /* #define DEBUG */
                    701: /* #define DEBUGBRENT */
1.203     brouard   702: /* #define DEBUGLINMIN */
                    703: /* #define DEBUGHESS */
                    704: #define DEBUGHESSIJ
                    705: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan)*\/ */
1.165     brouard   706: #define POWELL /* Instead of NLOPT */
1.192     brouard   707: #define POWELLF1F3 /* Skip test */
1.186     brouard   708: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                    709: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard   710: 
                    711: #include <math.h>
                    712: #include <stdio.h>
                    713: #include <stdlib.h>
                    714: #include <string.h>
1.159     brouard   715: 
                    716: #ifdef _WIN32
                    717: #include <io.h>
1.172     brouard   718: #include <windows.h>
                    719: #include <tchar.h>
1.159     brouard   720: #else
1.126     brouard   721: #include <unistd.h>
1.159     brouard   722: #endif
1.126     brouard   723: 
                    724: #include <limits.h>
                    725: #include <sys/types.h>
1.171     brouard   726: 
                    727: #if defined(__GNUC__)
                    728: #include <sys/utsname.h> /* Doesn't work on Windows */
                    729: #endif
                    730: 
1.126     brouard   731: #include <sys/stat.h>
                    732: #include <errno.h>
1.159     brouard   733: /* extern int errno; */
1.126     brouard   734: 
1.157     brouard   735: /* #ifdef LINUX */
                    736: /* #include <time.h> */
                    737: /* #include "timeval.h" */
                    738: /* #else */
                    739: /* #include <sys/time.h> */
                    740: /* #endif */
                    741: 
1.126     brouard   742: #include <time.h>
                    743: 
1.136     brouard   744: #ifdef GSL
                    745: #include <gsl/gsl_errno.h>
                    746: #include <gsl/gsl_multimin.h>
                    747: #endif
                    748: 
1.167     brouard   749: 
1.162     brouard   750: #ifdef NLOPT
                    751: #include <nlopt.h>
                    752: typedef struct {
                    753:   double (* function)(double [] );
                    754: } myfunc_data ;
                    755: #endif
                    756: 
1.126     brouard   757: /* #include <libintl.h> */
                    758: /* #define _(String) gettext (String) */
                    759: 
1.141     brouard   760: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   761: 
                    762: #define GNUPLOTPROGRAM "gnuplot"
                    763: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    764: #define FILENAMELENGTH 132
                    765: 
                    766: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    767: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    768: 
1.144     brouard   769: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    770: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   771: 
                    772: #define NINTERVMAX 8
1.144     brouard   773: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    774: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    775: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197     brouard   776: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard   777: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                    778: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.126     brouard   779: #define MAXN 20000
1.144     brouard   780: #define YEARM 12. /**< Number of months per year */
1.126     brouard   781: #define AGESUP 130
                    782: #define AGEBASE 40
1.194     brouard   783: #define AGEOVERFLOW 1.e20
1.164     brouard   784: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard   785: #ifdef _WIN32
                    786: #define DIRSEPARATOR '\\'
                    787: #define CHARSEPARATOR "\\"
                    788: #define ODIRSEPARATOR '/'
                    789: #else
1.126     brouard   790: #define DIRSEPARATOR '/'
                    791: #define CHARSEPARATOR "/"
                    792: #define ODIRSEPARATOR '\\'
                    793: #endif
                    794: 
1.216   ! brouard   795: /* $Id: imach.c,v 1.215 2015/12/16 08:52:24 brouard Exp $ */
1.126     brouard   796: /* $State: Exp $ */
1.196     brouard   797: #include "version.h"
                    798: char version[]=__IMACH_VERSION__;
1.204     brouard   799: 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.216   ! brouard   800: char fullversion[]="$Revision: 1.215 $ $Date: 2015/12/16 08:52:24 $"; 
1.126     brouard   801: char strstart[80];
                    802: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   803: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard   804: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard   805: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    806: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    807: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
                    808: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
                    809: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    810: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    811: int cptcoveff=0; /* Total number of covariates to vary for printing results */
                    812: int cptcov=0; /* Working variable */
1.126     brouard   813: int npar=NPARMAX;
                    814: int nlstate=2; /* Number of live states */
                    815: int ndeath=1; /* Number of dead states */
1.130     brouard   816: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126     brouard   817: int popbased=0;
                    818: 
                    819: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard   820: int maxwav=0; /* Maxim number of waves */
                    821: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    822: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    823: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard   824:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard   825: int mle=1, weightopt=0;
1.126     brouard   826: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    827: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    828: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    829:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard   830: int countcallfunc=0;  /* Count the number of calls to func */
1.130     brouard   831: double jmean=1; /* Mean space between 2 waves */
1.145     brouard   832: double **matprod2(); /* test */
1.126     brouard   833: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    834: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136     brouard   835: /*FILE *fic ; */ /* Used in readdata only */
1.214     brouard   836: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126     brouard   837: FILE *ficlog, *ficrespow;
1.130     brouard   838: int globpr=0; /* Global variable for printing or not */
1.126     brouard   839: double fretone; /* Only one call to likelihood */
1.130     brouard   840: long ipmx=0; /* Number of contributions */
1.126     brouard   841: double sw; /* Sum of weights */
                    842: char filerespow[FILENAMELENGTH];
                    843: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                    844: FILE *ficresilk;
                    845: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                    846: FILE *ficresprobmorprev;
                    847: FILE *fichtm, *fichtmcov; /* Html File */
                    848: FILE *ficreseij;
                    849: char filerese[FILENAMELENGTH];
                    850: FILE *ficresstdeij;
                    851: char fileresstde[FILENAMELENGTH];
                    852: FILE *ficrescveij;
                    853: char filerescve[FILENAMELENGTH];
                    854: FILE  *ficresvij;
                    855: char fileresv[FILENAMELENGTH];
                    856: FILE  *ficresvpl;
                    857: char fileresvpl[FILENAMELENGTH];
                    858: char title[MAXLINE];
                    859: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
                    860: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                    861: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                    862: char command[FILENAMELENGTH];
                    863: int  outcmd=0;
                    864: 
                    865: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard   866: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard   867: char filelog[FILENAMELENGTH]; /* Log file */
                    868: char filerest[FILENAMELENGTH];
                    869: char fileregp[FILENAMELENGTH];
                    870: char popfile[FILENAMELENGTH];
                    871: 
                    872: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                    873: 
1.157     brouard   874: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                    875: /* struct timezone tzp; */
                    876: /* extern int gettimeofday(); */
                    877: struct tm tml, *gmtime(), *localtime();
                    878: 
                    879: extern time_t time();
                    880: 
                    881: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                    882: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                    883: struct tm tm;
                    884: 
1.126     brouard   885: char strcurr[80], strfor[80];
                    886: 
                    887: char *endptr;
                    888: long lval;
                    889: double dval;
                    890: 
                    891: #define NR_END 1
                    892: #define FREE_ARG char*
                    893: #define FTOL 1.0e-10
                    894: 
                    895: #define NRANSI 
                    896: #define ITMAX 200 
                    897: 
                    898: #define TOL 2.0e-4 
                    899: 
                    900: #define CGOLD 0.3819660 
                    901: #define ZEPS 1.0e-10 
                    902: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                    903: 
                    904: #define GOLD 1.618034 
                    905: #define GLIMIT 100.0 
                    906: #define TINY 1.0e-20 
                    907: 
                    908: static double maxarg1,maxarg2;
                    909: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                    910: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                    911:   
                    912: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                    913: #define rint(a) floor(a+0.5)
1.166     brouard   914: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard   915: #define mytinydouble 1.0e-16
1.166     brouard   916: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                    917: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                    918: /* static double dsqrarg; */
                    919: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard   920: static double sqrarg;
                    921: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                    922: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                    923: int agegomp= AGEGOMP;
                    924: 
                    925: int imx; 
                    926: int stepm=1;
                    927: /* Stepm, step in month: minimum step interpolation*/
                    928: 
                    929: int estepm;
                    930: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                    931: 
                    932: int m,nb;
                    933: long *num;
1.197     brouard   934: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard   935: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                    936:                   covariate for which somebody answered excluding 
                    937:                   undefined. Usually 2: 0 and 1. */
                    938: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                    939:                             covariate for which somebody answered including 
                    940:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard   941: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
                    942: double **pmmij, ***probs;
                    943: double *ageexmed,*agecens;
                    944: double dateintmean=0;
                    945: 
                    946: double *weight;
                    947: int **s; /* Status */
1.141     brouard   948: double *agedc;
1.145     brouard   949: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard   950:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard   951:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.141     brouard   952: double  idx; 
                    953: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.197     brouard   954: int *Tage;
1.145     brouard   955: int *Ndum; /** Freq of modality (tricode */
1.200     brouard   956: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.141     brouard   957: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126     brouard   958: double *lsurv, *lpop, *tpop;
                    959: 
1.143     brouard   960: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                    961: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard   962: 
                    963: /**************** split *************************/
                    964: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                    965: {
                    966:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                    967:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                    968:   */ 
                    969:   char *ss;                            /* pointer */
1.186     brouard   970:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard   971: 
                    972:   l1 = strlen(path );                  /* length of path */
                    973:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                    974:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                    975:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                    976:     strcpy( name, path );              /* we got the fullname name because no directory */
                    977:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                    978:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                    979:     /* get current working directory */
                    980:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard   981: #ifdef WIN32
                    982:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                    983: #else
                    984:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                    985: #endif
1.126     brouard   986:       return( GLOCK_ERROR_GETCWD );
                    987:     }
                    988:     /* got dirc from getcwd*/
                    989:     printf(" DIRC = %s \n",dirc);
1.205     brouard   990:   } else {                             /* strip directory from path */
1.126     brouard   991:     ss++;                              /* after this, the filename */
                    992:     l2 = strlen( ss );                 /* length of filename */
                    993:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                    994:     strcpy( name, ss );                /* save file name */
                    995:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard   996:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard   997:     printf(" DIRC2 = %s \n",dirc);
                    998:   }
                    999:   /* We add a separator at the end of dirc if not exists */
                   1000:   l1 = strlen( dirc );                 /* length of directory */
                   1001:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1002:     dirc[l1] =  DIRSEPARATOR;
                   1003:     dirc[l1+1] = 0; 
                   1004:     printf(" DIRC3 = %s \n",dirc);
                   1005:   }
                   1006:   ss = strrchr( name, '.' );           /* find last / */
                   1007:   if (ss >0){
                   1008:     ss++;
                   1009:     strcpy(ext,ss);                    /* save extension */
                   1010:     l1= strlen( name);
                   1011:     l2= strlen(ss)+1;
                   1012:     strncpy( finame, name, l1-l2);
                   1013:     finame[l1-l2]= 0;
                   1014:   }
                   1015: 
                   1016:   return( 0 );                         /* we're done */
                   1017: }
                   1018: 
                   1019: 
                   1020: /******************************************/
                   1021: 
                   1022: void replace_back_to_slash(char *s, char*t)
                   1023: {
                   1024:   int i;
                   1025:   int lg=0;
                   1026:   i=0;
                   1027:   lg=strlen(t);
                   1028:   for(i=0; i<= lg; i++) {
                   1029:     (s[i] = t[i]);
                   1030:     if (t[i]== '\\') s[i]='/';
                   1031:   }
                   1032: }
                   1033: 
1.132     brouard  1034: char *trimbb(char *out, char *in)
1.137     brouard  1035: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1036:   char *s;
                   1037:   s=out;
                   1038:   while (*in != '\0'){
1.137     brouard  1039:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1040:       in++;
                   1041:     }
                   1042:     *out++ = *in++;
                   1043:   }
                   1044:   *out='\0';
                   1045:   return s;
                   1046: }
                   1047: 
1.187     brouard  1048: /* char *substrchaine(char *out, char *in, char *chain) */
                   1049: /* { */
                   1050: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1051: /*   char *s, *t; */
                   1052: /*   t=in;s=out; */
                   1053: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1054: /*     *out++ = *in++; */
                   1055: /*   } */
                   1056: 
                   1057: /*   /\* *in matches *chain *\/ */
                   1058: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1059: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1060: /*   } */
                   1061: /*   in--; chain--; */
                   1062: /*   while ( (*in != '\0')){ */
                   1063: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1064: /*     *out++ = *in++; */
                   1065: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1066: /*   } */
                   1067: /*   *out='\0'; */
                   1068: /*   out=s; */
                   1069: /*   return out; */
                   1070: /* } */
                   1071: char *substrchaine(char *out, char *in, char *chain)
                   1072: {
                   1073:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1074:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1075: 
                   1076:   char *strloc;
                   1077: 
                   1078:   strcpy (out, in); 
                   1079:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1080:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1081:   if(strloc != NULL){ 
                   1082:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1083:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1084:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1085:   }
                   1086:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1087:   return out;
                   1088: }
                   1089: 
                   1090: 
1.145     brouard  1091: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1092: {
1.187     brouard  1093:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1094:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187     brouard  1095:      gives blocc="abcdef" and alocc="ghi2j".
1.145     brouard  1096:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1097:   */
1.160     brouard  1098:   char *s, *t;
1.145     brouard  1099:   t=in;s=in;
                   1100:   while ((*in != occ) && (*in != '\0')){
                   1101:     *alocc++ = *in++;
                   1102:   }
                   1103:   if( *in == occ){
                   1104:     *(alocc)='\0';
                   1105:     s=++in;
                   1106:   }
                   1107:  
                   1108:   if (s == t) {/* occ not found */
                   1109:     *(alocc-(in-s))='\0';
                   1110:     in=s;
                   1111:   }
                   1112:   while ( *in != '\0'){
                   1113:     *blocc++ = *in++;
                   1114:   }
                   1115: 
                   1116:   *blocc='\0';
                   1117:   return t;
                   1118: }
1.137     brouard  1119: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1120: {
1.187     brouard  1121:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1122:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1123:      gives blocc="abcdef2ghi" and alocc="j".
                   1124:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1125:   */
                   1126:   char *s, *t;
                   1127:   t=in;s=in;
                   1128:   while (*in != '\0'){
                   1129:     while( *in == occ){
                   1130:       *blocc++ = *in++;
                   1131:       s=in;
                   1132:     }
                   1133:     *blocc++ = *in++;
                   1134:   }
                   1135:   if (s == t) /* occ not found */
                   1136:     *(blocc-(in-s))='\0';
                   1137:   else
                   1138:     *(blocc-(in-s)-1)='\0';
                   1139:   in=s;
                   1140:   while ( *in != '\0'){
                   1141:     *alocc++ = *in++;
                   1142:   }
                   1143: 
                   1144:   *alocc='\0';
                   1145:   return s;
                   1146: }
                   1147: 
1.126     brouard  1148: int nbocc(char *s, char occ)
                   1149: {
                   1150:   int i,j=0;
                   1151:   int lg=20;
                   1152:   i=0;
                   1153:   lg=strlen(s);
                   1154:   for(i=0; i<= lg; i++) {
                   1155:   if  (s[i] == occ ) j++;
                   1156:   }
                   1157:   return j;
                   1158: }
                   1159: 
1.137     brouard  1160: /* void cutv(char *u,char *v, char*t, char occ) */
                   1161: /* { */
                   1162: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1163: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1164: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1165: /*   int i,lg,j,p=0; */
                   1166: /*   i=0; */
                   1167: /*   lg=strlen(t); */
                   1168: /*   for(j=0; j<=lg-1; j++) { */
                   1169: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1170: /*   } */
1.126     brouard  1171: 
1.137     brouard  1172: /*   for(j=0; j<p; j++) { */
                   1173: /*     (u[j] = t[j]); */
                   1174: /*   } */
                   1175: /*      u[p]='\0'; */
1.126     brouard  1176: 
1.137     brouard  1177: /*    for(j=0; j<= lg; j++) { */
                   1178: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1179: /*   } */
                   1180: /* } */
1.126     brouard  1181: 
1.160     brouard  1182: #ifdef _WIN32
                   1183: char * strsep(char **pp, const char *delim)
                   1184: {
                   1185:   char *p, *q;
                   1186:          
                   1187:   if ((p = *pp) == NULL)
                   1188:     return 0;
                   1189:   if ((q = strpbrk (p, delim)) != NULL)
                   1190:   {
                   1191:     *pp = q + 1;
                   1192:     *q = '\0';
                   1193:   }
                   1194:   else
                   1195:     *pp = 0;
                   1196:   return p;
                   1197: }
                   1198: #endif
                   1199: 
1.126     brouard  1200: /********************** nrerror ********************/
                   1201: 
                   1202: void nrerror(char error_text[])
                   1203: {
                   1204:   fprintf(stderr,"ERREUR ...\n");
                   1205:   fprintf(stderr,"%s\n",error_text);
                   1206:   exit(EXIT_FAILURE);
                   1207: }
                   1208: /*********************** vector *******************/
                   1209: double *vector(int nl, int nh)
                   1210: {
                   1211:   double *v;
                   1212:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1213:   if (!v) nrerror("allocation failure in vector");
                   1214:   return v-nl+NR_END;
                   1215: }
                   1216: 
                   1217: /************************ free vector ******************/
                   1218: void free_vector(double*v, int nl, int nh)
                   1219: {
                   1220:   free((FREE_ARG)(v+nl-NR_END));
                   1221: }
                   1222: 
                   1223: /************************ivector *******************************/
                   1224: int *ivector(long nl,long nh)
                   1225: {
                   1226:   int *v;
                   1227:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1228:   if (!v) nrerror("allocation failure in ivector");
                   1229:   return v-nl+NR_END;
                   1230: }
                   1231: 
                   1232: /******************free ivector **************************/
                   1233: void free_ivector(int *v, long nl, long nh)
                   1234: {
                   1235:   free((FREE_ARG)(v+nl-NR_END));
                   1236: }
                   1237: 
                   1238: /************************lvector *******************************/
                   1239: long *lvector(long nl,long nh)
                   1240: {
                   1241:   long *v;
                   1242:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1243:   if (!v) nrerror("allocation failure in ivector");
                   1244:   return v-nl+NR_END;
                   1245: }
                   1246: 
                   1247: /******************free lvector **************************/
                   1248: void free_lvector(long *v, long nl, long nh)
                   1249: {
                   1250:   free((FREE_ARG)(v+nl-NR_END));
                   1251: }
                   1252: 
                   1253: /******************* imatrix *******************************/
                   1254: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1255:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1256: { 
                   1257:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1258:   int **m; 
                   1259:   
                   1260:   /* allocate pointers to rows */ 
                   1261:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1262:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1263:   m += NR_END; 
                   1264:   m -= nrl; 
                   1265:   
                   1266:   
                   1267:   /* allocate rows and set pointers to them */ 
                   1268:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1269:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1270:   m[nrl] += NR_END; 
                   1271:   m[nrl] -= ncl; 
                   1272:   
                   1273:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1274:   
                   1275:   /* return pointer to array of pointers to rows */ 
                   1276:   return m; 
                   1277: } 
                   1278: 
                   1279: /****************** free_imatrix *************************/
                   1280: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1281:       int **m;
                   1282:       long nch,ncl,nrh,nrl; 
                   1283:      /* free an int matrix allocated by imatrix() */ 
                   1284: { 
                   1285:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1286:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1287: } 
                   1288: 
                   1289: /******************* matrix *******************************/
                   1290: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1291: {
                   1292:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1293:   double **m;
                   1294: 
                   1295:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1296:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1297:   m += NR_END;
                   1298:   m -= nrl;
                   1299: 
                   1300:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1301:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1302:   m[nrl] += NR_END;
                   1303:   m[nrl] -= ncl;
                   1304: 
                   1305:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1306:   return m;
1.145     brouard  1307:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1308: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1309: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1310:    */
                   1311: }
                   1312: 
                   1313: /*************************free matrix ************************/
                   1314: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1315: {
                   1316:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1317:   free((FREE_ARG)(m+nrl-NR_END));
                   1318: }
                   1319: 
                   1320: /******************* ma3x *******************************/
                   1321: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1322: {
                   1323:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1324:   double ***m;
                   1325: 
                   1326:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1327:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1328:   m += NR_END;
                   1329:   m -= nrl;
                   1330: 
                   1331:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1332:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1333:   m[nrl] += NR_END;
                   1334:   m[nrl] -= ncl;
                   1335: 
                   1336:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1337: 
                   1338:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1339:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1340:   m[nrl][ncl] += NR_END;
                   1341:   m[nrl][ncl] -= nll;
                   1342:   for (j=ncl+1; j<=nch; j++) 
                   1343:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1344:   
                   1345:   for (i=nrl+1; i<=nrh; i++) {
                   1346:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1347:     for (j=ncl+1; j<=nch; j++) 
                   1348:       m[i][j]=m[i][j-1]+nlay;
                   1349:   }
                   1350:   return m; 
                   1351:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1352:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1353:   */
                   1354: }
                   1355: 
                   1356: /*************************free ma3x ************************/
                   1357: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1358: {
                   1359:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1360:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1361:   free((FREE_ARG)(m+nrl-NR_END));
                   1362: }
                   1363: 
                   1364: /*************** function subdirf ***********/
                   1365: char *subdirf(char fileres[])
                   1366: {
                   1367:   /* Caution optionfilefiname is hidden */
                   1368:   strcpy(tmpout,optionfilefiname);
                   1369:   strcat(tmpout,"/"); /* Add to the right */
                   1370:   strcat(tmpout,fileres);
                   1371:   return tmpout;
                   1372: }
                   1373: 
                   1374: /*************** function subdirf2 ***********/
                   1375: char *subdirf2(char fileres[], char *preop)
                   1376: {
                   1377:   
                   1378:   /* Caution optionfilefiname is hidden */
                   1379:   strcpy(tmpout,optionfilefiname);
                   1380:   strcat(tmpout,"/");
                   1381:   strcat(tmpout,preop);
                   1382:   strcat(tmpout,fileres);
                   1383:   return tmpout;
                   1384: }
                   1385: 
                   1386: /*************** function subdirf3 ***********/
                   1387: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1388: {
                   1389:   
                   1390:   /* Caution optionfilefiname is hidden */
                   1391:   strcpy(tmpout,optionfilefiname);
                   1392:   strcat(tmpout,"/");
                   1393:   strcat(tmpout,preop);
                   1394:   strcat(tmpout,preop2);
                   1395:   strcat(tmpout,fileres);
                   1396:   return tmpout;
                   1397: }
1.213     brouard  1398:  
                   1399: /*************** function subdirfext ***********/
                   1400: char *subdirfext(char fileres[], char *preop, char *postop)
                   1401: {
                   1402:   
                   1403:   strcpy(tmpout,preop);
                   1404:   strcat(tmpout,fileres);
                   1405:   strcat(tmpout,postop);
                   1406:   return tmpout;
                   1407: }
1.126     brouard  1408: 
1.213     brouard  1409: /*************** function subdirfext3 ***********/
                   1410: char *subdirfext3(char fileres[], char *preop, char *postop)
                   1411: {
                   1412:   
                   1413:   /* Caution optionfilefiname is hidden */
                   1414:   strcpy(tmpout,optionfilefiname);
                   1415:   strcat(tmpout,"/");
                   1416:   strcat(tmpout,preop);
                   1417:   strcat(tmpout,fileres);
                   1418:   strcat(tmpout,postop);
                   1419:   return tmpout;
                   1420: }
                   1421:  
1.162     brouard  1422: char *asc_diff_time(long time_sec, char ascdiff[])
                   1423: {
                   1424:   long sec_left, days, hours, minutes;
                   1425:   days = (time_sec) / (60*60*24);
                   1426:   sec_left = (time_sec) % (60*60*24);
                   1427:   hours = (sec_left) / (60*60) ;
                   1428:   sec_left = (sec_left) %(60*60);
                   1429:   minutes = (sec_left) /60;
                   1430:   sec_left = (sec_left) % (60);
                   1431:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1432:   return ascdiff;
                   1433: }
                   1434: 
1.126     brouard  1435: /***************** f1dim *************************/
                   1436: extern int ncom; 
                   1437: extern double *pcom,*xicom;
                   1438: extern double (*nrfunc)(double []); 
                   1439:  
                   1440: double f1dim(double x) 
                   1441: { 
                   1442:   int j; 
                   1443:   double f;
                   1444:   double *xt; 
                   1445:  
                   1446:   xt=vector(1,ncom); 
                   1447:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1448:   f=(*nrfunc)(xt); 
                   1449:   free_vector(xt,1,ncom); 
                   1450:   return f; 
                   1451: } 
                   1452: 
                   1453: /*****************brent *************************/
                   1454: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1455: {
                   1456:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1457:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1458:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1459:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1460:    * returned function value. 
                   1461:   */
1.126     brouard  1462:   int iter; 
                   1463:   double a,b,d,etemp;
1.159     brouard  1464:   double fu=0,fv,fw,fx;
1.164     brouard  1465:   double ftemp=0.;
1.126     brouard  1466:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1467:   double e=0.0; 
                   1468:  
                   1469:   a=(ax < cx ? ax : cx); 
                   1470:   b=(ax > cx ? ax : cx); 
                   1471:   x=w=v=bx; 
                   1472:   fw=fv=fx=(*f)(x); 
                   1473:   for (iter=1;iter<=ITMAX;iter++) { 
                   1474:     xm=0.5*(a+b); 
                   1475:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1476:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1477:     printf(".");fflush(stdout);
                   1478:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1479: #ifdef DEBUGBRENT
1.126     brouard  1480:     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);
                   1481:     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);
                   1482:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1483: #endif
                   1484:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1485:       *xmin=x; 
                   1486:       return fx; 
                   1487:     } 
                   1488:     ftemp=fu;
                   1489:     if (fabs(e) > tol1) { 
                   1490:       r=(x-w)*(fx-fv); 
                   1491:       q=(x-v)*(fx-fw); 
                   1492:       p=(x-v)*q-(x-w)*r; 
                   1493:       q=2.0*(q-r); 
                   1494:       if (q > 0.0) p = -p; 
                   1495:       q=fabs(q); 
                   1496:       etemp=e; 
                   1497:       e=d; 
                   1498:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
                   1499:        d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1500:       else { 
                   1501:        d=p/q; 
                   1502:        u=x+d; 
                   1503:        if (u-a < tol2 || b-u < tol2) 
                   1504:          d=SIGN(tol1,xm-x); 
                   1505:       } 
                   1506:     } else { 
                   1507:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1508:     } 
                   1509:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1510:     fu=(*f)(u); 
                   1511:     if (fu <= fx) { 
                   1512:       if (u >= x) a=x; else b=x; 
                   1513:       SHFT(v,w,x,u) 
1.183     brouard  1514:       SHFT(fv,fw,fx,fu) 
                   1515:     } else { 
                   1516:       if (u < x) a=u; else b=u; 
                   1517:       if (fu <= fw || w == x) { 
                   1518:        v=w; 
                   1519:        w=u; 
                   1520:        fv=fw; 
                   1521:        fw=fu; 
                   1522:       } else if (fu <= fv || v == x || v == w) { 
                   1523:        v=u; 
                   1524:        fv=fu; 
                   1525:       } 
                   1526:     } 
1.126     brouard  1527:   } 
                   1528:   nrerror("Too many iterations in brent"); 
                   1529:   *xmin=x; 
                   1530:   return fx; 
                   1531: } 
                   1532: 
                   1533: /****************** mnbrak ***********************/
                   1534: 
                   1535: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1536:            double (*func)(double)) 
1.183     brouard  1537: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1538: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1539: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1540: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1541:    */
1.126     brouard  1542:   double ulim,u,r,q, dum;
                   1543:   double fu; 
1.187     brouard  1544: 
                   1545:   double scale=10.;
                   1546:   int iterscale=0;
                   1547: 
                   1548:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   1549:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   1550: 
                   1551: 
                   1552:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   1553:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   1554:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   1555:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   1556:   /* } */
                   1557: 
1.126     brouard  1558:   if (*fb > *fa) { 
                   1559:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  1560:     SHFT(dum,*fb,*fa,dum) 
                   1561:   } 
1.126     brouard  1562:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1563:   *fc=(*func)(*cx); 
1.183     brouard  1564: #ifdef DEBUG
                   1565:   printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1566:   fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1567: #endif
                   1568:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1.126     brouard  1569:     r=(*bx-*ax)*(*fb-*fc); 
                   1570:     q=(*bx-*cx)*(*fb-*fa); 
                   1571:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  1572:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1573:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   1574:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  1575:       fu=(*func)(u); 
1.163     brouard  1576: #ifdef DEBUG
                   1577:       /* f(x)=A(x-u)**2+f(u) */
                   1578:       double A, fparabu; 
                   1579:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1580:       fparabu= *fa - A*(*ax-u)*(*ax-u);
                   1581:       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);
                   1582:       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  1583:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   1584:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   1585:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   1586:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  1587: #endif 
1.184     brouard  1588: #ifdef MNBRAKORIGINAL
1.183     brouard  1589: #else
1.191     brouard  1590: /*       if (fu > *fc) { */
                   1591: /* #ifdef DEBUG */
                   1592: /*       printf("mnbrak4  fu > fc \n"); */
                   1593: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   1594: /* #endif */
                   1595: /*     /\* 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 *\\/  *\/ */
                   1596: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   1597: /*     dum=u; /\* Shifting c and u *\/ */
                   1598: /*     u = *cx; */
                   1599: /*     *cx = dum; */
                   1600: /*     dum = fu; */
                   1601: /*     fu = *fc; */
                   1602: /*     *fc =dum; */
                   1603: /*       } else { /\* end *\/ */
                   1604: /* #ifdef DEBUG */
                   1605: /*       printf("mnbrak3  fu < fc \n"); */
                   1606: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   1607: /* #endif */
                   1608: /*     dum=u; /\* Shifting c and u *\/ */
                   1609: /*     u = *cx; */
                   1610: /*     *cx = dum; */
                   1611: /*     dum = fu; */
                   1612: /*     fu = *fc; */
                   1613: /*     *fc =dum; */
                   1614: /*       } */
1.183     brouard  1615: #ifdef DEBUG
1.191     brouard  1616:       printf("mnbrak34  fu < or >= fc \n");
                   1617:       fprintf(ficlog, "mnbrak34 fu < fc\n");
1.183     brouard  1618: #endif
1.191     brouard  1619:       dum=u; /* Shifting c and u */
                   1620:       u = *cx;
                   1621:       *cx = dum;
                   1622:       dum = fu;
                   1623:       fu = *fc;
                   1624:       *fc =dum;
1.183     brouard  1625: #endif
1.162     brouard  1626:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  1627: #ifdef DEBUG
                   1628:       printf("mnbrak2  u after c but before ulim\n");
                   1629:       fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
                   1630: #endif
1.126     brouard  1631:       fu=(*func)(u); 
                   1632:       if (fu < *fc) { 
1.183     brouard  1633: #ifdef DEBUG
                   1634:       printf("mnbrak2  u after c but before ulim AND fu < fc\n");
                   1635:       fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
                   1636: #endif
1.126     brouard  1637:        SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
1.183     brouard  1638:        SHFT(*fb,*fc,fu,(*func)(u)) 
                   1639:       } 
1.162     brouard  1640:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  1641: #ifdef DEBUG
                   1642:       printf("mnbrak2  u outside ulim (verifying that ulim is beyond c)\n");
                   1643:       fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
                   1644: #endif
1.126     brouard  1645:       u=ulim; 
                   1646:       fu=(*func)(u); 
1.183     brouard  1647:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   1648: #ifdef DEBUG
                   1649:       printf("mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1650:       fprintf(ficlog, "mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1651: #endif
1.126     brouard  1652:       u=(*cx)+GOLD*(*cx-*bx); 
                   1653:       fu=(*func)(u); 
1.183     brouard  1654:     } /* end tests */
1.126     brouard  1655:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  1656:     SHFT(*fa,*fb,*fc,fu) 
                   1657: #ifdef DEBUG
                   1658:       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);
                   1659:       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);
                   1660: #endif
                   1661:   } /* 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  1662: } 
                   1663: 
                   1664: /*************** linmin ************************/
1.162     brouard  1665: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   1666: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   1667: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   1668: the value of func at the returned location p . This is actually all accomplished by calling the
                   1669: routines mnbrak and brent .*/
1.126     brouard  1670: int ncom; 
                   1671: double *pcom,*xicom;
                   1672: double (*nrfunc)(double []); 
                   1673:  
                   1674: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
                   1675: { 
                   1676:   double brent(double ax, double bx, double cx, 
                   1677:               double (*f)(double), double tol, double *xmin); 
                   1678:   double f1dim(double x); 
                   1679:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1680:              double *fc, double (*func)(double)); 
                   1681:   int j; 
                   1682:   double xx,xmin,bx,ax; 
                   1683:   double fx,fb,fa;
1.187     brouard  1684: 
1.203     brouard  1685: #ifdef LINMINORIGINAL
                   1686: #else
                   1687:   double scale=10., axs, xxs; /* Scale added for infinity */
                   1688: #endif
                   1689:   
1.126     brouard  1690:   ncom=n; 
                   1691:   pcom=vector(1,n); 
                   1692:   xicom=vector(1,n); 
                   1693:   nrfunc=func; 
                   1694:   for (j=1;j<=n;j++) { 
                   1695:     pcom[j]=p[j]; 
1.202     brouard  1696:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  1697:   } 
1.187     brouard  1698: 
1.203     brouard  1699: #ifdef LINMINORIGINAL
                   1700:   xx=1.;
                   1701: #else
                   1702:   axs=0.0;
                   1703:   xxs=1.;
                   1704:   do{
                   1705:     xx= xxs;
                   1706: #endif
1.187     brouard  1707:     ax=0.;
                   1708:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   1709:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   1710:     /* 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))   */
                   1711:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   1712:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   1713:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   1714:     /* 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  1715: #ifdef LINMINORIGINAL
                   1716: #else
                   1717:     if (fx != fx){
                   1718:        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   1719:        printf("|");
                   1720:        fprintf(ficlog,"|");
                   1721: #ifdef DEBUGLINMIN
                   1722:        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);
                   1723: #endif
                   1724:     }
                   1725:   }while(fx != fx);
                   1726: #endif
                   1727:   
1.191     brouard  1728: #ifdef DEBUGLINMIN
                   1729:   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  1730:   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  1731: #endif
1.187     brouard  1732:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   1733:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   1734:   /* fmin = f(p[j] + xmin * xi[j]) */
                   1735:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   1736:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  1737: #ifdef DEBUG
                   1738:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1739:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1740: #endif
1.191     brouard  1741: #ifdef DEBUGLINMIN
                   1742:   printf("linmin end ");
1.202     brouard  1743:   fprintf(ficlog,"linmin end ");
1.191     brouard  1744: #endif
1.126     brouard  1745:   for (j=1;j<=n;j++) { 
1.203     brouard  1746: #ifdef LINMINORIGINAL
                   1747:     xi[j] *= xmin; 
                   1748: #else
                   1749: #ifdef DEBUGLINMIN
                   1750:     if(xxs <1.0)
                   1751:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   1752: #endif
                   1753:     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) */
                   1754: #ifdef DEBUGLINMIN
                   1755:     if(xxs <1.0)
                   1756:       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 );
                   1757: #endif
                   1758: #endif
1.187     brouard  1759:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  1760:   } 
1.191     brouard  1761: #ifdef DEBUGLINMIN
1.203     brouard  1762:   printf("\n");
1.191     brouard  1763:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  1764:   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  1765:   for (j=1;j<=n;j++) { 
1.202     brouard  1766:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   1767:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   1768:     if(j % ncovmodel == 0){
1.191     brouard  1769:       printf("\n");
1.202     brouard  1770:       fprintf(ficlog,"\n");
                   1771:     }
1.191     brouard  1772:   }
1.203     brouard  1773: #else
1.191     brouard  1774: #endif
1.126     brouard  1775:   free_vector(xicom,1,n); 
                   1776:   free_vector(pcom,1,n); 
                   1777: } 
                   1778: 
                   1779: 
                   1780: /*************** powell ************************/
1.162     brouard  1781: /*
                   1782: Minimization of a function func of n variables. Input consists of an initial starting point
                   1783: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   1784: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   1785: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   1786: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   1787: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   1788:  */
1.126     brouard  1789: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   1790:            double (*func)(double [])) 
                   1791: { 
                   1792:   void linmin(double p[], double xi[], int n, double *fret, 
                   1793:              double (*func)(double [])); 
                   1794:   int i,ibig,j; 
                   1795:   double del,t,*pt,*ptt,*xit;
1.181     brouard  1796:   double directest;
1.126     brouard  1797:   double fp,fptt;
                   1798:   double *xits;
                   1799:   int niterf, itmp;
                   1800: 
                   1801:   pt=vector(1,n); 
                   1802:   ptt=vector(1,n); 
                   1803:   xit=vector(1,n); 
                   1804:   xits=vector(1,n); 
                   1805:   *fret=(*func)(p); 
                   1806:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  1807:   rcurr_time = time(NULL);  
1.126     brouard  1808:   for (*iter=1;;++(*iter)) { 
1.187     brouard  1809:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  1810:     ibig=0; 
                   1811:     del=0.0; 
1.157     brouard  1812:     rlast_time=rcurr_time;
                   1813:     /* (void) gettimeofday(&curr_time,&tzp); */
                   1814:     rcurr_time = time(NULL);  
                   1815:     curr_time = *localtime(&rcurr_time);
                   1816:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   1817:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   1818: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  1819:     for (i=1;i<=n;i++) {
1.126     brouard  1820:       printf(" %d %.12f",i, p[i]);
                   1821:       fprintf(ficlog," %d %.12lf",i, p[i]);
                   1822:       fprintf(ficrespow," %.12lf", p[i]);
                   1823:     }
                   1824:     printf("\n");
                   1825:     fprintf(ficlog,"\n");
                   1826:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   1827:     if(*iter <=3){
1.157     brouard  1828:       tml = *localtime(&rcurr_time);
                   1829:       strcpy(strcurr,asctime(&tml));
                   1830:       rforecast_time=rcurr_time; 
1.126     brouard  1831:       itmp = strlen(strcurr);
                   1832:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
                   1833:        strcurr[itmp-1]='\0';
1.162     brouard  1834:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  1835:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  1836:       for(niterf=10;niterf<=30;niterf+=10){
1.157     brouard  1837:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   1838:        forecast_time = *localtime(&rforecast_time);
                   1839:        strcpy(strfor,asctime(&forecast_time));
1.126     brouard  1840:        itmp = strlen(strfor);
                   1841:        if(strfor[itmp-1]=='\n')
                   1842:        strfor[itmp-1]='\0';
1.157     brouard  1843:        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);
                   1844:        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  1845:       }
                   1846:     }
1.187     brouard  1847:     for (i=1;i<=n;i++) { /* For each direction i */
                   1848:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  1849:       fptt=(*fret); 
                   1850: #ifdef DEBUG
1.203     brouard  1851:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   1852:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  1853: #endif
1.203     brouard  1854:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  1855:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.188     brouard  1856:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   1857:                                    /* Outputs are fret(new point p) p is updated and xit rescaled */
                   1858:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
                   1859:        /* because that direction will be replaced unless the gain del is small */
                   1860:        /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   1861:        /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   1862:        /* with the new direction. */
1.126     brouard  1863:        del=fabs(fptt-(*fret)); 
                   1864:        ibig=i; 
                   1865:       } 
                   1866: #ifdef DEBUG
                   1867:       printf("%d %.12e",i,(*fret));
                   1868:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   1869:       for (j=1;j<=n;j++) {
                   1870:        xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   1871:        printf(" x(%d)=%.12e",j,xit[j]);
                   1872:        fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
                   1873:       }
                   1874:       for(j=1;j<=n;j++) {
1.162     brouard  1875:        printf(" p(%d)=%.12e",j,p[j]);
                   1876:        fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  1877:       }
                   1878:       printf("\n");
                   1879:       fprintf(ficlog,"\n");
                   1880: #endif
1.187     brouard  1881:     } /* end loop on each direction i */
                   1882:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  1883:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  1884:     /* New value of last point Pn is not computed, P(n-1) */
1.182     brouard  1885:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1.188     brouard  1886:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   1887:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   1888:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   1889:       /* decreased of more than 3.84  */
                   1890:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   1891:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   1892:       /* By adding 10 parameters more the gain should be 18.31 */
                   1893: 
                   1894:       /* Starting the program with initial values given by a former maximization will simply change */
                   1895:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   1896:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   1897:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  1898: #ifdef DEBUG
                   1899:       int k[2],l;
                   1900:       k[0]=1;
                   1901:       k[1]=-1;
                   1902:       printf("Max: %.12e",(*func)(p));
                   1903:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   1904:       for (j=1;j<=n;j++) {
                   1905:        printf(" %.12e",p[j]);
                   1906:        fprintf(ficlog," %.12e",p[j]);
                   1907:       }
                   1908:       printf("\n");
                   1909:       fprintf(ficlog,"\n");
                   1910:       for(l=0;l<=1;l++) {
                   1911:        for (j=1;j<=n;j++) {
                   1912:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   1913:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1914:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1915:        }
                   1916:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1917:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1918:       }
                   1919: #endif
                   1920: 
                   1921: 
                   1922:       free_vector(xit,1,n); 
                   1923:       free_vector(xits,1,n); 
                   1924:       free_vector(ptt,1,n); 
                   1925:       free_vector(pt,1,n); 
                   1926:       return; 
1.192     brouard  1927:     } /* enough precision */ 
1.126     brouard  1928:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  1929:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  1930:       ptt[j]=2.0*p[j]-pt[j]; 
                   1931:       xit[j]=p[j]-pt[j]; 
                   1932:       pt[j]=p[j]; 
                   1933:     } 
1.181     brouard  1934:     fptt=(*func)(ptt); /* f_3 */
1.192     brouard  1935: #ifdef POWELLF1F3
                   1936: #else
1.161     brouard  1937:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  1938: #endif
1.162     brouard  1939:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  1940:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  1941:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   1942:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   1943:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.181     brouard  1944:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1.161     brouard  1945:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.183     brouard  1946: #ifdef NRCORIGINAL
                   1947:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   1948: #else
                   1949:       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  1950:       t= t- del*SQR(fp-fptt);
1.183     brouard  1951: #endif
1.202     brouard  1952:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  1953: #ifdef DEBUG
1.181     brouard  1954:       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);
                   1955:       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  1956:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1957:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1958:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1959:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1960:       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);
                   1961:       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);
                   1962: #endif
1.183     brouard  1963: #ifdef POWELLORIGINAL
                   1964:       if (t < 0.0) { /* Then we use it for new direction */
                   1965: #else
1.182     brouard  1966:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.202     brouard  1967:        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  1968:         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  1969:         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  1970:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   1971:       } 
1.181     brouard  1972:       if (directest < 0.0) { /* Then we use it for new direction */
                   1973: #endif
1.191     brouard  1974: #ifdef DEBUGLINMIN
                   1975:        printf("Before linmin in direction P%d-P0\n",n);
                   1976:        for (j=1;j<=n;j++) { 
1.202     brouard  1977:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   1978:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   1979:          if(j % ncovmodel == 0){
1.191     brouard  1980:            printf("\n");
1.202     brouard  1981:            fprintf(ficlog,"\n");
                   1982:          }
1.191     brouard  1983:        }
                   1984: #endif
1.187     brouard  1985:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.191     brouard  1986: #ifdef DEBUGLINMIN
                   1987:        for (j=1;j<=n;j++) { 
                   1988:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1.202     brouard  1989:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   1990:          if(j % ncovmodel == 0){
1.191     brouard  1991:            printf("\n");
1.202     brouard  1992:            fprintf(ficlog,"\n");
                   1993:          }
1.191     brouard  1994:        }
                   1995: #endif
1.126     brouard  1996:        for (j=1;j<=n;j++) { 
1.181     brouard  1997:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   1998:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
1.126     brouard  1999:        }
1.181     brouard  2000:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2001:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161     brouard  2002: 
1.126     brouard  2003: #ifdef DEBUG
1.164     brouard  2004:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2005:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126     brouard  2006:        for(j=1;j<=n;j++){
                   2007:          printf(" %.12e",xit[j]);
                   2008:          fprintf(ficlog," %.12e",xit[j]);
                   2009:        }
                   2010:        printf("\n");
                   2011:        fprintf(ficlog,"\n");
                   2012: #endif
1.192     brouard  2013:       } /* end of t or directest negative */
                   2014: #ifdef POWELLF1F3
                   2015: #else
1.162     brouard  2016:     } /* end if (fptt < fp)  */
1.192     brouard  2017: #endif
                   2018:   } /* loop iteration */ 
1.126     brouard  2019: } 
                   2020: 
                   2021: /**** Prevalence limit (stable or period prevalence)  ****************/
                   2022: 
1.203     brouard  2023: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij)
1.126     brouard  2024: {
                   2025:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1.203     brouard  2026:      matrix by transitions matrix until convergence is reached with precision ftolpl */
1.206     brouard  2027:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2028:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2029:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2030:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2031:   /* Initial matrix pimij */
                   2032:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2033:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2034:   /*  0,                   0                  , 1} */
                   2035:   /*
                   2036:    * and after some iteration: */
                   2037:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2038:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2039:   /*  0,                   0                  , 1} */
                   2040:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2041:   /* {0.51571254859325999, 0.4842874514067399, */
                   2042:   /*  0.51326036147820708, 0.48673963852179264} */
                   2043:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2044: 
1.126     brouard  2045:   int i, ii,j,k;
1.209     brouard  2046:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2047:   /* double **matprod2(); */ /* test */
1.131     brouard  2048:   double **out, cov[NCOVMAX+1], **pmij();
1.126     brouard  2049:   double **newm;
1.209     brouard  2050:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2051:   int ncvloop=0;
1.169     brouard  2052:   
1.209     brouard  2053:   min=vector(1,nlstate);
                   2054:   max=vector(1,nlstate);
                   2055:   meandiff=vector(1,nlstate);
                   2056: 
1.126     brouard  2057:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2058:     for (j=1;j<=nlstate+ndeath;j++){
                   2059:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2060:     }
1.169     brouard  2061:   
                   2062:   cov[1]=1.;
                   2063:   
                   2064:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2065:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2066:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2067:     ncvloop++;
1.126     brouard  2068:     newm=savm;
                   2069:     /* Covariates have to be included here again */
1.138     brouard  2070:     cov[2]=agefin;
1.187     brouard  2071:     if(nagesqr==1)
                   2072:       cov[3]= agefin*agefin;;
1.138     brouard  2073:     for (k=1; k<=cptcovn;k++) {
1.200     brouard  2074:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
                   2075:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
1.198     brouard  2076:       /* 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  2077:     }
1.186     brouard  2078:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  2079:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
                   2080:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
1.186     brouard  2081:     for (k=1; k<=cptcovprod;k++) /* Useless */
1.200     brouard  2082:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   2083:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
1.138     brouard  2084:     
                   2085:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2086:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2087:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2088:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2089:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142     brouard  2090:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2091:     
1.126     brouard  2092:     savm=oldm;
                   2093:     oldm=newm;
1.209     brouard  2094: 
                   2095:     for(j=1; j<=nlstate; j++){
                   2096:       max[j]=0.;
                   2097:       min[j]=1.;
                   2098:     }
                   2099:     for(i=1;i<=nlstate;i++){
                   2100:       sumnew=0;
                   2101:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2102:       for(j=1; j<=nlstate; j++){ 
                   2103:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2104:        max[j]=FMAX(max[j],prlim[i][j]);
                   2105:        min[j]=FMIN(min[j],prlim[i][j]);
                   2106:       }
                   2107:     }
                   2108: 
1.126     brouard  2109:     maxmax=0.;
1.209     brouard  2110:     for(j=1; j<=nlstate; j++){
                   2111:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2112:       maxmax=FMAX(maxmax,meandiff[j]);
                   2113:       /* 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  2114:     } /* j loop */
1.203     brouard  2115:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2116:     /* 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  2117:     if(maxmax < ftolpl){
1.209     brouard  2118:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2119:       free_vector(min,1,nlstate);
                   2120:       free_vector(max,1,nlstate);
                   2121:       free_vector(meandiff,1,nlstate);
1.126     brouard  2122:       return prlim;
                   2123:     }
1.169     brouard  2124:   } /* age loop */
1.208     brouard  2125:     /* After some age loop it doesn't converge */
1.209     brouard  2126:   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  2127: 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  2128:   /* 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); */
                   2129:   free_vector(min,1,nlstate);
                   2130:   free_vector(max,1,nlstate);
                   2131:   free_vector(meandiff,1,nlstate);
1.208     brouard  2132:   
1.169     brouard  2133:   return prlim; /* should not reach here */
1.126     brouard  2134: }
                   2135: 
                   2136: /*************** transition probabilities ***************/ 
                   2137: 
                   2138: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   2139: {
1.138     brouard  2140:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2141:      computes the probability to be observed in state j being in state i by appying the
                   2142:      model to the ncovmodel covariates (including constant and age).
                   2143:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2144:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2145:      ncth covariate in the global vector x is given by the formula:
                   2146:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2147:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2148:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2149:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2150:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2151:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2152:   */
                   2153:   double s1, lnpijopii;
1.126     brouard  2154:   /*double t34;*/
1.164     brouard  2155:   int i,j, nc, ii, jj;
1.126     brouard  2156: 
                   2157:     for(i=1; i<= nlstate; i++){
                   2158:       for(j=1; j<i;j++){
1.138     brouard  2159:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2160:          /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2161:          lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2162: /*      printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  2163:        }
1.138     brouard  2164:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2165: /*     printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  2166:       }
                   2167:       for(j=i+1; j<=nlstate+ndeath;j++){
1.138     brouard  2168:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2169:          /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2170:          lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2171: /*       printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126     brouard  2172:        }
1.138     brouard  2173:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126     brouard  2174:       }
                   2175:     }
                   2176:     
                   2177:     for(i=1; i<= nlstate; i++){
                   2178:       s1=0;
1.131     brouard  2179:       for(j=1; j<i; j++){
1.138     brouard  2180:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  2181:        /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2182:       }
                   2183:       for(j=i+1; j<=nlstate+ndeath; j++){
1.138     brouard  2184:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  2185:        /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2186:       }
1.138     brouard  2187:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126     brouard  2188:       ps[i][i]=1./(s1+1.);
1.138     brouard  2189:       /* Computing other pijs */
1.126     brouard  2190:       for(j=1; j<i; j++)
                   2191:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2192:       for(j=i+1; j<=nlstate+ndeath; j++)
                   2193:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2194:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2195:     } /* end i */
                   2196:     
                   2197:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2198:       for(jj=1; jj<= nlstate+ndeath; jj++){
                   2199:        ps[ii][jj]=0;
                   2200:        ps[ii][ii]=1;
                   2201:       }
                   2202:     }
                   2203:     
1.145     brouard  2204:     
                   2205:     /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2206:     /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2207:     /*         printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2208:     /*   } */
                   2209:     /*   printf("\n "); */
                   2210:     /* } */
                   2211:     /* printf("\n ");printf("%lf ",cov[2]);*/
                   2212:     /*
1.126     brouard  2213:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   2214:       goto end;*/
                   2215:     return ps;
                   2216: }
                   2217: 
                   2218: /**************** Product of 2 matrices ******************/
                   2219: 
1.145     brouard  2220: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  2221: {
                   2222:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   2223:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   2224:   /* in, b, out are matrice of pointers which should have been initialized 
                   2225:      before: only the contents of out is modified. The function returns
                   2226:      a pointer to pointers identical to out */
1.145     brouard  2227:   int i, j, k;
1.126     brouard  2228:   for(i=nrl; i<= nrh; i++)
1.145     brouard  2229:     for(k=ncolol; k<=ncoloh; k++){
                   2230:       out[i][k]=0.;
                   2231:       for(j=ncl; j<=nch; j++)
                   2232:        out[i][k] +=in[i][j]*b[j][k];
                   2233:     }
1.126     brouard  2234:   return out;
                   2235: }
                   2236: 
                   2237: 
                   2238: /************* Higher Matrix Product ***************/
                   2239: 
                   2240: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
                   2241: {
                   2242:   /* Computes the transition matrix starting at age 'age' over 
                   2243:      'nhstepm*hstepm*stepm' months (i.e. until
                   2244:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   2245:      nhstepm*hstepm matrices. 
                   2246:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   2247:      (typically every 2 years instead of every month which is too big 
                   2248:      for the memory).
                   2249:      Model is determined by parameters x and covariates have to be 
                   2250:      included manually here. 
                   2251: 
                   2252:      */
                   2253: 
                   2254:   int i, j, d, h, k;
1.131     brouard  2255:   double **out, cov[NCOVMAX+1];
1.126     brouard  2256:   double **newm;
1.187     brouard  2257:   double agexact;
1.214     brouard  2258:   double agebegin, ageend;
1.126     brouard  2259: 
                   2260:   /* Hstepm could be zero and should return the unit matrix */
                   2261:   for (i=1;i<=nlstate+ndeath;i++)
                   2262:     for (j=1;j<=nlstate+ndeath;j++){
                   2263:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   2264:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   2265:     }
                   2266:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2267:   for(h=1; h <=nhstepm; h++){
                   2268:     for(d=1; d <=hstepm; d++){
                   2269:       newm=savm;
                   2270:       /* Covariates have to be included here again */
                   2271:       cov[1]=1.;
1.214     brouard  2272:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  2273:       cov[2]=agexact;
                   2274:       if(nagesqr==1)
                   2275:        cov[3]= agexact*agexact;
1.131     brouard  2276:       for (k=1; k<=cptcovn;k++) 
1.200     brouard  2277:        cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   2278:        /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.186     brouard  2279:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
                   2280:        /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  2281:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2282:        /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
1.145     brouard  2283:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.200     brouard  2284:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2285:        /* 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  2286: 
                   2287: 
                   2288:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   2289:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
                   2290:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   2291:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2292:       savm=oldm;
                   2293:       oldm=newm;
                   2294:     }
                   2295:     for(i=1; i<=nlstate+ndeath; i++)
                   2296:       for(j=1;j<=nlstate+ndeath;j++) {
                   2297:        po[i][j][h]=newm[i][j];
1.128     brouard  2298:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  2299:       }
1.128     brouard  2300:     /*printf("h=%d ",h);*/
1.126     brouard  2301:   } /* end h */
1.128     brouard  2302: /*     printf("\n H=%d \n",h); */
1.126     brouard  2303:   return po;
                   2304: }
                   2305: 
1.162     brouard  2306: #ifdef NLOPT
                   2307:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   2308:   double fret;
                   2309:   double *xt;
                   2310:   int j;
                   2311:   myfunc_data *d2 = (myfunc_data *) pd;
                   2312: /* xt = (p1-1); */
                   2313:   xt=vector(1,n); 
                   2314:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   2315: 
                   2316:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   2317:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   2318:   printf("Function = %.12lf ",fret);
                   2319:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   2320:   printf("\n");
                   2321:  free_vector(xt,1,n);
                   2322:   return fret;
                   2323: }
                   2324: #endif
1.126     brouard  2325: 
                   2326: /*************** log-likelihood *************/
                   2327: double func( double *x)
                   2328: {
                   2329:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2330:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2331:   double **out;
                   2332:   double sw; /* Sum of weights */
                   2333:   double lli; /* Individual log likelihood */
                   2334:   int s1, s2;
                   2335:   double bbh, survp;
                   2336:   long ipmx;
1.187     brouard  2337:   double agexact;
1.126     brouard  2338:   /*extern weight */
                   2339:   /* We are differentiating ll according to initial status */
                   2340:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2341:   /*for(i=1;i<imx;i++) 
                   2342:     printf(" %d\n",s[4][i]);
                   2343:   */
1.162     brouard  2344: 
                   2345:   ++countcallfunc;
                   2346: 
1.126     brouard  2347:   cov[1]=1.;
                   2348: 
                   2349:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2350: 
                   2351:   if(mle==1){
                   2352:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138     brouard  2353:       /* Computes the values of the ncovmodel covariates of the model
                   2354:         depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
                   2355:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   2356:         to be observed in j being in i according to the model.
                   2357:        */
1.145     brouard  2358:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1.187     brouard  2359:          cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.145     brouard  2360:       }
1.137     brouard  2361:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.138     brouard  2362:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
1.137     brouard  2363:         has been calculated etc */
1.126     brouard  2364:       for(mi=1; mi<= wav[i]-1; mi++){
                   2365:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2366:          for (j=1;j<=nlstate+ndeath;j++){
                   2367:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2368:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2369:          }
                   2370:        for(d=0; d<dh[mi][i]; d++){
                   2371:          newm=savm;
1.187     brouard  2372:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2373:          cov[2]=agexact;
                   2374:          if(nagesqr==1)
                   2375:            cov[3]= agexact*agexact;
1.126     brouard  2376:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2377:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.126     brouard  2378:          }
                   2379:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2380:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2381:          savm=oldm;
                   2382:          oldm=newm;
                   2383:        } /* end mult */
                   2384:       
                   2385:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   2386:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   2387:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   2388:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   2389:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   2390:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   2391:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   2392:         * probability in order to take into account the bias as a fraction of the way
                   2393:         * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   2394:         * -stepm/2 to stepm/2 .
                   2395:         * For stepm=1 the results are the same as for previous versions of Imach.
                   2396:         * For stepm > 1 the results are less biased than in previous versions. 
                   2397:         */
                   2398:        s1=s[mw[mi][i]][i];
                   2399:        s2=s[mw[mi+1][i]][i];
                   2400:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2401:        /* bias bh is positive if real duration
                   2402:         * is higher than the multiple of stepm and negative otherwise.
                   2403:         */
                   2404:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   2405:        if( s2 > nlstate){ 
                   2406:          /* i.e. if s2 is a death state and if the date of death is known 
                   2407:             then the contribution to the likelihood is the probability to 
                   2408:             die between last step unit time and current  step unit time, 
                   2409:             which is also equal to probability to die before dh 
                   2410:             minus probability to die before dh-stepm . 
                   2411:             In version up to 0.92 likelihood was computed
                   2412:        as if date of death was unknown. Death was treated as any other
                   2413:        health state: the date of the interview describes the actual state
                   2414:        and not the date of a change in health state. The former idea was
                   2415:        to consider that at each interview the state was recorded
                   2416:        (healthy, disable or death) and IMaCh was corrected; but when we
                   2417:        introduced the exact date of death then we should have modified
                   2418:        the contribution of an exact death to the likelihood. This new
                   2419:        contribution is smaller and very dependent of the step unit
                   2420:        stepm. It is no more the probability to die between last interview
                   2421:        and month of death but the probability to survive from last
                   2422:        interview up to one month before death multiplied by the
                   2423:        probability to die within a month. Thanks to Chris
                   2424:        Jackson for correcting this bug.  Former versions increased
                   2425:        mortality artificially. The bad side is that we add another loop
                   2426:        which slows down the processing. The difference can be up to 10%
                   2427:        lower mortality.
                   2428:          */
1.183     brouard  2429:        /* If, at the beginning of the maximization mostly, the
                   2430:           cumulative probability or probability to be dead is
                   2431:           constant (ie = 1) over time d, the difference is equal to
                   2432:           0.  out[s1][3] = savm[s1][3]: probability, being at state
                   2433:           s1 at precedent wave, to be dead a month before current
                   2434:           wave is equal to probability, being at state s1 at
                   2435:           precedent wave, to be dead at mont of the current
                   2436:           wave. Then the observed probability (that this person died)
                   2437:           is null according to current estimated parameter. In fact,
                   2438:           it should be very low but not zero otherwise the log go to
                   2439:           infinity.
                   2440:        */
                   2441: /* #ifdef INFINITYORIGINAL */
                   2442: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2443: /* #else */
                   2444: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   2445: /*         lli=log(mytinydouble); */
                   2446: /*       else */
                   2447: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2448: /* #endif */
1.216   ! brouard  2449:          lli=log(out[s1][s2] - savm[s1][s2]);
        !          2450:          
        !          2451:        } else if  ( s2==-1 ) { /* alive */
1.126     brouard  2452:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   2453:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2454:          /*survp += out[s1][j]; */
                   2455:          lli= log(survp);
                   2456:        }
                   2457:        else if  (s2==-4) { 
                   2458:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   2459:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2460:          lli= log(survp); 
                   2461:        } 
                   2462:        else if  (s2==-5) { 
                   2463:          for (j=1,survp=0. ; j<=2; j++)  
                   2464:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2465:          lli= log(survp); 
                   2466:        } 
                   2467:        else{
                   2468:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2469:          /*  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 */
                   2470:        } 
                   2471:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   2472:        /*if(lli ==000.0)*/
                   2473:        /*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); */
                   2474:        ipmx +=1;
                   2475:        sw += weight[i];
                   2476:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.183     brouard  2477:        /* if (lli < log(mytinydouble)){ */
                   2478:        /*   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); */
                   2479:        /*   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]); */
                   2480:        /* } */
1.126     brouard  2481:       } /* end of wave */
                   2482:     } /* end of individual */
                   2483:   }  else if(mle==2){
                   2484:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2485:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2486:       for(mi=1; mi<= wav[i]-1; mi++){
                   2487:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2488:          for (j=1;j<=nlstate+ndeath;j++){
                   2489:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2490:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2491:          }
                   2492:        for(d=0; d<=dh[mi][i]; d++){
                   2493:          newm=savm;
1.187     brouard  2494:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2495:          cov[2]=agexact;
                   2496:          if(nagesqr==1)
                   2497:            cov[3]= agexact*agexact;
1.126     brouard  2498:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2499:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2500:          }
                   2501:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2502:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2503:          savm=oldm;
                   2504:          oldm=newm;
                   2505:        } /* end mult */
                   2506:       
                   2507:        s1=s[mw[mi][i]][i];
                   2508:        s2=s[mw[mi+1][i]][i];
                   2509:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2510:        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 */
                   2511:        ipmx +=1;
                   2512:        sw += weight[i];
                   2513:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2514:       } /* end of wave */
                   2515:     } /* end of individual */
                   2516:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   2517:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2518:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2519:       for(mi=1; mi<= wav[i]-1; mi++){
                   2520:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2521:          for (j=1;j<=nlstate+ndeath;j++){
                   2522:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2523:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2524:          }
                   2525:        for(d=0; d<dh[mi][i]; d++){
                   2526:          newm=savm;
1.187     brouard  2527:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2528:          cov[2]=agexact;
                   2529:          if(nagesqr==1)
                   2530:            cov[3]= agexact*agexact;
1.126     brouard  2531:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2532:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2533:          }
                   2534:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2535:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2536:          savm=oldm;
                   2537:          oldm=newm;
                   2538:        } /* end mult */
                   2539:       
                   2540:        s1=s[mw[mi][i]][i];
                   2541:        s2=s[mw[mi+1][i]][i];
                   2542:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2543:        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 */
                   2544:        ipmx +=1;
                   2545:        sw += weight[i];
                   2546:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2547:       } /* end of wave */
                   2548:     } /* end of individual */
                   2549:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   2550:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2551:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2552:       for(mi=1; mi<= wav[i]-1; mi++){
                   2553:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2554:          for (j=1;j<=nlstate+ndeath;j++){
                   2555:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2556:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2557:          }
                   2558:        for(d=0; d<dh[mi][i]; d++){
                   2559:          newm=savm;
1.187     brouard  2560:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2561:          cov[2]=agexact;
                   2562:          if(nagesqr==1)
                   2563:            cov[3]= agexact*agexact;
1.126     brouard  2564:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2565:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2566:          }
                   2567:        
                   2568:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2569:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2570:          savm=oldm;
                   2571:          oldm=newm;
                   2572:        } /* end mult */
                   2573:       
                   2574:        s1=s[mw[mi][i]][i];
                   2575:        s2=s[mw[mi+1][i]][i];
                   2576:        if( s2 > nlstate){ 
                   2577:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216   ! brouard  2578:        } else if  ( s2==-1 ) { /* alive */
        !          2579:          for (j=1,survp=0. ; j<=nlstate; j++) 
        !          2580:            survp += out[s1][j];
        !          2581:          lli= log(survp);
1.126     brouard  2582:        }else{
                   2583:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2584:        }
                   2585:        ipmx +=1;
                   2586:        sw += weight[i];
                   2587:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2588: /*     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]); */
                   2589:       } /* end of wave */
                   2590:     } /* end of individual */
                   2591:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   2592:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2593:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2594:       for(mi=1; mi<= wav[i]-1; mi++){
                   2595:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2596:          for (j=1;j<=nlstate+ndeath;j++){
                   2597:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2598:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2599:          }
                   2600:        for(d=0; d<dh[mi][i]; d++){
                   2601:          newm=savm;
1.187     brouard  2602:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2603:          cov[2]=agexact;
                   2604:          if(nagesqr==1)
                   2605:            cov[3]= agexact*agexact;
1.126     brouard  2606:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2607:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2608:          }
                   2609:        
                   2610:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2611:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2612:          savm=oldm;
                   2613:          oldm=newm;
                   2614:        } /* end mult */
                   2615:       
                   2616:        s1=s[mw[mi][i]][i];
                   2617:        s2=s[mw[mi+1][i]][i];
                   2618:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2619:        ipmx +=1;
                   2620:        sw += weight[i];
                   2621:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2622:        /*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]);*/
                   2623:       } /* end of wave */
                   2624:     } /* end of individual */
                   2625:   } /* End of if */
                   2626:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2627:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2628:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2629:   return -l;
                   2630: }
                   2631: 
                   2632: /*************** log-likelihood *************/
                   2633: double funcone( double *x)
                   2634: {
                   2635:   /* Same as likeli but slower because of a lot of printf and if */
                   2636:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2637:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2638:   double **out;
                   2639:   double lli; /* Individual log likelihood */
                   2640:   double llt;
                   2641:   int s1, s2;
                   2642:   double bbh, survp;
1.187     brouard  2643:   double agexact;
1.214     brouard  2644:   double agebegin, ageend;
1.126     brouard  2645:   /*extern weight */
                   2646:   /* We are differentiating ll according to initial status */
                   2647:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2648:   /*for(i=1;i<imx;i++) 
                   2649:     printf(" %d\n",s[4][i]);
                   2650:   */
                   2651:   cov[1]=1.;
                   2652: 
                   2653:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2654: 
                   2655:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2656:     for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2657:     for(mi=1; mi<= wav[i]-1; mi++){
                   2658:       for (ii=1;ii<=nlstate+ndeath;ii++)
                   2659:        for (j=1;j<=nlstate+ndeath;j++){
                   2660:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2661:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2662:        }
1.214     brouard  2663:       
                   2664:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   2665:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   2666:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
                   2667:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   2668:          and mw[mi+1][i]. dh depends on stepm.*/
1.126     brouard  2669:        newm=savm;
1.187     brouard  2670:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2671:        cov[2]=agexact;
                   2672:        if(nagesqr==1)
                   2673:          cov[3]= agexact*agexact;
1.126     brouard  2674:        for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2675:          cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2676:        }
1.187     brouard  2677: 
1.145     brouard  2678:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126     brouard  2679:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2680:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145     brouard  2681:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   2682:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126     brouard  2683:        savm=oldm;
                   2684:        oldm=newm;
                   2685:       } /* end mult */
                   2686:       
                   2687:       s1=s[mw[mi][i]][i];
                   2688:       s2=s[mw[mi+1][i]][i];
1.216   ! brouard  2689:       if(s2==-1){
        !          2690:        printf(" s1=%d, s2=%d i=%d \n", s1, s2, i);
        !          2691:        /* exit(1); */
        !          2692:       }
1.126     brouard  2693:       bbh=(double)bh[mi][i]/(double)stepm; 
                   2694:       /* bias is positive if real duration
                   2695:        * is higher than the multiple of stepm and negative otherwise.
                   2696:        */
                   2697:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
                   2698:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216   ! brouard  2699:       } else if  ( s2==-1 ) { /* alive */
1.126     brouard  2700:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   2701:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2702:        lli= log(survp);
                   2703:       }else if (mle==1){
                   2704:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2705:       } else if(mle==2){
                   2706:        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 */
                   2707:       } else if(mle==3){  /* exponential inter-extrapolation */
                   2708:        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 */
                   2709:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
                   2710:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  2711:       } else{  /* mle=0 back to 1 */
                   2712:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2713:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  2714:       } /* End of if */
                   2715:       ipmx +=1;
                   2716:       sw += weight[i];
                   2717:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  2718:       /*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  2719:       if(globpr){
1.214     brouard  2720:        fprintf(ficresilk,"%9ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %11.6f %8.4f %8.3f\
1.126     brouard  2721:  %11.6f %11.6f %11.6f ", \
1.214     brouard  2722:                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  2723:                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
                   2724:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   2725:          llt +=ll[k]*gipmx/gsw;
                   2726:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   2727:        }
                   2728:        fprintf(ficresilk," %10.6f\n", -llt);
                   2729:       }
                   2730:     } /* end of wave */
                   2731:   } /* end of individual */
                   2732:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2733:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2734:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2735:   if(globpr==0){ /* First time we count the contributions and weights */
                   2736:     gipmx=ipmx;
                   2737:     gsw=sw;
                   2738:   }
                   2739:   return -l;
                   2740: }
                   2741: 
                   2742: 
                   2743: /*************** function likelione ***********/
                   2744: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   2745: {
                   2746:   /* This routine should help understanding what is done with 
                   2747:      the selection of individuals/waves and
                   2748:      to check the exact contribution to the likelihood.
                   2749:      Plotting could be done.
                   2750:    */
                   2751:   int k;
                   2752: 
                   2753:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  2754:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  2755:     strcat(fileresilk,fileresu);
1.126     brouard  2756:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   2757:       printf("Problem with resultfile: %s\n", fileresilk);
                   2758:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   2759:     }
1.214     brouard  2760:     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");
                   2761:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  2762:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   2763:     for(k=1; k<=nlstate; k++) 
                   2764:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   2765:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   2766:   }
                   2767: 
                   2768:   *fretone=(*funcone)(p);
                   2769:   if(*globpri !=0){
                   2770:     fclose(ficresilk);
1.205     brouard  2771:     if (mle ==0)
                   2772:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   2773:     else if(mle >=1)
                   2774:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   2775:     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  2776:     
1.208     brouard  2777:       
                   2778:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  2779:       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  2780: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   2781:     }
1.207     brouard  2782:     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  2783: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  2784:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  2785: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  2786:     fflush(fichtm);
1.205     brouard  2787:   }
1.126     brouard  2788:   return;
                   2789: }
                   2790: 
                   2791: 
                   2792: /*********** Maximum Likelihood Estimation ***************/
                   2793: 
                   2794: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   2795: {
1.165     brouard  2796:   int i,j, iter=0;
1.126     brouard  2797:   double **xi;
                   2798:   double fret;
                   2799:   double fretone; /* Only one call to likelihood */
                   2800:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  2801: 
                   2802: #ifdef NLOPT
                   2803:   int creturn;
                   2804:   nlopt_opt opt;
                   2805:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   2806:   double *lb;
                   2807:   double minf; /* the minimum objective value, upon return */
                   2808:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   2809:   myfunc_data dinst, *d = &dinst;
                   2810: #endif
                   2811: 
                   2812: 
1.126     brouard  2813:   xi=matrix(1,npar,1,npar);
                   2814:   for (i=1;i<=npar;i++)
                   2815:     for (j=1;j<=npar;j++)
                   2816:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   2817:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  2818:   strcpy(filerespow,"POW_"); 
1.126     brouard  2819:   strcat(filerespow,fileres);
                   2820:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   2821:     printf("Problem with resultfile: %s\n", filerespow);
                   2822:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   2823:   }
                   2824:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   2825:   for (i=1;i<=nlstate;i++)
                   2826:     for(j=1;j<=nlstate+ndeath;j++)
                   2827:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   2828:   fprintf(ficrespow,"\n");
1.162     brouard  2829: #ifdef POWELL
1.126     brouard  2830:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  2831: #endif
1.126     brouard  2832: 
1.162     brouard  2833: #ifdef NLOPT
                   2834: #ifdef NEWUOA
                   2835:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   2836: #else
                   2837:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   2838: #endif
                   2839:   lb=vector(0,npar-1);
                   2840:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   2841:   nlopt_set_lower_bounds(opt, lb);
                   2842:   nlopt_set_initial_step1(opt, 0.1);
                   2843:   
                   2844:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   2845:   d->function = func;
                   2846:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   2847:   nlopt_set_min_objective(opt, myfunc, d);
                   2848:   nlopt_set_xtol_rel(opt, ftol);
                   2849:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   2850:     printf("nlopt failed! %d\n",creturn); 
                   2851:   }
                   2852:   else {
                   2853:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   2854:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   2855:     iter=1; /* not equal */
                   2856:   }
                   2857:   nlopt_destroy(opt);
                   2858: #endif
1.126     brouard  2859:   free_matrix(xi,1,npar,1,npar);
                   2860:   fclose(ficrespow);
1.203     brouard  2861:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   2862:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  2863:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  2864: 
                   2865: }
                   2866: 
                   2867: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  2868: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  2869: {
                   2870:   double  **a,**y,*x,pd;
1.203     brouard  2871:   /* double **hess; */
1.164     brouard  2872:   int i, j;
1.126     brouard  2873:   int *indx;
                   2874: 
                   2875:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  2876:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  2877:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   2878:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   2879:   double gompertz(double p[]);
1.203     brouard  2880:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  2881: 
                   2882:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   2883:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   2884:   for (i=1;i<=npar;i++){
1.203     brouard  2885:     printf("%d-",i);fflush(stdout);
                   2886:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  2887:    
                   2888:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   2889:     
                   2890:     /*  printf(" %f ",p[i]);
                   2891:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   2892:   }
                   2893:   
                   2894:   for (i=1;i<=npar;i++) {
                   2895:     for (j=1;j<=npar;j++)  {
                   2896:       if (j>i) { 
1.203     brouard  2897:        printf(".%d-%d",i,j);fflush(stdout);
                   2898:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   2899:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  2900:        
                   2901:        hess[j][i]=hess[i][j];    
                   2902:        /*printf(" %lf ",hess[i][j]);*/
                   2903:       }
                   2904:     }
                   2905:   }
                   2906:   printf("\n");
                   2907:   fprintf(ficlog,"\n");
                   2908: 
                   2909:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2910:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2911:   
                   2912:   a=matrix(1,npar,1,npar);
                   2913:   y=matrix(1,npar,1,npar);
                   2914:   x=vector(1,npar);
                   2915:   indx=ivector(1,npar);
                   2916:   for (i=1;i<=npar;i++)
                   2917:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   2918:   ludcmp(a,npar,indx,&pd);
                   2919: 
                   2920:   for (j=1;j<=npar;j++) {
                   2921:     for (i=1;i<=npar;i++) x[i]=0;
                   2922:     x[j]=1;
                   2923:     lubksb(a,npar,indx,x);
                   2924:     for (i=1;i<=npar;i++){ 
                   2925:       matcov[i][j]=x[i];
                   2926:     }
                   2927:   }
                   2928: 
                   2929:   printf("\n#Hessian matrix#\n");
                   2930:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   2931:   for (i=1;i<=npar;i++) { 
                   2932:     for (j=1;j<=npar;j++) { 
1.203     brouard  2933:       printf("%.6e ",hess[i][j]);
                   2934:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  2935:     }
                   2936:     printf("\n");
                   2937:     fprintf(ficlog,"\n");
                   2938:   }
                   2939: 
1.203     brouard  2940:   /* printf("\n#Covariance matrix#\n"); */
                   2941:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   2942:   /* for (i=1;i<=npar;i++) {  */
                   2943:   /*   for (j=1;j<=npar;j++) {  */
                   2944:   /*     printf("%.6e ",matcov[i][j]); */
                   2945:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   2946:   /*   } */
                   2947:   /*   printf("\n"); */
                   2948:   /*   fprintf(ficlog,"\n"); */
                   2949:   /* } */
                   2950: 
1.126     brouard  2951:   /* Recompute Inverse */
1.203     brouard  2952:   /* for (i=1;i<=npar;i++) */
                   2953:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   2954:   /* ludcmp(a,npar,indx,&pd); */
                   2955: 
                   2956:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   2957: 
                   2958:   /* for (j=1;j<=npar;j++) { */
                   2959:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   2960:   /*   x[j]=1; */
                   2961:   /*   lubksb(a,npar,indx,x); */
                   2962:   /*   for (i=1;i<=npar;i++){  */
                   2963:   /*     y[i][j]=x[i]; */
                   2964:   /*     printf("%.3e ",y[i][j]); */
                   2965:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   2966:   /*   } */
                   2967:   /*   printf("\n"); */
                   2968:   /*   fprintf(ficlog,"\n"); */
                   2969:   /* } */
                   2970: 
                   2971:   /* Verifying the inverse matrix */
                   2972: #ifdef DEBUGHESS
                   2973:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  2974: 
1.203     brouard  2975:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   2976:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  2977: 
                   2978:   for (j=1;j<=npar;j++) {
                   2979:     for (i=1;i<=npar;i++){ 
1.203     brouard  2980:       printf("%.2f ",y[i][j]);
                   2981:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  2982:     }
                   2983:     printf("\n");
                   2984:     fprintf(ficlog,"\n");
                   2985:   }
1.203     brouard  2986: #endif
1.126     brouard  2987: 
                   2988:   free_matrix(a,1,npar,1,npar);
                   2989:   free_matrix(y,1,npar,1,npar);
                   2990:   free_vector(x,1,npar);
                   2991:   free_ivector(indx,1,npar);
1.203     brouard  2992:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  2993: 
                   2994: 
                   2995: }
                   2996: 
                   2997: /*************** hessian matrix ****************/
                   2998: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  2999: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  3000:   int i;
                   3001:   int l=1, lmax=20;
1.203     brouard  3002:   double k1,k2, res, fx;
1.132     brouard  3003:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  3004:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   3005:   int k=0,kmax=10;
                   3006:   double l1;
                   3007: 
                   3008:   fx=func(x);
                   3009:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  3010:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  3011:     l1=pow(10,l);
                   3012:     delts=delt;
                   3013:     for(k=1 ; k <kmax; k=k+1){
                   3014:       delt = delta*(l1*k);
                   3015:       p2[theta]=x[theta] +delt;
1.145     brouard  3016:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  3017:       p2[theta]=x[theta]-delt;
                   3018:       k2=func(p2)-fx;
                   3019:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  3020:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  3021:       
1.203     brouard  3022: #ifdef DEBUGHESSII
1.126     brouard  3023:       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);
                   3024:       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);
                   3025: #endif
                   3026:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   3027:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   3028:        k=kmax;
                   3029:       }
                   3030:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  3031:        k=kmax; l=lmax*10;
1.126     brouard  3032:       }
                   3033:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   3034:        delts=delt;
                   3035:       }
1.203     brouard  3036:     } /* End loop k */
1.126     brouard  3037:   }
                   3038:   delti[theta]=delts;
                   3039:   return res; 
                   3040:   
                   3041: }
                   3042: 
1.203     brouard  3043: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  3044: {
                   3045:   int i;
1.164     brouard  3046:   int l=1, lmax=20;
1.126     brouard  3047:   double k1,k2,k3,k4,res,fx;
1.132     brouard  3048:   double p2[MAXPARM+1];
1.203     brouard  3049:   int k, kmax=1;
                   3050:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  3051: 
                   3052:   int firstime=0;
1.203     brouard  3053:   
1.126     brouard  3054:   fx=func(x);
1.203     brouard  3055:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  3056:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  3057:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   3058:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  3059:     k1=func(p2)-fx;
                   3060:   
1.203     brouard  3061:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   3062:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  3063:     k2=func(p2)-fx;
                   3064:   
1.203     brouard  3065:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   3066:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  3067:     k3=func(p2)-fx;
                   3068:   
1.203     brouard  3069:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   3070:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  3071:     k4=func(p2)-fx;
1.203     brouard  3072:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   3073:     if(k1*k2*k3*k4 <0.){
1.208     brouard  3074:       firstime=1;
1.203     brouard  3075:       kmax=kmax+10;
1.208     brouard  3076:     }
                   3077:     if(kmax >=10 || firstime ==1){
1.203     brouard  3078:       printf("Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
                   3079:       fprintf(ficlog,"Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
                   3080:       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);
                   3081:       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);
                   3082:     }
                   3083: #ifdef DEBUGHESSIJ
                   3084:     v1=hess[thetai][thetai];
                   3085:     v2=hess[thetaj][thetaj];
                   3086:     cv12=res;
                   3087:     /* Computing eigen value of Hessian matrix */
                   3088:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   3089:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   3090:     if ((lc2 <0) || (lc1 <0) ){
                   3091:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   3092:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   3093:       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);
                   3094:       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);
                   3095:     }
1.126     brouard  3096: #endif
                   3097:   }
                   3098:   return res;
                   3099: }
                   3100: 
1.203     brouard  3101:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   3102: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   3103: /* { */
                   3104: /*   int i; */
                   3105: /*   int l=1, lmax=20; */
                   3106: /*   double k1,k2,k3,k4,res,fx; */
                   3107: /*   double p2[MAXPARM+1]; */
                   3108: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   3109: /*   int k=0,kmax=10; */
                   3110: /*   double l1; */
                   3111:   
                   3112: /*   fx=func(x); */
                   3113: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   3114: /*     l1=pow(10,l); */
                   3115: /*     delts=delt; */
                   3116: /*     for(k=1 ; k <kmax; k=k+1){ */
                   3117: /*       delt = delti*(l1*k); */
                   3118: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   3119: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   3120: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   3121: /*       k1=func(p2)-fx; */
                   3122:       
                   3123: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   3124: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   3125: /*       k2=func(p2)-fx; */
                   3126:       
                   3127: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   3128: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   3129: /*       k3=func(p2)-fx; */
                   3130:       
                   3131: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   3132: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   3133: /*       k4=func(p2)-fx; */
                   3134: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   3135: /* #ifdef DEBUGHESSIJ */
                   3136: /*       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); */
                   3137: /*       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); */
                   3138: /* #endif */
                   3139: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   3140: /*     k=kmax; */
                   3141: /*       } */
                   3142: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   3143: /*     k=kmax; l=lmax*10; */
                   3144: /*       } */
                   3145: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   3146: /*     delts=delt; */
                   3147: /*       } */
                   3148: /*     } /\* End loop k *\/ */
                   3149: /*   } */
                   3150: /*   delti[theta]=delts; */
                   3151: /*   return res;  */
                   3152: /* } */
                   3153: 
                   3154: 
1.126     brouard  3155: /************** Inverse of matrix **************/
                   3156: void ludcmp(double **a, int n, int *indx, double *d) 
                   3157: { 
                   3158:   int i,imax,j,k; 
                   3159:   double big,dum,sum,temp; 
                   3160:   double *vv; 
                   3161:  
                   3162:   vv=vector(1,n); 
                   3163:   *d=1.0; 
                   3164:   for (i=1;i<=n;i++) { 
                   3165:     big=0.0; 
                   3166:     for (j=1;j<=n;j++) 
                   3167:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   3168:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   3169:     vv[i]=1.0/big; 
                   3170:   } 
                   3171:   for (j=1;j<=n;j++) { 
                   3172:     for (i=1;i<j;i++) { 
                   3173:       sum=a[i][j]; 
                   3174:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   3175:       a[i][j]=sum; 
                   3176:     } 
                   3177:     big=0.0; 
                   3178:     for (i=j;i<=n;i++) { 
                   3179:       sum=a[i][j]; 
                   3180:       for (k=1;k<j;k++) 
                   3181:        sum -= a[i][k]*a[k][j]; 
                   3182:       a[i][j]=sum; 
                   3183:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   3184:        big=dum; 
                   3185:        imax=i; 
                   3186:       } 
                   3187:     } 
                   3188:     if (j != imax) { 
                   3189:       for (k=1;k<=n;k++) { 
                   3190:        dum=a[imax][k]; 
                   3191:        a[imax][k]=a[j][k]; 
                   3192:        a[j][k]=dum; 
                   3193:       } 
                   3194:       *d = -(*d); 
                   3195:       vv[imax]=vv[j]; 
                   3196:     } 
                   3197:     indx[j]=imax; 
                   3198:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   3199:     if (j != n) { 
                   3200:       dum=1.0/(a[j][j]); 
                   3201:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   3202:     } 
                   3203:   } 
                   3204:   free_vector(vv,1,n);  /* Doesn't work */
                   3205: ;
                   3206: } 
                   3207: 
                   3208: void lubksb(double **a, int n, int *indx, double b[]) 
                   3209: { 
                   3210:   int i,ii=0,ip,j; 
                   3211:   double sum; 
                   3212:  
                   3213:   for (i=1;i<=n;i++) { 
                   3214:     ip=indx[i]; 
                   3215:     sum=b[ip]; 
                   3216:     b[ip]=b[i]; 
                   3217:     if (ii) 
                   3218:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   3219:     else if (sum) ii=i; 
                   3220:     b[i]=sum; 
                   3221:   } 
                   3222:   for (i=n;i>=1;i--) { 
                   3223:     sum=b[i]; 
                   3224:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   3225:     b[i]=sum/a[i][i]; 
                   3226:   } 
                   3227: } 
                   3228: 
                   3229: void pstamp(FILE *fichier)
                   3230: {
1.196     brouard  3231:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  3232: }
                   3233: 
                   3234: /************ Frequencies ********************/
1.214     brouard  3235: void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
                   3236:                  int *Tvaraff, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[],\
                   3237:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.126     brouard  3238: {  /* Some frequencies */
                   3239:   
1.164     brouard  3240:   int i, m, jk, j1, bool, z1,j;
1.214     brouard  3241:   int mi; /* Effective wave */
1.126     brouard  3242:   int first;
                   3243:   double ***freq; /* Frequencies */
                   3244:   double *pp, **prop;
                   3245:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
1.214     brouard  3246:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   3247:   double agebegin, ageend;
                   3248:     
1.126     brouard  3249:   pp=vector(1,nlstate);
                   3250:   prop=matrix(1,nlstate,iagemin,iagemax+3);
1.201     brouard  3251:   strcpy(fileresp,"P_");
                   3252:   strcat(fileresp,fileresu);
1.213     brouard  3253:   /*strcat(fileresphtm,fileresu);*/
1.126     brouard  3254:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   3255:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   3256:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   3257:     exit(0);
                   3258:   }
1.214     brouard  3259: 
1.213     brouard  3260:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   3261:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   3262:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   3263:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   3264:     fflush(ficlog);
                   3265:     exit(70); 
                   3266:   }
1.214     brouard  3267:   else{
                   3268:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   3269: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   3270: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
                   3271:          fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   3272:   }
                   3273:     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);
                   3274:     
                   3275:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   3276:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   3277:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   3278:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   3279:     fflush(ficlog);
                   3280:     exit(70); 
                   3281:   }
                   3282:   else{
                   3283:     fprintf(ficresphtmfr,"<html><head>\n<title>IMaCh PHTM_Frequency table %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   3284: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   3285: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
                   3286:          fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   3287:   }
                   3288:   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);
                   3289: 
1.126     brouard  3290:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
                   3291:   j1=0;
                   3292:   
                   3293:   j=cptcoveff;
                   3294:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   3295: 
                   3296:   first=1;
                   3297: 
1.214     brouard  3298:   for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){ /* Loop on covariates combination */
1.126     brouard  3299:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   3300:        scanf("%d", i);*/
                   3301:       for (i=-5; i<=nlstate+ndeath; i++)  
                   3302:        for (jk=-5; jk<=nlstate+ndeath; jk++)  
                   3303:          for(m=iagemin; m <= iagemax+3; m++)
                   3304:            freq[i][jk][m]=0;
1.143     brouard  3305:       
                   3306:       for (i=1; i<=nlstate; i++)  
                   3307:        for(m=iagemin; m <= iagemax+3; m++)
                   3308:          prop[i][m]=0;
1.126     brouard  3309:       
                   3310:       dateintsum=0;
                   3311:       k2cpt=0;
1.214     brouard  3312:       for (i=1; i<=imx; i++) { /* For each individual i */
1.126     brouard  3313:        bool=1;
1.210     brouard  3314:        if (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
1.144     brouard  3315:          for (z1=1; z1<=cptcoveff; z1++)       
1.198     brouard  3316:             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
1.145     brouard  3317:                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144     brouard  3318:               bool=0;
1.198     brouard  3319:               /* 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", 
                   3320:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   3321:                 j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
                   3322:               /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
1.144     brouard  3323:             } 
1.210     brouard  3324:        } /* cptcovn > 0 */
1.214     brouard  3325: 
1.126     brouard  3326:        if (bool==1){
1.214     brouard  3327:          /* for(m=firstpass; m<=lastpass; m++){ */
                   3328:          for(mi=1; mi<wav[i];mi++){
                   3329:            m=mw[mi][i];
                   3330:            /* dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective (mi) waves m=mw[mi][i]
                   3331:               and mw[mi+1][i]. dh depends on stepm. */
                   3332:            agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   3333:            ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /* Age at end of wave and transition */
                   3334:            if(m >=firstpass && m <=lastpass){
                   3335:              k2=anint[m][i]+(mint[m][i]/12.);
                   3336:              /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   3337:              if(agev[m][i]==0) agev[m][i]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   3338:              if(agev[m][i]==1) agev[m][i]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   3339:              if (s[m][i]>0 && s[m][i]<=nlstate)  /* If status at wave m is known and a live state */
                   3340:                prop[s[m][i]][(int)agev[m][i]] += weight[i];  /* At age of beginning of transition, where status is known */
1.126     brouard  3341:              if (m<lastpass) {
1.214     brouard  3342:                /* if(s[m][i]==4 && s[m+1][i]==4) */
                   3343:                /*   printf(" num=%ld m=%d, i=%d s1=%d s2=%d agev at m=%d\n", num[i], m, i,s[m][i],s[m+1][i], (int)agev[m][i]); */
                   3344:                if(s[m][i]==-1)
                   3345:                  printf(" num=%ld m=%d, i=%d s1=%d s2=%d agev at m=%d agebegin=%.2f ageend=%.2f, agemed=%d\n", num[i], m, i,s[m][i],s[m+1][i], (int)agev[m][i],agebegin, ageend, (int)((agebegin+ageend)/2.));
                   3346:                freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i]; /* At age of beginning of transition, where status is known */
                   3347:                /* freq[s[m][i]][s[m+1][i]][(int)((agebegin+ageend)/2.)] += weight[i]; */
                   3348:                freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i]; /* Total is in iagemax+3 *//* At age of beginning of transition, where status is known */
1.126     brouard  3349:              }
1.214     brouard  3350:            }  
                   3351:            if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3)) && (anint[m][i]!=9999) && (mint[m][i]!=99)) {
                   3352:              dateintsum=dateintsum+k2;
                   3353:              k2cpt++;
                   3354:              /* printf("i=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",i, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
                   3355:            }
                   3356:            /*}*/
1.210     brouard  3357:          } /* end m */
                   3358:        } /* end bool */
                   3359:       } /* end i = 1 to imx */
1.126     brouard  3360:        
                   3361:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   3362:       pstamp(ficresp);
                   3363:       if  (cptcovn>0) {
                   3364:        fprintf(ficresp, "\n#********** Variable "); 
1.214     brouard  3365:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   3366:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
1.213     brouard  3367:        for (z1=1; z1<=cptcoveff; z1++){
                   3368:          fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   3369:          fprintf(ficresphtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.214     brouard  3370:          fprintf(ficresphtmfr, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.213     brouard  3371:        }
                   3372:          fprintf(ficresp, "**********\n#");
1.214     brouard  3373:        fprintf(ficresphtm, "**********</h3>\n");
                   3374:        fprintf(ficresphtmfr, "**********</h3>\n");
1.143     brouard  3375:        fprintf(ficlog, "\n#********** Variable "); 
1.198     brouard  3376:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.214     brouard  3377:        fprintf(ficlog, "**********\n");
1.126     brouard  3378:       }
1.214     brouard  3379:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.213     brouard  3380:       for(i=1; i<=nlstate;i++) {
1.126     brouard  3381:        fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
1.213     brouard  3382:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   3383:       }
1.126     brouard  3384:       fprintf(ficresp, "\n");
1.213     brouard  3385:       fprintf(ficresphtm, "\n");
1.126     brouard  3386:       
1.214     brouard  3387:       /* Header of frequency table by age */
                   3388:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   3389:       fprintf(ficresphtmfr,"<th>Age</th> ");
                   3390:       for(jk=-1; jk <=nlstate+ndeath; jk++){
                   3391:        for(m=-1; m <=nlstate+ndeath; m++){
                   3392:          if(jk!=0 && m!=0)
                   3393:            fprintf(ficresphtmfr,"<th>%d%d</th> ",jk,m);
                   3394:        }
                   3395:       }
                   3396:       fprintf(ficresphtmfr, "\n");
                   3397:       
                   3398:       /* For each age */
1.126     brouard  3399:       for(i=iagemin; i <= iagemax+3; i++){
1.213     brouard  3400:        fprintf(ficresphtm,"<tr>");
1.214     brouard  3401:        if(i==iagemax+1){
                   3402:          fprintf(ficlog,"1");
                   3403:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   3404:        }else if(i==iagemax+2){
                   3405:          fprintf(ficlog,"0");
                   3406:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   3407:        }else if(i==iagemax+3){
1.126     brouard  3408:          fprintf(ficlog,"Total");
1.214     brouard  3409:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
1.126     brouard  3410:        }else{
                   3411:          if(first==1){
                   3412:            first=0;
                   3413:            printf("See log file for details...\n");
                   3414:          }
1.214     brouard  3415:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",i);
1.126     brouard  3416:          fprintf(ficlog,"Age %d", i);
                   3417:        }
                   3418:        for(jk=1; jk <=nlstate ; jk++){
                   3419:          for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   3420:            pp[jk] += freq[jk][m][i]; 
                   3421:        }
                   3422:        for(jk=1; jk <=nlstate ; jk++){
                   3423:          for(m=-1, pos=0; m <=0 ; m++)
                   3424:            pos += freq[jk][m][i];
                   3425:          if(pp[jk]>=1.e-10){
                   3426:            if(first==1){
1.132     brouard  3427:              printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126     brouard  3428:            }
                   3429:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   3430:          }else{
                   3431:            if(first==1)
                   3432:              printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   3433:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   3434:          }
                   3435:        }
                   3436: 
                   3437:        for(jk=1; jk <=nlstate ; jk++){
                   3438:          for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
                   3439:            pp[jk] += freq[jk][m][i];
                   3440:        }       
                   3441:        for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
                   3442:          pos += pp[jk];
                   3443:          posprop += prop[jk][i];
                   3444:        }
                   3445:        for(jk=1; jk <=nlstate ; jk++){
                   3446:          if(pos>=1.e-5){
                   3447:            if(first==1)
                   3448:              printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   3449:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   3450:          }else{
                   3451:            if(first==1)
                   3452:              printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   3453:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   3454:          }
                   3455:          if( i <= iagemax){
                   3456:            if(pos>=1.e-5){
                   3457:              fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
1.213     brouard  3458:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",i,prop[jk][i]/posprop, prop[jk][i],posprop);
1.126     brouard  3459:              /*probs[i][jk][j1]= pp[jk]/pos;*/
                   3460:              /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
                   3461:            }
1.213     brouard  3462:            else{
1.126     brouard  3463:              fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
1.213     brouard  3464:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",i, prop[jk][i],posprop);
                   3465:            }
1.126     brouard  3466:          }
                   3467:        }
                   3468:        
1.214     brouard  3469:        for(jk=-1; jk <=nlstate+ndeath; jk++){
                   3470:          for(m=-1; m <=nlstate+ndeath; m++){
                   3471:            if(freq[jk][m][i] !=0 ) { /* minimizing output */
                   3472:              if(first==1){
                   3473:                printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
                   3474:              }
1.126     brouard  3475:              fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
                   3476:            }
1.214     brouard  3477:            if(jk!=0 && m!=0)
                   3478:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[jk][m][i]);
                   3479:          }
                   3480:        }
                   3481:        fprintf(ficresphtmfr,"</tr>\n ");
1.213     brouard  3482:        if(i <= iagemax){
1.126     brouard  3483:          fprintf(ficresp,"\n");
1.213     brouard  3484:          fprintf(ficresphtm,"</tr>\n");
                   3485:        }
1.126     brouard  3486:        if(first==1)
                   3487:          printf("Others in log...\n");
                   3488:        fprintf(ficlog,"\n");
1.210     brouard  3489:       } /* end loop i */
1.213     brouard  3490:       fprintf(ficresphtm,"</table>\n");
1.214     brouard  3491:       fprintf(ficresphtmfr,"</table>\n");
1.145     brouard  3492:       /*}*/
1.210     brouard  3493:   } /* end j1 */
1.126     brouard  3494:   dateintmean=dateintsum/k2cpt; 
                   3495:  
                   3496:   fclose(ficresp);
1.213     brouard  3497:   fclose(ficresphtm);
1.214     brouard  3498:   fclose(ficresphtmfr);
1.126     brouard  3499:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
                   3500:   free_vector(pp,1,nlstate);
                   3501:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
                   3502:   /* End of Freq */
                   3503: }
                   3504: 
                   3505: /************ Prevalence ********************/
                   3506: 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)
                   3507: {  
                   3508:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   3509:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   3510:      We still use firstpass and lastpass as another selection.
                   3511:   */
                   3512:  
1.164     brouard  3513:   int i, m, jk, j1, bool, z1,j;
1.214     brouard  3514:   int mi; /* Effective wave */
                   3515:   int iage;
                   3516:   double agebegin, ageend;
1.164     brouard  3517: 
                   3518:   double **prop;
                   3519:   double posprop; 
1.126     brouard  3520:   double  y2; /* in fractional years */
                   3521:   int iagemin, iagemax;
1.145     brouard  3522:   int first; /** to stop verbosity which is redirected to log file */
1.126     brouard  3523: 
                   3524:   iagemin= (int) agemin;
                   3525:   iagemax= (int) agemax;
                   3526:   /*pp=vector(1,nlstate);*/
                   3527:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
                   3528:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   3529:   j1=0;
                   3530:   
1.145     brouard  3531:   /*j=cptcoveff;*/
1.126     brouard  3532:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   3533:   
1.145     brouard  3534:   first=1;
                   3535:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
1.214     brouard  3536:     for (i=1; i<=nlstate; i++)  
                   3537:       for(iage=iagemin; iage <= iagemax+3; iage++)
                   3538:        prop[i][iage]=0.0;
                   3539:     
                   3540:     for (i=1; i<=imx; i++) { /* Each individual */
                   3541:       bool=1;
                   3542:       if  (cptcovn>0) {  /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   3543:        for (z1=1; z1<=cptcoveff; z1++) 
                   3544:          if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) 
                   3545:            bool=0;
                   3546:       } 
                   3547:       if (bool==1) { 
                   3548:        /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   3549:        for(mi=1; mi<wav[i];mi++){
                   3550:          m=mw[mi][i];
                   3551:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   3552:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   3553:          if(m >=firstpass && m <=lastpass){
1.126     brouard  3554:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   3555:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   3556:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   3557:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   3558:              if((int)agev[m][i] <iagemin || (int)agev[m][i] >iagemax+3) printf("Error on individual =%d agev[m][i]=%f m=%d\n",i, agev[m][i],m); 
1.214     brouard  3559:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
1.126     brouard  3560:                /*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]]);*/
1.214     brouard  3561:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   3562:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   3563:              } /* end valid statuses */ 
                   3564:            } /* end selection of dates */
1.126     brouard  3565:          } /* end selection of waves */
1.214     brouard  3566:        } /* end effective waves */
                   3567:       } /* end bool */
                   3568:     }
                   3569:     for(i=iagemin; i <= iagemax+3; i++){  
                   3570:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   3571:        posprop += prop[jk][i]; 
                   3572:       } 
                   3573:       
                   3574:       for(jk=1; jk <=nlstate ; jk++){      
                   3575:        if( i <=  iagemax){ 
                   3576:          if(posprop>=1.e-5){ 
                   3577:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   3578:          } else{
                   3579:            if(first==1){
                   3580:              first=0;
                   3581:              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]);
1.145     brouard  3582:            }
1.214     brouard  3583:          }
                   3584:        } 
                   3585:       }/* end jk */ 
                   3586:     }/* end i */ 
1.145     brouard  3587:     /*} *//* end i1 */
                   3588:   } /* end j1 */
1.126     brouard  3589:   
                   3590:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   3591:   /*free_vector(pp,1,nlstate);*/
                   3592:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
                   3593: }  /* End of prevalence */
                   3594: 
                   3595: /************* Waves Concatenation ***************/
                   3596: 
                   3597: 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)
                   3598: {
                   3599:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   3600:      Death is a valid wave (if date is known).
                   3601:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   3602:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   3603:      and mw[mi+1][i]. dh depends on stepm.
                   3604:      */
                   3605: 
                   3606:   int i, mi, m;
                   3607:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   3608:      double sum=0., jmean=0.;*/
1.214     brouard  3609:   int first, firstwo;
1.126     brouard  3610:   int j, k=0,jk, ju, jl;
                   3611:   double sum=0.;
                   3612:   first=0;
1.214     brouard  3613:   firstwo=0;
1.164     brouard  3614:   jmin=100000;
1.126     brouard  3615:   jmax=-1;
                   3616:   jmean=0.;
1.214     brouard  3617:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.126     brouard  3618:     mi=0;
                   3619:     m=firstpass;
1.214     brouard  3620:     while(s[m][i] <= nlstate){  /* a live state */
1.216   ! brouard  3621:       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.126     brouard  3622:        mw[++mi][i]=m;
1.216   ! brouard  3623:       }
        !          3624:       if(m >=lastpass){
        !          3625:        if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){
        !          3626:          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);
        !          3627:          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.\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);
        !          3628:          mw[++mi][i]=m;
        !          3629:        }
        !          3630:        if(s[m][i]==-2){ /* Vital status is really unknown */
        !          3631:          nbwarn++;
        !          3632:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified? */
        !          3633:            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);
        !          3634:            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);
        !          3635:          }
        !          3636:          break;
        !          3637:        }
1.126     brouard  3638:        break;
1.216   ! brouard  3639:       }
1.126     brouard  3640:       else
                   3641:        m++;
                   3642:     }/* end while */
1.216   ! brouard  3643:     
        !          3644:     /* After last pass */
1.214     brouard  3645:     if (s[m][i] > nlstate){  /* In a death state */
1.126     brouard  3646:       mi++;    /* Death is another wave */
                   3647:       /* if(mi==0)  never been interviewed correctly before death */
                   3648:         /* Only death is a correct wave */
                   3649:       mw[mi][i]=m;
1.216   ! brouard  3650:     }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 */
        !          3651:       /* m++; */
        !          3652:       /* mi++; */
        !          3653:       /* s[m][i]=nlstate+1;  /\* We are setting the status to the last of non live state *\/ */
        !          3654:       /* mw[mi][i]=m; */
        !          3655:       nberr++;
1.214     brouard  3656:       if(firstwo==0){
1.216   ! brouard  3657:        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 );
        !          3658:        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.\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 );
1.214     brouard  3659:        firstwo=1;
1.216   ! brouard  3660:       }else if(firstwo==1){
        !          3661:        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.\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 );
1.214     brouard  3662:       }
1.126     brouard  3663:     }
                   3664:     wav[i]=mi;
                   3665:     if(mi==0){
                   3666:       nbwarn++;
                   3667:       if(first==0){
                   3668:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   3669:        first=1;
                   3670:       }
                   3671:       if(first==1){
                   3672:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
                   3673:       }
                   3674:     } /* end mi==0 */
                   3675:   } /* End individuals */
1.214     brouard  3676:   /* wav and mw are no more changed */
1.126     brouard  3677: 
1.214     brouard  3678:   
1.126     brouard  3679:   for(i=1; i<=imx; i++){
                   3680:     for(mi=1; mi<wav[i];mi++){
                   3681:       if (stepm <=0)
                   3682:        dh[mi][i]=1;
                   3683:       else{
                   3684:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                   3685:          if (agedc[i] < 2*AGESUP) {
                   3686:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   3687:            if(j==0) j=1;  /* Survives at least one month after exam */
                   3688:            else if(j<0){
                   3689:              nberr++;
                   3690:              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]);
                   3691:              j=1; /* Temporary Dangerous patch */
                   3692:              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);
                   3693:              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]);
                   3694:              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);
                   3695:            }
                   3696:            k=k+1;
                   3697:            if (j >= jmax){
                   3698:              jmax=j;
                   3699:              ijmax=i;
                   3700:            }
                   3701:            if (j <= jmin){
                   3702:              jmin=j;
                   3703:              ijmin=i;
                   3704:            }
                   3705:            sum=sum+j;
                   3706:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   3707:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   3708:          }
                   3709:        }
                   3710:        else{
                   3711:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
                   3712: /*       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]); */
                   3713: 
                   3714:          k=k+1;
                   3715:          if (j >= jmax) {
                   3716:            jmax=j;
                   3717:            ijmax=i;
                   3718:          }
                   3719:          else if (j <= jmin){
                   3720:            jmin=j;
                   3721:            ijmin=i;
                   3722:          }
                   3723:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   3724:          /*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]);*/
                   3725:          if(j<0){
                   3726:            nberr++;
                   3727:            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]);
                   3728:            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]);
                   3729:          }
                   3730:          sum=sum+j;
                   3731:        }
                   3732:        jk= j/stepm;
                   3733:        jl= j -jk*stepm;
                   3734:        ju= j -(jk+1)*stepm;
                   3735:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   3736:          if(jl==0){
                   3737:            dh[mi][i]=jk;
                   3738:            bh[mi][i]=0;
                   3739:          }else{ /* We want a negative bias in order to only have interpolation ie
1.136     brouard  3740:                  * to avoid the price of an extra matrix product in likelihood */
1.126     brouard  3741:            dh[mi][i]=jk+1;
                   3742:            bh[mi][i]=ju;
                   3743:          }
                   3744:        }else{
                   3745:          if(jl <= -ju){
                   3746:            dh[mi][i]=jk;
                   3747:            bh[mi][i]=jl;       /* bias is positive if real duration
                   3748:                                 * is higher than the multiple of stepm and negative otherwise.
                   3749:                                 */
                   3750:          }
                   3751:          else{
                   3752:            dh[mi][i]=jk+1;
                   3753:            bh[mi][i]=ju;
                   3754:          }
                   3755:          if(dh[mi][i]==0){
                   3756:            dh[mi][i]=1; /* At least one step */
                   3757:            bh[mi][i]=ju; /* At least one step */
                   3758:            /*  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);*/
                   3759:          }
                   3760:        } /* end if mle */
                   3761:       }
                   3762:     } /* end wave */
                   3763:   }
                   3764:   jmean=sum/k;
                   3765:   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  3766:   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  3767:  }
                   3768: 
                   3769: /*********** Tricode ****************************/
1.145     brouard  3770: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126     brouard  3771: {
1.144     brouard  3772:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   3773:   /*     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  3774:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145     brouard  3775:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.169     brouard  3776:    * nbcode[Tvar[j]][1]= 
1.144     brouard  3777:   */
1.130     brouard  3778: 
1.145     brouard  3779:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136     brouard  3780:   int modmaxcovj=0; /* Modality max of covariates j */
1.145     brouard  3781:   int cptcode=0; /* Modality max of covariates j */
                   3782:   int modmincovj=0; /* Modality min of covariates j */
                   3783: 
                   3784: 
1.126     brouard  3785:   cptcoveff=0; 
                   3786:  
1.144     brouard  3787:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  3788: 
1.145     brouard  3789:   /* Loop on covariates without age and products */
1.186     brouard  3790:   for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
1.192     brouard  3791:     for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.186     brouard  3792:     for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the 
1.136     brouard  3793:                               modality of this covariate Vj*/ 
1.145     brouard  3794:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   3795:                                    * If product of Vn*Vm, still boolean *:
                   3796:                                    * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   3797:                                    * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   3798:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136     brouard  3799:                                      modality of the nth covariate of individual i. */
1.145     brouard  3800:       if (ij > modmaxcovj)
                   3801:         modmaxcovj=ij; 
                   3802:       else if (ij < modmincovj) 
                   3803:        modmincovj=ij; 
                   3804:       if ((ij < -1) && (ij > NCOVMAX)){
                   3805:        printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   3806:        exit(1);
                   3807:       }else
1.136     brouard  3808:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145     brouard  3809:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126     brouard  3810:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136     brouard  3811:       /* getting the maximum value of the modality of the covariate
                   3812:         (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   3813:         female is 1, then modmaxcovj=1.*/
1.192     brouard  3814:     } /* end for loop on individuals i */
1.145     brouard  3815:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
1.192     brouard  3816:     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  3817:     cptcode=modmaxcovj;
1.137     brouard  3818:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145     brouard  3819:    /*for (i=0; i<=cptcode; i++) {*/
1.192     brouard  3820:     for (k=modmincovj;  k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
                   3821:       printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   3822:       fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   3823:       if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
                   3824:        if( k != -1){
                   3825:          ncodemax[j]++;  /* ncodemax[j]= Number of modalities of the j th
                   3826:                             covariate for which somebody answered excluding 
                   3827:                             undefined. Usually 2: 0 and 1. */
                   3828:        }
                   3829:        ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
                   3830:                             covariate for which somebody answered including 
                   3831:                             undefined. Usually 3: -1, 0 and 1. */
1.145     brouard  3832:       }
                   3833:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
                   3834:         historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131     brouard  3835:     } /* Ndum[-1] number of undefined modalities */
1.126     brouard  3836: 
1.136     brouard  3837:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.186     brouard  3838:     /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. 
                   3839:        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  3840:        modmincovj=3; modmaxcovj = 7;
1.186     brouard  3841:        There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
                   3842:        which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
                   3843:        defining two dummy variables: variables V1_1 and V1_2.
1.145     brouard  3844:        nbcode[Tvar[j]][ij]=k;
                   3845:        nbcode[Tvar[j]][1]=0;
                   3846:        nbcode[Tvar[j]][2]=1;
                   3847:        nbcode[Tvar[j]][3]=2;
1.197     brouard  3848:        To be continued (not working yet).
1.145     brouard  3849:     */
1.197     brouard  3850:     ij=0; /* ij is similar to i but can jump over null modalities */
                   3851:     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*/
                   3852:        if (Ndum[i] == 0) { /* If nobody responded to this modality k */
1.192     brouard  3853:          break;
                   3854:        }
                   3855:        ij++;
1.197     brouard  3856:        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  3857:        cptcode = ij; /* New max modality for covar j */
                   3858:     } /* end of loop on modality i=-1 to 1 or more */
                   3859:       
                   3860:     /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
                   3861:     /*         /\*recode from 0 *\/ */
                   3862:     /*                                      k is a modality. If we have model=V1+V1*sex  */
                   3863:     /*                                      then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
                   3864:     /*                                   But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
                   3865:     /*         } */
                   3866:     /*         /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
                   3867:     /*         if (ij > ncodemax[j]) { */
                   3868:     /*           printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
                   3869:     /*           fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
                   3870:     /*           break; */
                   3871:     /*         } */
                   3872:     /*   }  /\* end of loop on modality k *\/ */
1.137     brouard  3873:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   3874:   
1.145     brouard  3875:  for (k=-1; k< maxncov; k++) Ndum[k]=0; 
1.137     brouard  3876:   
1.187     brouard  3877:   for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
1.145     brouard  3878:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   3879:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
1.187     brouard  3880:    Ndum[ij]++; /* Might be supersed V1 + V1*age */
1.145     brouard  3881:  } 
1.126     brouard  3882: 
1.192     brouard  3883:  ij=0;
1.145     brouard  3884:  for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   3885:    /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126     brouard  3886:    if((Ndum[i]!=0) && (i<=ncovcol)){
1.192     brouard  3887:      ij++;
1.145     brouard  3888:      /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   3889:      Tvaraff[ij]=i; /*For printing (unclear) */
1.192     brouard  3890:    }else{
                   3891:        /* Tvaraff[ij]=0; */
                   3892:    }
1.126     brouard  3893:  }
1.192     brouard  3894:  /* ij--; */
1.144     brouard  3895:  cptcoveff=ij; /*Number of total covariates*/
1.145     brouard  3896: 
1.126     brouard  3897: }
                   3898: 
1.145     brouard  3899: 
1.126     brouard  3900: /*********** Health Expectancies ****************/
                   3901: 
1.127     brouard  3902: 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  3903: 
                   3904: {
                   3905:   /* Health expectancies, no variances */
1.164     brouard  3906:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  3907:   int nhstepma, nstepma; /* Decreasing with age */
                   3908:   double age, agelim, hf;
                   3909:   double ***p3mat;
                   3910:   double eip;
                   3911: 
                   3912:   pstamp(ficreseij);
                   3913:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   3914:   fprintf(ficreseij,"# Age");
                   3915:   for(i=1; i<=nlstate;i++){
                   3916:     for(j=1; j<=nlstate;j++){
                   3917:       fprintf(ficreseij," e%1d%1d ",i,j);
                   3918:     }
                   3919:     fprintf(ficreseij," e%1d. ",i);
                   3920:   }
                   3921:   fprintf(ficreseij,"\n");
                   3922: 
                   3923:   
                   3924:   if(estepm < stepm){
                   3925:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3926:   }
                   3927:   else  hstepm=estepm;   
                   3928:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3929:    * This is mainly to measure the difference between two models: for example
                   3930:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3931:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3932:    * progression in between and thus overestimating or underestimating according
                   3933:    * to the curvature of the survival function. If, for the same date, we 
                   3934:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3935:    * to compare the new estimate of Life expectancy with the same linear 
                   3936:    * hypothesis. A more precise result, taking into account a more precise
                   3937:    * curvature will be obtained if estepm is as small as stepm. */
                   3938: 
                   3939:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3940:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3941:      nhstepm is the number of hstepm from age to agelim 
                   3942:      nstepm is the number of stepm from age to agelin. 
                   3943:      Look at hpijx to understand the reason of that which relies in memory size
                   3944:      and note for a fixed period like estepm months */
                   3945:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3946:      survival function given by stepm (the optimization length). Unfortunately it
                   3947:      means that if the survival funtion is printed only each two years of age and if
                   3948:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3949:      results. So we changed our mind and took the option of the best precision.
                   3950:   */
                   3951:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3952: 
                   3953:   agelim=AGESUP;
                   3954:   /* If stepm=6 months */
                   3955:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   3956:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   3957:     
                   3958: /* nhstepm age range expressed in number of stepm */
                   3959:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3960:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3961:   /* if (stepm >= YEARM) hstepm=1;*/
                   3962:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3963:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3964: 
                   3965:   for (age=bage; age<=fage; age ++){ 
                   3966:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3967:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3968:     /* if (stepm >= YEARM) hstepm=1;*/
                   3969:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3970: 
                   3971:     /* If stepm=6 months */
                   3972:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3973:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3974:     
                   3975:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3976:     
                   3977:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3978:     
                   3979:     printf("%d|",(int)age);fflush(stdout);
                   3980:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3981:     
                   3982:     /* Computing expectancies */
                   3983:     for(i=1; i<=nlstate;i++)
                   3984:       for(j=1; j<=nlstate;j++)
                   3985:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3986:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   3987:          
                   3988:          /* 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]);*/
                   3989: 
                   3990:        }
                   3991: 
                   3992:     fprintf(ficreseij,"%3.0f",age );
                   3993:     for(i=1; i<=nlstate;i++){
                   3994:       eip=0;
                   3995:       for(j=1; j<=nlstate;j++){
                   3996:        eip +=eij[i][j][(int)age];
                   3997:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   3998:       }
                   3999:       fprintf(ficreseij,"%9.4f", eip );
                   4000:     }
                   4001:     fprintf(ficreseij,"\n");
                   4002:     
                   4003:   }
                   4004:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4005:   printf("\n");
                   4006:   fprintf(ficlog,"\n");
                   4007:   
                   4008: }
                   4009: 
1.127     brouard  4010: 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  4011: 
                   4012: {
                   4013:   /* Covariances of health expectancies eij and of total life expectancies according
                   4014:    to initial status i, ei. .
                   4015:   */
                   4016:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   4017:   int nhstepma, nstepma; /* Decreasing with age */
                   4018:   double age, agelim, hf;
                   4019:   double ***p3matp, ***p3matm, ***varhe;
                   4020:   double **dnewm,**doldm;
                   4021:   double *xp, *xm;
                   4022:   double **gp, **gm;
                   4023:   double ***gradg, ***trgradg;
                   4024:   int theta;
                   4025: 
                   4026:   double eip, vip;
                   4027: 
                   4028:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   4029:   xp=vector(1,npar);
                   4030:   xm=vector(1,npar);
                   4031:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   4032:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   4033:   
                   4034:   pstamp(ficresstdeij);
                   4035:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   4036:   fprintf(ficresstdeij,"# Age");
                   4037:   for(i=1; i<=nlstate;i++){
                   4038:     for(j=1; j<=nlstate;j++)
                   4039:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   4040:     fprintf(ficresstdeij," e%1d. ",i);
                   4041:   }
                   4042:   fprintf(ficresstdeij,"\n");
                   4043: 
                   4044:   pstamp(ficrescveij);
                   4045:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   4046:   fprintf(ficrescveij,"# Age");
                   4047:   for(i=1; i<=nlstate;i++)
                   4048:     for(j=1; j<=nlstate;j++){
                   4049:       cptj= (j-1)*nlstate+i;
                   4050:       for(i2=1; i2<=nlstate;i2++)
                   4051:        for(j2=1; j2<=nlstate;j2++){
                   4052:          cptj2= (j2-1)*nlstate+i2;
                   4053:          if(cptj2 <= cptj)
                   4054:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   4055:        }
                   4056:     }
                   4057:   fprintf(ficrescveij,"\n");
                   4058:   
                   4059:   if(estepm < stepm){
                   4060:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4061:   }
                   4062:   else  hstepm=estepm;   
                   4063:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   4064:    * This is mainly to measure the difference between two models: for example
                   4065:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   4066:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   4067:    * progression in between and thus overestimating or underestimating according
                   4068:    * to the curvature of the survival function. If, for the same date, we 
                   4069:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   4070:    * to compare the new estimate of Life expectancy with the same linear 
                   4071:    * hypothesis. A more precise result, taking into account a more precise
                   4072:    * curvature will be obtained if estepm is as small as stepm. */
                   4073: 
                   4074:   /* For example we decided to compute the life expectancy with the smallest unit */
                   4075:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   4076:      nhstepm is the number of hstepm from age to agelim 
                   4077:      nstepm is the number of stepm from age to agelin. 
                   4078:      Look at hpijx to understand the reason of that which relies in memory size
                   4079:      and note for a fixed period like estepm months */
                   4080:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   4081:      survival function given by stepm (the optimization length). Unfortunately it
                   4082:      means that if the survival funtion is printed only each two years of age and if
                   4083:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   4084:      results. So we changed our mind and took the option of the best precision.
                   4085:   */
                   4086:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   4087: 
                   4088:   /* If stepm=6 months */
                   4089:   /* nhstepm age range expressed in number of stepm */
                   4090:   agelim=AGESUP;
                   4091:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   4092:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   4093:   /* if (stepm >= YEARM) hstepm=1;*/
                   4094:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   4095:   
                   4096:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4097:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4098:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   4099:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   4100:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   4101:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   4102: 
                   4103:   for (age=bage; age<=fage; age ++){ 
                   4104:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   4105:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   4106:     /* if (stepm >= YEARM) hstepm=1;*/
                   4107:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   4108: 
                   4109:     /* If stepm=6 months */
                   4110:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   4111:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   4112:     
                   4113:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   4114: 
                   4115:     /* Computing  Variances of health expectancies */
                   4116:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   4117:        decrease memory allocation */
                   4118:     for(theta=1; theta <=npar; theta++){
                   4119:       for(i=1; i<=npar; i++){ 
                   4120:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4121:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
                   4122:       }
                   4123:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
                   4124:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
                   4125:   
                   4126:       for(j=1; j<= nlstate; j++){
                   4127:        for(i=1; i<=nlstate; i++){
                   4128:          for(h=0; h<=nhstepm-1; h++){
                   4129:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   4130:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   4131:          }
                   4132:        }
                   4133:       }
                   4134:      
                   4135:       for(ij=1; ij<= nlstate*nlstate; ij++)
                   4136:        for(h=0; h<=nhstepm-1; h++){
                   4137:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   4138:        }
                   4139:     }/* End theta */
                   4140:     
                   4141:     
                   4142:     for(h=0; h<=nhstepm-1; h++)
                   4143:       for(j=1; j<=nlstate*nlstate;j++)
                   4144:        for(theta=1; theta <=npar; theta++)
                   4145:          trgradg[h][j][theta]=gradg[h][theta][j];
                   4146:     
                   4147: 
                   4148:      for(ij=1;ij<=nlstate*nlstate;ij++)
                   4149:       for(ji=1;ji<=nlstate*nlstate;ji++)
                   4150:        varhe[ij][ji][(int)age] =0.;
                   4151: 
                   4152:      printf("%d|",(int)age);fflush(stdout);
                   4153:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   4154:      for(h=0;h<=nhstepm-1;h++){
                   4155:       for(k=0;k<=nhstepm-1;k++){
                   4156:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   4157:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   4158:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   4159:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   4160:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
                   4161:       }
                   4162:     }
                   4163: 
                   4164:     /* Computing expectancies */
                   4165:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   4166:     for(i=1; i<=nlstate;i++)
                   4167:       for(j=1; j<=nlstate;j++)
                   4168:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   4169:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
                   4170:          
                   4171:          /* 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]);*/
                   4172: 
                   4173:        }
                   4174: 
                   4175:     fprintf(ficresstdeij,"%3.0f",age );
                   4176:     for(i=1; i<=nlstate;i++){
                   4177:       eip=0.;
                   4178:       vip=0.;
                   4179:       for(j=1; j<=nlstate;j++){
                   4180:        eip += eij[i][j][(int)age];
                   4181:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   4182:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   4183:        fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
                   4184:       }
                   4185:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   4186:     }
                   4187:     fprintf(ficresstdeij,"\n");
                   4188: 
                   4189:     fprintf(ficrescveij,"%3.0f",age );
                   4190:     for(i=1; i<=nlstate;i++)
                   4191:       for(j=1; j<=nlstate;j++){
                   4192:        cptj= (j-1)*nlstate+i;
                   4193:        for(i2=1; i2<=nlstate;i2++)
                   4194:          for(j2=1; j2<=nlstate;j2++){
                   4195:            cptj2= (j2-1)*nlstate+i2;
                   4196:            if(cptj2 <= cptj)
                   4197:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   4198:          }
                   4199:       }
                   4200:     fprintf(ficrescveij,"\n");
                   4201:    
                   4202:   }
                   4203:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   4204:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   4205:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   4206:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   4207:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4208:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4209:   printf("\n");
                   4210:   fprintf(ficlog,"\n");
                   4211: 
                   4212:   free_vector(xm,1,npar);
                   4213:   free_vector(xp,1,npar);
                   4214:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   4215:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   4216:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   4217: }
                   4218: 
                   4219: /************ Variance ******************/
1.209     brouard  4220:  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.126     brouard  4221: {
                   4222:   /* Variance of health expectancies */
                   4223:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   4224:   /* double **newm;*/
1.169     brouard  4225:   /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
                   4226:   
                   4227:   int movingaverage();
1.126     brouard  4228:   double **dnewm,**doldm;
                   4229:   double **dnewmp,**doldmp;
                   4230:   int i, j, nhstepm, hstepm, h, nstepm ;
1.164     brouard  4231:   int k;
1.126     brouard  4232:   double *xp;
                   4233:   double **gp, **gm;  /* for var eij */
                   4234:   double ***gradg, ***trgradg; /*for var eij */
                   4235:   double **gradgp, **trgradgp; /* for var p point j */
                   4236:   double *gpp, *gmp; /* for var p point j */
                   4237:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   4238:   double ***p3mat;
                   4239:   double age,agelim, hf;
                   4240:   double ***mobaverage;
                   4241:   int theta;
                   4242:   char digit[4];
                   4243:   char digitp[25];
                   4244: 
                   4245:   char fileresprobmorprev[FILENAMELENGTH];
                   4246: 
                   4247:   if(popbased==1){
                   4248:     if(mobilav!=0)
1.201     brouard  4249:       strcpy(digitp,"-POPULBASED-MOBILAV_");
                   4250:     else strcpy(digitp,"-POPULBASED-NOMOBIL_");
1.126     brouard  4251:   }
                   4252:   else 
1.201     brouard  4253:     strcpy(digitp,"-STABLBASED_");
1.126     brouard  4254: 
                   4255:   if (mobilav!=0) {
                   4256:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4257:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   4258:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   4259:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   4260:     }
                   4261:   }
                   4262: 
1.201     brouard  4263:   strcpy(fileresprobmorprev,"PRMORPREV-"); 
1.126     brouard  4264:   sprintf(digit,"%-d",ij);
                   4265:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   4266:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   4267:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
1.202     brouard  4268:   strcat(fileresprobmorprev,fileresu);
1.126     brouard  4269:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   4270:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   4271:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   4272:   }
                   4273:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   4274:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   4275:   pstamp(ficresprobmorprev);
                   4276:   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);
                   4277:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   4278:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   4279:     fprintf(ficresprobmorprev," p.%-d SE",j);
                   4280:     for(i=1; i<=nlstate;i++)
                   4281:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   4282:   }  
                   4283:   fprintf(ficresprobmorprev,"\n");
1.208     brouard  4284:   
1.126     brouard  4285:   fprintf(ficgp,"\n# Routine varevsij");
1.200     brouard  4286:   fprintf(ficgp,"\nunset title \n");
                   4287: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
1.126     brouard  4288:   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");
                   4289:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   4290: /*   } */
                   4291:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4292:   pstamp(ficresvij);
                   4293:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   4294:   if(popbased==1)
1.128     brouard  4295:     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);
1.126     brouard  4296:   else
                   4297:     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   4298:   fprintf(ficresvij,"# Age");
                   4299:   for(i=1; i<=nlstate;i++)
                   4300:     for(j=1; j<=nlstate;j++)
                   4301:       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   4302:   fprintf(ficresvij,"\n");
                   4303: 
                   4304:   xp=vector(1,npar);
                   4305:   dnewm=matrix(1,nlstate,1,npar);
                   4306:   doldm=matrix(1,nlstate,1,nlstate);
                   4307:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   4308:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4309: 
                   4310:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   4311:   gpp=vector(nlstate+1,nlstate+ndeath);
                   4312:   gmp=vector(nlstate+1,nlstate+ndeath);
                   4313:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   4314:   
                   4315:   if(estepm < stepm){
                   4316:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4317:   }
                   4318:   else  hstepm=estepm;   
                   4319:   /* For example we decided to compute the life expectancy with the smallest unit */
                   4320:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   4321:      nhstepm is the number of hstepm from age to agelim 
1.208     brouard  4322:      nstepm is the number of stepm from age to agelim. 
1.209     brouard  4323:      Look at function hpijx to understand why because of memory size limitations, 
1.208     brouard  4324:      we decided (b) to get a life expectancy respecting the most precise curvature of the
1.126     brouard  4325:      survival function given by stepm (the optimization length). Unfortunately it
                   4326:      means that if the survival funtion is printed every two years of age and if
                   4327:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   4328:      results. So we changed our mind and took the option of the best precision.
                   4329:   */
                   4330:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   4331:   agelim = AGESUP;
                   4332:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   4333:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   4334:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   4335:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4336:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   4337:     gp=matrix(0,nhstepm,1,nlstate);
                   4338:     gm=matrix(0,nhstepm,1,nlstate);
                   4339: 
                   4340: 
                   4341:     for(theta=1; theta <=npar; theta++){
                   4342:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   4343:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4344:       }
1.209     brouard  4345: 
                   4346:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
1.126     brouard  4347: 
                   4348:       if (popbased==1) {
                   4349:        if(mobilav ==0){
                   4350:          for(i=1; i<=nlstate;i++)
                   4351:            prlim[i][i]=probs[(int)age][i][ij];
                   4352:        }else{ /* mobilav */ 
                   4353:          for(i=1; i<=nlstate;i++)
                   4354:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   4355:        }
                   4356:       }
                   4357:   
1.209     brouard  4358:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  /* Returns p3mat[i][j][h] for h=1 to nhstepm */
1.126     brouard  4359:       for(j=1; j<= nlstate; j++){
                   4360:        for(h=0; h<=nhstepm; h++){
                   4361:          for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   4362:            gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   4363:        }
                   4364:       }
1.209     brouard  4365:       /* Next for computing probability of death (h=1 means
1.126     brouard  4366:          computed over hstepm matrices product = hstepm*stepm months) 
                   4367:          as a weighted average of prlim.
                   4368:       */
                   4369:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4370:        for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   4371:          gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   4372:       }    
                   4373:       /* end probability of death */
                   4374: 
                   4375:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   4376:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.209     brouard  4377: 
                   4378:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij);
1.126     brouard  4379:  
                   4380:       if (popbased==1) {
                   4381:        if(mobilav ==0){
                   4382:          for(i=1; i<=nlstate;i++)
                   4383:            prlim[i][i]=probs[(int)age][i][ij];
                   4384:        }else{ /* mobilav */ 
                   4385:          for(i=1; i<=nlstate;i++)
                   4386:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   4387:        }
                   4388:       }
                   4389: 
1.209     brouard  4390:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   4391: 
1.128     brouard  4392:       for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
1.126     brouard  4393:        for(h=0; h<=nhstepm; h++){
                   4394:          for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   4395:            gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   4396:        }
                   4397:       }
                   4398:       /* This for computing probability of death (h=1 means
                   4399:          computed over hstepm matrices product = hstepm*stepm months) 
                   4400:          as a weighted average of prlim.
                   4401:       */
                   4402:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4403:        for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   4404:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   4405:       }    
                   4406:       /* end probability of death */
                   4407: 
                   4408:       for(j=1; j<= nlstate; j++) /* vareij */
                   4409:        for(h=0; h<=nhstepm; h++){
                   4410:          gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   4411:        }
                   4412: 
                   4413:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   4414:        gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   4415:       }
                   4416: 
                   4417:     } /* End theta */
                   4418: 
                   4419:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   4420: 
                   4421:     for(h=0; h<=nhstepm; h++) /* veij */
                   4422:       for(j=1; j<=nlstate;j++)
                   4423:        for(theta=1; theta <=npar; theta++)
                   4424:          trgradg[h][j][theta]=gradg[h][theta][j];
                   4425: 
                   4426:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   4427:       for(theta=1; theta <=npar; theta++)
                   4428:        trgradgp[j][theta]=gradgp[theta][j];
                   4429:   
                   4430: 
                   4431:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   4432:     for(i=1;i<=nlstate;i++)
                   4433:       for(j=1;j<=nlstate;j++)
                   4434:        vareij[i][j][(int)age] =0.;
                   4435: 
                   4436:     for(h=0;h<=nhstepm;h++){
                   4437:       for(k=0;k<=nhstepm;k++){
                   4438:        matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   4439:        matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   4440:        for(i=1;i<=nlstate;i++)
                   4441:          for(j=1;j<=nlstate;j++)
                   4442:            vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   4443:       }
                   4444:     }
                   4445:   
                   4446:     /* pptj */
                   4447:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   4448:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   4449:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   4450:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   4451:        varppt[j][i]=doldmp[j][i];
                   4452:     /* end ppptj */
                   4453:     /*  x centered again */
1.209     brouard  4454: 
                   4455:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij);
1.126     brouard  4456:  
                   4457:     if (popbased==1) {
                   4458:       if(mobilav ==0){
                   4459:        for(i=1; i<=nlstate;i++)
                   4460:          prlim[i][i]=probs[(int)age][i][ij];
                   4461:       }else{ /* mobilav */ 
                   4462:        for(i=1; i<=nlstate;i++)
                   4463:          prlim[i][i]=mobaverage[(int)age][i][ij];
                   4464:       }
                   4465:     }
                   4466:              
                   4467:     /* This for computing probability of death (h=1 means
                   4468:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   4469:        as a weighted average of prlim.
                   4470:     */
1.209     brouard  4471:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
1.126     brouard  4472:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4473:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   4474:        gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   4475:     }    
                   4476:     /* end probability of death */
                   4477: 
                   4478:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   4479:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   4480:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   4481:       for(i=1; i<=nlstate;i++){
                   4482:        fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   4483:       }
                   4484:     } 
                   4485:     fprintf(ficresprobmorprev,"\n");
                   4486: 
                   4487:     fprintf(ficresvij,"%.0f ",age );
                   4488:     for(i=1; i<=nlstate;i++)
                   4489:       for(j=1; j<=nlstate;j++){
                   4490:        fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   4491:       }
                   4492:     fprintf(ficresvij,"\n");
                   4493:     free_matrix(gp,0,nhstepm,1,nlstate);
                   4494:     free_matrix(gm,0,nhstepm,1,nlstate);
                   4495:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   4496:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   4497:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4498:   } /* End age */
                   4499:   free_vector(gpp,nlstate+1,nlstate+ndeath);
                   4500:   free_vector(gmp,nlstate+1,nlstate+ndeath);
                   4501:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   4502:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.199     brouard  4503:   /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   4504:   fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
1.126     brouard  4505:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131     brouard  4506:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.201     brouard  4507:   fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  4508: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   4509: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   4510: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145     brouard  4511:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
1.170     brouard  4512:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
1.145     brouard  4513:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126     brouard  4514:   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
1.201     brouard  4515:   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);
1.199     brouard  4516:   /*  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  4517: */
1.199     brouard  4518: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
1.201     brouard  4519:   fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  4520: 
                   4521:   free_vector(xp,1,npar);
                   4522:   free_matrix(doldm,1,nlstate,1,nlstate);
                   4523:   free_matrix(dnewm,1,nlstate,1,npar);
                   4524:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4525:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   4526:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4527:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4528:   fclose(ficresprobmorprev);
                   4529:   fflush(ficgp);
                   4530:   fflush(fichtm); 
                   4531: }  /* end varevsij */
                   4532: 
                   4533: /************ Variance of prevlim ******************/
1.209     brouard  4534:  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  4535: {
1.205     brouard  4536:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  4537:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  4538: 
1.126     brouard  4539:   double **dnewm,**doldm;
                   4540:   int i, j, nhstepm, hstepm;
                   4541:   double *xp;
                   4542:   double *gp, *gm;
                   4543:   double **gradg, **trgradg;
1.208     brouard  4544:   double **mgm, **mgp;
1.126     brouard  4545:   double age,agelim;
                   4546:   int theta;
                   4547:   
                   4548:   pstamp(ficresvpl);
                   4549:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
                   4550:   fprintf(ficresvpl,"# Age");
                   4551:   for(i=1; i<=nlstate;i++)
                   4552:       fprintf(ficresvpl," %1d-%1d",i,i);
                   4553:   fprintf(ficresvpl,"\n");
                   4554: 
                   4555:   xp=vector(1,npar);
                   4556:   dnewm=matrix(1,nlstate,1,npar);
                   4557:   doldm=matrix(1,nlstate,1,nlstate);
                   4558:   
                   4559:   hstepm=1*YEARM; /* Every year of age */
                   4560:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   4561:   agelim = AGESUP;
                   4562:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   4563:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   4564:     if (stepm >= YEARM) hstepm=1;
                   4565:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   4566:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  4567:     mgp=matrix(1,npar,1,nlstate);
                   4568:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  4569:     gp=vector(1,nlstate);
                   4570:     gm=vector(1,nlstate);
                   4571: 
                   4572:     for(theta=1; theta <=npar; theta++){
                   4573:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   4574:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4575:       }
1.209     brouard  4576:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
                   4577:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
                   4578:       else
                   4579:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
1.208     brouard  4580:       for(i=1;i<=nlstate;i++){
1.126     brouard  4581:        gp[i] = prlim[i][i];
1.208     brouard  4582:        mgp[theta][i] = prlim[i][i];
                   4583:       }
1.126     brouard  4584:       for(i=1; i<=npar; i++) /* Computes gradient */
                   4585:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.209     brouard  4586:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
                   4587:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
                   4588:       else
                   4589:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij);
1.208     brouard  4590:       for(i=1;i<=nlstate;i++){
1.126     brouard  4591:        gm[i] = prlim[i][i];
1.208     brouard  4592:        mgm[theta][i] = prlim[i][i];
                   4593:       }
1.126     brouard  4594:       for(i=1;i<=nlstate;i++)
                   4595:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  4596:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  4597:     } /* End theta */
                   4598: 
                   4599:     trgradg =matrix(1,nlstate,1,npar);
                   4600: 
                   4601:     for(j=1; j<=nlstate;j++)
                   4602:       for(theta=1; theta <=npar; theta++)
                   4603:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  4604:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   4605:     /*   printf("\nmgm mgp %d ",(int)age); */
                   4606:     /*   for(j=1; j<=nlstate;j++){ */
                   4607:     /*         printf(" %d ",j); */
                   4608:     /*         for(theta=1; theta <=npar; theta++) */
                   4609:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   4610:     /*         printf("\n "); */
                   4611:     /*   } */
                   4612:     /* } */
                   4613:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   4614:     /*   printf("\n gradg %d ",(int)age); */
                   4615:     /*   for(j=1; j<=nlstate;j++){ */
                   4616:     /*         printf("%d ",j); */
                   4617:     /*         for(theta=1; theta <=npar; theta++) */
                   4618:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   4619:     /*         printf("\n "); */
                   4620:     /*   } */
                   4621:     /* } */
1.126     brouard  4622: 
                   4623:     for(i=1;i<=nlstate;i++)
                   4624:       varpl[i][(int)age] =0.;
1.209     brouard  4625:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.205     brouard  4626:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   4627:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   4628:     }else{
1.126     brouard  4629:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   4630:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  4631:     }
1.126     brouard  4632:     for(i=1;i<=nlstate;i++)
                   4633:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   4634: 
                   4635:     fprintf(ficresvpl,"%.0f ",age );
                   4636:     for(i=1; i<=nlstate;i++)
                   4637:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   4638:     fprintf(ficresvpl,"\n");
                   4639:     free_vector(gp,1,nlstate);
                   4640:     free_vector(gm,1,nlstate);
1.208     brouard  4641:     free_matrix(mgm,1,npar,1,nlstate);
                   4642:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  4643:     free_matrix(gradg,1,npar,1,nlstate);
                   4644:     free_matrix(trgradg,1,nlstate,1,npar);
                   4645:   } /* End age */
                   4646: 
                   4647:   free_vector(xp,1,npar);
                   4648:   free_matrix(doldm,1,nlstate,1,npar);
                   4649:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   4650: 
                   4651: }
                   4652: 
                   4653: /************ Variance of one-step probabilities  ******************/
                   4654: 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[])
                   4655: {
1.164     brouard  4656:   int i, j=0,  k1, l1, tj;
1.126     brouard  4657:   int k2, l2, j1,  z1;
1.164     brouard  4658:   int k=0, l;
1.145     brouard  4659:   int first=1, first1, first2;
1.126     brouard  4660:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   4661:   double **dnewm,**doldm;
                   4662:   double *xp;
                   4663:   double *gp, *gm;
                   4664:   double **gradg, **trgradg;
                   4665:   double **mu;
1.164     brouard  4666:   double age, cov[NCOVMAX+1];
1.126     brouard  4667:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   4668:   int theta;
                   4669:   char fileresprob[FILENAMELENGTH];
                   4670:   char fileresprobcov[FILENAMELENGTH];
                   4671:   char fileresprobcor[FILENAMELENGTH];
                   4672:   double ***varpij;
                   4673: 
1.201     brouard  4674:   strcpy(fileresprob,"PROB_"); 
1.126     brouard  4675:   strcat(fileresprob,fileres);
                   4676:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   4677:     printf("Problem with resultfile: %s\n", fileresprob);
                   4678:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   4679:   }
1.201     brouard  4680:   strcpy(fileresprobcov,"PROBCOV_"); 
1.202     brouard  4681:   strcat(fileresprobcov,fileresu);
1.126     brouard  4682:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   4683:     printf("Problem with resultfile: %s\n", fileresprobcov);
                   4684:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   4685:   }
1.201     brouard  4686:   strcpy(fileresprobcor,"PROBCOR_"); 
1.202     brouard  4687:   strcat(fileresprobcor,fileresu);
1.126     brouard  4688:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   4689:     printf("Problem with resultfile: %s\n", fileresprobcor);
                   4690:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   4691:   }
                   4692:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   4693:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   4694:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   4695:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   4696:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   4697:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   4698:   pstamp(ficresprob);
                   4699:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   4700:   fprintf(ficresprob,"# Age");
                   4701:   pstamp(ficresprobcov);
                   4702:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   4703:   fprintf(ficresprobcov,"# Age");
                   4704:   pstamp(ficresprobcor);
                   4705:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   4706:   fprintf(ficresprobcor,"# Age");
                   4707: 
                   4708: 
                   4709:   for(i=1; i<=nlstate;i++)
                   4710:     for(j=1; j<=(nlstate+ndeath);j++){
                   4711:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   4712:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   4713:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   4714:     }  
                   4715:  /* fprintf(ficresprob,"\n");
                   4716:   fprintf(ficresprobcov,"\n");
                   4717:   fprintf(ficresprobcor,"\n");
                   4718:  */
1.131     brouard  4719:   xp=vector(1,npar);
1.126     brouard  4720:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   4721:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   4722:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   4723:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   4724:   first=1;
                   4725:   fprintf(ficgp,"\n# Routine varprob");
                   4726:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   4727:   fprintf(fichtm,"\n");
                   4728: 
1.200     brouard  4729:   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);
1.197     brouard  4730:   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);
                   4731:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  4732: and drawn. It helps understanding how is the covariance between two incidences.\
                   4733:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
                   4734:   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. \
                   4735: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   4736: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   4737: standard deviations wide on each axis. <br>\
                   4738:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   4739:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   4740: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   4741: 
                   4742:   cov[1]=1;
1.145     brouard  4743:   /* tj=cptcoveff; */
                   4744:   tj = (int) pow(2,cptcoveff);
1.126     brouard  4745:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   4746:   j1=0;
1.145     brouard  4747:   for(j1=1; j1<=tj;j1++){
                   4748:     /*for(i1=1; i1<=ncodemax[t];i1++){ */
                   4749:     /*j1++;*/
1.126     brouard  4750:       if  (cptcovn>0) {
                   4751:        fprintf(ficresprob, "\n#********** Variable "); 
1.198     brouard  4752:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4753:        fprintf(ficresprob, "**********\n#\n");
                   4754:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.198     brouard  4755:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4756:        fprintf(ficresprobcov, "**********\n#\n");
                   4757:        
                   4758:        fprintf(ficgp, "\n#********** Variable "); 
1.198     brouard  4759:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4760:        fprintf(ficgp, "**********\n#\n");
                   4761:        
                   4762:        
                   4763:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.198     brouard  4764:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4765:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4766:        
                   4767:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.198     brouard  4768:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4769:        fprintf(ficresprobcor, "**********\n#");    
                   4770:       }
                   4771:       
1.145     brouard  4772:       gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   4773:       trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   4774:       gp=vector(1,(nlstate)*(nlstate+ndeath));
                   4775:       gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126     brouard  4776:       for (age=bage; age<=fage; age ++){ 
                   4777:        cov[2]=age;
1.187     brouard  4778:        if(nagesqr==1)
                   4779:          cov[3]= age*age;
1.126     brouard  4780:        for (k=1; k<=cptcovn;k++) {
1.200     brouard  4781:          cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
                   4782:          /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
1.145     brouard  4783:                                                         * 1  1 1 1 1
                   4784:                                                         * 2  2 1 1 1
                   4785:                                                         * 3  1 2 1 1
                   4786:                                                         */
                   4787:          /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126     brouard  4788:        }
1.186     brouard  4789:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  4790:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
1.126     brouard  4791:        for (k=1; k<=cptcovprod;k++)
1.200     brouard  4792:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.126     brouard  4793:        
                   4794:     
                   4795:        for(theta=1; theta <=npar; theta++){
                   4796:          for(i=1; i<=npar; i++)
                   4797:            xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
                   4798:          
                   4799:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   4800:          
                   4801:          k=0;
                   4802:          for(i=1; i<= (nlstate); i++){
                   4803:            for(j=1; j<=(nlstate+ndeath);j++){
                   4804:              k=k+1;
                   4805:              gp[k]=pmmij[i][j];
                   4806:            }
                   4807:          }
                   4808:          
                   4809:          for(i=1; i<=npar; i++)
                   4810:            xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
                   4811:     
                   4812:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   4813:          k=0;
                   4814:          for(i=1; i<=(nlstate); i++){
                   4815:            for(j=1; j<=(nlstate+ndeath);j++){
                   4816:              k=k+1;
                   4817:              gm[k]=pmmij[i][j];
                   4818:            }
                   4819:          }
                   4820:      
                   4821:          for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   4822:            gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   4823:        }
                   4824: 
                   4825:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   4826:          for(theta=1; theta <=npar; theta++)
                   4827:            trgradg[j][theta]=gradg[theta][j];
                   4828:        
                   4829:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   4830:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
                   4831: 
                   4832:        pmij(pmmij,cov,ncovmodel,x,nlstate);
                   4833:        
                   4834:        k=0;
                   4835:        for(i=1; i<=(nlstate); i++){
                   4836:          for(j=1; j<=(nlstate+ndeath);j++){
                   4837:            k=k+1;
                   4838:            mu[k][(int) age]=pmmij[i][j];
                   4839:          }
                   4840:        }
                   4841:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   4842:          for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   4843:            varpij[i][j][(int)age] = doldm[i][j];
                   4844: 
                   4845:        /*printf("\n%d ",(int)age);
                   4846:          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   4847:          printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   4848:          fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   4849:          }*/
                   4850: 
                   4851:        fprintf(ficresprob,"\n%d ",(int)age);
                   4852:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   4853:        fprintf(ficresprobcor,"\n%d ",(int)age);
                   4854: 
                   4855:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   4856:          fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   4857:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   4858:          fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   4859:          fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   4860:        }
                   4861:        i=0;
                   4862:        for (k=1; k<=(nlstate);k++){
                   4863:          for (l=1; l<=(nlstate+ndeath);l++){ 
1.145     brouard  4864:            i++;
1.126     brouard  4865:            fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   4866:            fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   4867:            for (j=1; j<=i;j++){
1.145     brouard  4868:              /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126     brouard  4869:              fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   4870:              fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   4871:            }
                   4872:          }
                   4873:        }/* end of loop for state */
                   4874:       } /* end of loop for age */
1.145     brouard  4875:       free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   4876:       free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   4877:       free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   4878:       free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   4879:       
1.126     brouard  4880:       /* Confidence intervalle of pij  */
                   4881:       /*
1.131     brouard  4882:        fprintf(ficgp,"\nunset parametric;unset label");
1.126     brouard  4883:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   4884:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   4885:        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);
                   4886:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   4887:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   4888:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   4889:       */
                   4890: 
                   4891:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145     brouard  4892:       first1=1;first2=2;
1.126     brouard  4893:       for (k2=1; k2<=(nlstate);k2++){
                   4894:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   4895:          if(l2==k2) continue;
                   4896:          j=(k2-1)*(nlstate+ndeath)+l2;
                   4897:          for (k1=1; k1<=(nlstate);k1++){
                   4898:            for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   4899:              if(l1==k1) continue;
                   4900:              i=(k1-1)*(nlstate+ndeath)+l1;
                   4901:              if(i<=j) continue;
                   4902:              for (age=bage; age<=fage; age ++){ 
                   4903:                if ((int)age %5==0){
                   4904:                  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   4905:                  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   4906:                  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   4907:                  mu1=mu[i][(int) age]/stepm*YEARM ;
                   4908:                  mu2=mu[j][(int) age]/stepm*YEARM;
                   4909:                  c12=cv12/sqrt(v1*v2);
                   4910:                  /* Computing eigen value of matrix of covariance */
                   4911:                  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4912:                  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135     brouard  4913:                  if ((lc2 <0) || (lc1 <0) ){
1.145     brouard  4914:                    if(first2==1){
                   4915:                      first1=0;
                   4916:                    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);
                   4917:                    }
                   4918:                    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);
                   4919:                    /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   4920:                    /* lc2=fabs(lc2); */
1.135     brouard  4921:                  }
                   4922: 
1.126     brouard  4923:                  /* Eigen vectors */
                   4924:                  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   4925:                  /*v21=sqrt(1.-v11*v11); *//* error */
                   4926:                  v21=(lc1-v1)/cv12*v11;
                   4927:                  v12=-v21;
                   4928:                  v22=v11;
                   4929:                  tnalp=v21/v11;
                   4930:                  if(first1==1){
                   4931:                    first1=0;
                   4932:                    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);
                   4933:                  }
                   4934:                  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);
                   4935:                  /*printf(fignu*/
                   4936:                  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   4937:                  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   4938:                  if(first==1){
                   4939:                    first=0;
1.200     brouard  4940:                    fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
1.126     brouard  4941:                    fprintf(ficgp,"\nset parametric;unset label");
                   4942:                    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);
1.199     brouard  4943:                    fprintf(ficgp,"\nset ter svg size 640, 480");
1.126     brouard  4944:                    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.201     brouard  4945:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">\
                   4946: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
                   4947:                            subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,\
                   4948:                            subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   4949:                    fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
1.126     brouard  4950:                    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
1.201     brouard  4951:                    fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
1.126     brouard  4952:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4953:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4954:                    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",\
                   4955:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4956:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4957:                  }else{
                   4958:                    first=0;
                   4959:                    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   4960:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4961:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4962:                    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",\
                   4963:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4964:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4965:                  }/* if first */
                   4966:                } /* age mod 5 */
                   4967:              } /* end loop age */
1.201     brouard  4968:              fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
1.126     brouard  4969:              first=1;
                   4970:            } /*l12 */
                   4971:          } /* k12 */
                   4972:        } /*l1 */
                   4973:       }/* k1 */
1.169     brouard  4974:       /* } */ /* loop covariates */
1.126     brouard  4975:   }
                   4976:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   4977:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   4978:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   4979:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   4980:   free_vector(xp,1,npar);
                   4981:   fclose(ficresprob);
                   4982:   fclose(ficresprobcov);
                   4983:   fclose(ficresprobcor);
                   4984:   fflush(ficgp);
                   4985:   fflush(fichtmcov);
                   4986: }
                   4987: 
                   4988: 
                   4989: /******************* Printing html file ***********/
1.201     brouard  4990: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  4991:                  int lastpass, int stepm, int weightopt, char model[],\
                   4992:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.211     brouard  4993:                  int popforecast, int prevfcast, int estepm ,          \
1.213     brouard  4994:                  double jprev1, double mprev1,double anprev1, double dateprev1, \
                   4995:                  double jprev2, double mprev2,double anprev2, double dateprev2){
1.126     brouard  4996:   int jj1, k1, i1, cpt;
                   4997: 
                   4998:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   4999:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   5000: </ul>");
1.214     brouard  5001:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   5002:    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",
                   5003:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
                   5004:    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  5005:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   5006:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  5007:    fprintf(fichtm,"\
                   5008:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  5009:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  5010:    fprintf(fichtm,"\
                   5011:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  5012:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  5013:    fprintf(fichtm,"\
1.211     brouard  5014:  - (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  5015:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  5016:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  5017:    if(prevfcast==1){
                   5018:      fprintf(fichtm,"\
                   5019:  - Prevalence projections by age and states:                           \
1.201     brouard  5020:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  5021:    }
1.126     brouard  5022: 
                   5023: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
                   5024: 
1.145     brouard  5025:  m=pow(2,cptcoveff);
1.126     brouard  5026:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   5027: 
                   5028:  jj1=0;
                   5029:  for(k1=1; k1<=m;k1++){
1.192     brouard  5030:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126     brouard  5031:      jj1++;
                   5032:      if (cptcovn > 0) {
                   5033:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.192     brouard  5034:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.198     brouard  5035:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
                   5036:         printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout);
1.192     brouard  5037:        }
1.126     brouard  5038:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   5039:      }
1.201     brouard  5040:      /* aij, bij */
1.211     brouard  5041:      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> \
                   5042: <img src=\"%s_%d-1.svg\">",model,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
1.126     brouard  5043:      /* Pij */
1.211     brouard  5044:      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  5045: <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);     
1.126     brouard  5046:      /* Quasi-incidences */
1.211     brouard  5047:      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.201     brouard  5048:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too,\
1.211     brouard  5049:  incidence (rates) are the limit when h tends to zero of the ratio of the probability  <sub>h</sub>P<sub>ij</sub> \
                   5050: 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  5051: <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1); 
                   5052:      /* Survival functions (period) in state j */
                   5053:      for(cpt=1; cpt<=nlstate;cpt++){
                   5054:        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> \
                   5055: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1);
                   5056:      }
                   5057:      /* State specific survival functions (period) */
                   5058:      for(cpt=1; cpt<=nlstate;cpt++){
1.208     brouard  5059:        fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
1.201     brouard  5060:  Or probability to survive in various states (1 to %d) being in state %d at different ages.\
                   5061:  <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);
                   5062:      }
                   5063:      /* Period (stable) prevalence in each health state */
                   5064:      for(cpt=1; cpt<=nlstate;cpt++){
                   5065:        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> \
                   5066: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1);
                   5067:      }
1.211     brouard  5068:     if(prevfcast==1){
                   5069:       /* Projection of prevalence up to period (stable) prevalence in each health state */
                   5070:       for(cpt=1; cpt<=nlstate;cpt++){
1.214     brouard  5071:        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  5072: <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.211     brouard  5073:       }
                   5074:     }
                   5075: 
1.126     brouard  5076:      for(cpt=1; cpt<=nlstate;cpt++) {
1.205     brouard  5077:        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  5078: <img src=\"%s_%d%d.svg\">",cpt,nlstate,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1);
1.126     brouard  5079:      }
1.192     brouard  5080:    /* } /\* end i1 *\/ */
1.126     brouard  5081:  }/* End k1 */
                   5082:  fprintf(fichtm,"</ul>");
                   5083: 
                   5084:  fprintf(fichtm,"\
                   5085: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  5086:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  5087:  - 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  5088: But because parameters are usually highly correlated (a higher incidence of disability \
                   5089: and a higher incidence of recovery can give very close observed transition) it might \
                   5090: be very useful to look not only at linear confidence intervals estimated from the \
                   5091: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   5092: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   5093: covariance matrix of the one-step probabilities. \
                   5094: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  5095: 
1.193     brouard  5096:  fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  5097:         subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
1.126     brouard  5098:  fprintf(fichtm,"\
                   5099:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  5100:         subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  5101: 
                   5102:  fprintf(fichtm,"\
                   5103:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  5104:         subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
1.126     brouard  5105:  fprintf(fichtm,"\
                   5106:  - 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): \
                   5107:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  5108:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.126     brouard  5109:  fprintf(fichtm,"\
                   5110:  - (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): \
                   5111:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  5112:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.126     brouard  5113:  fprintf(fichtm,"\
1.128     brouard  5114:  - 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.201     brouard  5115:         estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
1.126     brouard  5116:  fprintf(fichtm,"\
1.128     brouard  5117:  - 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.201     brouard  5118:         estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
1.126     brouard  5119:  fprintf(fichtm,"\
                   5120:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.201     brouard  5121:         subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  5122: 
                   5123: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   5124: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   5125: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   5126: /*     <br>",fileres,fileres,fileres,fileres); */
                   5127: /*  else  */
                   5128: /*    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); */
                   5129:  fflush(fichtm);
                   5130:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
                   5131: 
1.145     brouard  5132:  m=pow(2,cptcoveff);
1.126     brouard  5133:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   5134: 
                   5135:  jj1=0;
                   5136:  for(k1=1; k1<=m;k1++){
1.192     brouard  5137:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126     brouard  5138:      jj1++;
                   5139:      if (cptcovn > 0) {
                   5140:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   5141:        for (cpt=1; cpt<=cptcoveff;cpt++) 
1.198     brouard  5142:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
1.126     brouard  5143:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   5144:      }
                   5145:      for(cpt=1; cpt<=nlstate;cpt++) {
                   5146:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.205     brouard  5147: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d%d.svg\"> %s_%d-%d.svg <br>\
                   5148: <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  5149:      }
                   5150:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  5151: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   5152: true period expectancies (those weighted with period prevalences are also\
                   5153:  drawn in addition to the population based expectancies computed using\
1.205     brouard  5154:  observed and cahotic prevalences:  <a href=\"%s_%d.svg\">%s_%d.svg<br>\
                   5155: <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);
1.192     brouard  5156:    /* } /\* end i1 *\/ */
1.126     brouard  5157:  }/* End k1 */
                   5158:  fprintf(fichtm,"</ul>");
                   5159:  fflush(fichtm);
                   5160: }
                   5161: 
                   5162: /******************* Gnuplot file **************/
1.211     brouard  5163:     void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , int prevfcast, char pathc[], double p[]){
1.126     brouard  5164: 
                   5165:   char dirfileres[132],optfileres[132];
1.164     brouard  5166:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.211     brouard  5167:   int lv=0, vlv=0, kl=0;
1.130     brouard  5168:   int ng=0;
1.201     brouard  5169:   int vpopbased;
1.126     brouard  5170: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   5171: /*     printf("Problem with file %s",optionfilegnuplot); */
                   5172: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   5173: /*   } */
                   5174: 
                   5175:   /*#ifdef windows */
                   5176:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   5177:     /*#endif */
                   5178:   m=pow(2,cptcoveff);
                   5179: 
1.202     brouard  5180:   /* Contribution to likelihood */
                   5181:   /* Plot the probability implied in the likelihood */
                   5182:     fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   5183:     fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   5184:     /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
1.205     brouard  5185:     fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  5186: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  5187:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   5188: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
                   5189:     /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
1.204     brouard  5190:     fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
1.214     brouard  5191:     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));
1.204     brouard  5192:     fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
1.214     brouard  5193:     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));
1.204     brouard  5194:     for (i=1; i<= nlstate ; i ++) {
                   5195:       fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
1.205     brouard  5196:       fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
1.214     brouard  5197:       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);
1.204     brouard  5198:       for (j=2; j<= nlstate+ndeath ; j ++) {
1.214     brouard  5199:        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);
1.204     brouard  5200:       }
                   5201:       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   5202:     }
                   5203:     /* 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 */             
                   5204:     /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   5205:     /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
1.203     brouard  5206:     fprintf(ficgp,"\nset out;unset log\n");
1.202     brouard  5207:     /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
                   5208: 
1.126     brouard  5209:   strcpy(dirfileres,optionfilefiname);
                   5210:   strcpy(optfileres,"vpl");
                   5211:  /* 1eme*/
1.211     brouard  5212:   for (cpt=1; cpt<= nlstate ; cpt ++) { /* For each live state */
                   5213:     for (k1=1; k1<= m ; k1 ++) { /* For each combination of covariate */
                   5214:       /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
                   5215:       fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files ");
                   5216:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   5217:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   5218:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5219:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5220:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5221:        vlv= nbcode[Tvaraff[lv]][lv];
                   5222:        fprintf(ficgp," V%d=%d ",k,vlv);
                   5223:       }
                   5224:       fprintf(ficgp,"\n#\n");
                   5225: 
1.201     brouard  5226:      fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);
                   5227:      fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);
1.126     brouard  5228:      fprintf(ficgp,"set xlabel \"Age\" \n\
                   5229: set ylabel \"Probability\" \n\
1.199     brouard  5230: set ter svg size 640, 480\n\
1.201     brouard  5231: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);
1.126     brouard  5232: 
                   5233:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  5234:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   5235:        else        fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  5236:      }
1.201     brouard  5237:      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);
1.126     brouard  5238:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  5239:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   5240:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  5241:      } 
1.201     brouard  5242:      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); 
1.126     brouard  5243:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  5244:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   5245:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  5246:      }  
1.201     brouard  5247:      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));
                   5248:      fprintf(ficgp,"\nset out \n");
                   5249:     } /* k1 */
                   5250:   } /* cpt */
1.126     brouard  5251:   /*2 eme*/
                   5252:   for (k1=1; k1<= m ; k1 ++) { 
1.211     brouard  5253:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
                   5254:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   5255:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   5256:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5257:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5258:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5259:        vlv= nbcode[Tvaraff[lv]][lv];
                   5260:        fprintf(ficgp," V%d=%d ",k,vlv);
                   5261:       }
                   5262:       fprintf(ficgp,"\n#\n");
                   5263: 
1.201     brouard  5264:     fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);
                   5265:     for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
                   5266:       if(vpopbased==0)
                   5267:        fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
                   5268:       else
                   5269:        fprintf(ficgp,"\nreplot ");
                   5270:       for (i=1; i<= nlstate+1 ; i ++) {
                   5271:        k=2*i;
                   5272:        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);
                   5273:        for (j=1; j<= nlstate+1 ; j ++) {
                   5274:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   5275:          else fprintf(ficgp," %%*lf (%%*lf)");
                   5276:        }   
                   5277:        if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   5278:        else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
                   5279:        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);
                   5280:        for (j=1; j<= nlstate+1 ; j ++) {
                   5281:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   5282:          else fprintf(ficgp," %%*lf (%%*lf)");
                   5283:        }   
                   5284:        fprintf(ficgp,"\" t\"\" w l lt 0,");
                   5285:        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);
                   5286:        for (j=1; j<= nlstate+1 ; j ++) {
                   5287:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   5288:          else fprintf(ficgp," %%*lf (%%*lf)");
                   5289:        }   
                   5290:        if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   5291:        else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   5292:       } /* state */
                   5293:     } /* vpopbased */
                   5294:     fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
                   5295:   } /* k1 */
1.211     brouard  5296: 
                   5297: 
1.126     brouard  5298:   /*3eme*/
                   5299:   for (k1=1; k1<= m ; k1 ++) { 
                   5300:     for (cpt=1; cpt<= nlstate ; cpt ++) {
1.211     brouard  5301:       fprintf(ficgp,"\n# 3d: Life expectancy with EXP_ files:  cov=%d state=%d",k1, cpt);
                   5302:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   5303:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   5304:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5305:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5306:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5307:        vlv= nbcode[Tvaraff[lv]][lv];
                   5308:        fprintf(ficgp," V%d=%d ",k,vlv);
                   5309:       }
                   5310:       fprintf(ficgp,"\n#\n");
                   5311: 
1.126     brouard  5312:       /*       k=2+nlstate*(2*cpt-2); */
                   5313:       k=2+(nlstate+1)*(cpt-1);
1.201     brouard  5314:       fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);
1.199     brouard  5315:       fprintf(ficgp,"set ter svg size 640, 480\n\
1.201     brouard  5316: 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  5317:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   5318:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   5319:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   5320:        fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   5321:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   5322:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   5323:        
                   5324:       */
                   5325:       for (i=1; i< nlstate ; i ++) {
1.201     brouard  5326:        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);
1.126     brouard  5327:        /*      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);*/
                   5328:        
                   5329:       } 
1.201     brouard  5330:       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  5331:     }
                   5332:   }
                   5333:   
1.201     brouard  5334:   /* Survival functions (period) from state i in state j by initial state i */
                   5335:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
                   5336:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.211     brouard  5337:       fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
                   5338:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   5339:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   5340:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5341:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5342:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5343:        vlv= nbcode[Tvaraff[lv]][lv];
                   5344:        fprintf(ficgp," V%d=%d ",k,vlv);
                   5345:       }
                   5346:       fprintf(ficgp,"\n#\n");
                   5347: 
1.201     brouard  5348:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);
                   5349:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   5350: set ter svg size 640, 480\n\
                   5351: unset log y\n\
                   5352: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  5353:       k=3;
1.201     brouard  5354:       for (i=1; i<= nlstate ; i ++){
                   5355:        if(i==1)
                   5356:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   5357:        else
                   5358:          fprintf(ficgp,", '' ");
                   5359:        l=(nlstate+ndeath)*(i-1)+1;
                   5360:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   5361:        for (j=2; j<= nlstate+ndeath ; j ++)
                   5362:          fprintf(ficgp,"+$%d",k+l+j-1);
                   5363:        fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   5364:       } /* nlstate */
                   5365:       fprintf(ficgp,"\nset out\n");
                   5366:     } /* end cpt state*/ 
                   5367:   } /* end covariate */  
                   5368: 
                   5369:   /* Survival functions (period) from state i in state j by final state j */
1.202     brouard  5370:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
1.201     brouard  5371:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
                   5372:       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  5373:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   5374:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   5375:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5376:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5377:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5378:        vlv= nbcode[Tvaraff[lv]][lv];
                   5379:        fprintf(ficgp," V%d=%d ",k,vlv);
                   5380:       }
                   5381:       fprintf(ficgp,"\n#\n");
                   5382: 
1.201     brouard  5383:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);
                   5384:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   5385: set ter svg size 640, 480\n\
                   5386: unset log y\n\
                   5387: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  5388:       k=3;
1.201     brouard  5389:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   5390:        if(j==1)
                   5391:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   5392:        else
                   5393:          fprintf(ficgp,", '' ");
                   5394:        l=(nlstate+ndeath)*(cpt-1) +j;
                   5395:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   5396:        /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   5397:        /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   5398:        fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   5399:       } /* nlstate */
                   5400:       fprintf(ficgp,", '' ");
                   5401:       fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   5402:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   5403:        l=(nlstate+ndeath)*(cpt-1) +j;
                   5404:        if(j < nlstate)
                   5405:          fprintf(ficgp,"$%d +",k+l);
                   5406:        else
                   5407:          fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   5408:       }
                   5409:       fprintf(ficgp,"\nset out\n");
                   5410:     } /* end cpt state*/ 
                   5411:   } /* end covariate */  
                   5412: 
1.202     brouard  5413:   /* CV preval stable (period) for each covariate */
1.211     brouard  5414:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
1.153     brouard  5415:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.211     brouard  5416:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
                   5417:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   5418:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   5419:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5420:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5421:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5422:        vlv= nbcode[Tvaraff[lv]][lv];
                   5423:        fprintf(ficgp," V%d=%d ",k,vlv);
                   5424:       }
                   5425:       fprintf(ficgp,"\n#\n");
                   5426: 
1.201     brouard  5427:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);
1.126     brouard  5428:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.199     brouard  5429: set ter svg size 640, 480\n\
1.126     brouard  5430: unset log y\n\
1.153     brouard  5431: plot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  5432:       k=3; /* Offset */
1.153     brouard  5433:       for (i=1; i<= nlstate ; i ++){
                   5434:        if(i==1)
1.201     brouard  5435:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
1.153     brouard  5436:        else
                   5437:          fprintf(ficgp,", '' ");
1.154     brouard  5438:        l=(nlstate+ndeath)*(i-1)+1;
                   5439:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.201     brouard  5440:        for (j=2; j<= nlstate ; j ++)
                   5441:          fprintf(ficgp,"+$%d",k+l+j-1);
1.153     brouard  5442:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
                   5443:       } /* nlstate */
1.201     brouard  5444:       fprintf(ficgp,"\nset out\n");
1.153     brouard  5445:     } /* end cpt state*/ 
                   5446:   } /* end covariate */  
1.201     brouard  5447: 
1.211     brouard  5448:   if(prevfcast==1){
                   5449:   /* Projection from cross-sectional to stable (period) for each covariate */
                   5450: 
                   5451:     for (k1=1; k1<= m ; k1 ++) { /* For each covariate combination (1 to m=2**k), if any covariate is present */
                   5452:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   5453:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to stable (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
                   5454:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   5455:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   5456:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5457:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5458:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5459:          vlv= nbcode[Tvaraff[lv]][lv];
                   5460:          fprintf(ficgp," V%d=%d ",k,vlv);
                   5461:        }
                   5462:        fprintf(ficgp,"\n#\n");
                   5463:        
                   5464:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
                   5465:        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1);
                   5466:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   5467: set ter svg size 640, 480\n\
                   5468: unset log y\n\
                   5469: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   5470:        for (i=1; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   5471:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   5472:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   5473:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   5474:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   5475:          if(i==1){
                   5476:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   5477:          }else{
                   5478:            fprintf(ficgp,",\\\n '' ");
                   5479:          }
                   5480:          if(cptcoveff ==0){ /* No covariate */
                   5481:            fprintf(ficgp," u 2:("); /* Age is in 2 */
                   5482:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   5483:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   5484:            if(i==nlstate+1)
                   5485:              fprintf(ficgp," $%d/(1.-$%d)) t 'p.%d' with line ", \
                   5486:                        2+(cpt-1)*(nlstate+1)+1+(i-1),  2+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   5487:            else
                   5488:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ", \
                   5489:                      2+(cpt-1)*(nlstate+1)+1+(i-1),  2+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   5490:          }else{
                   5491:            fprintf(ficgp,"u 6:(("); /* Age is in 6 */
                   5492:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   5493:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   5494:            kl=0;
                   5495:            for (k=1; k<=cptcoveff; k++){    /* For each covariate  */
                   5496:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   5497:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   5498:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   5499:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   5500:              vlv= nbcode[Tvaraff[lv]][lv];
                   5501:              kl++;
                   5502:              /* 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 *\/ */
                   5503:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   5504:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   5505:              /* ''  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*/
                   5506:              if(k==cptcoveff)
                   5507:                if(i==nlstate+1)
                   5508:                  fprintf(ficgp,"$%d==%d && $%d==%d)? $%d/(1.-$%d) : 1/0) t 'p.%d' with line ",kl, k,kl+1,nbcode[Tvaraff[lv]][lv], \
                   5509:                          6+(cpt-1)*(nlstate+1)+1+(i-1),  6+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   5510:                else
                   5511:                  fprintf(ficgp,"$%d==%d && $%d==%d)? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ",kl, k,kl+1,nbcode[Tvaraff[lv]][lv], \
                   5512:                          6+(cpt-1)*(nlstate+1)+1+(i-1),  6+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   5513:              else{
                   5514:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl, k,kl+1,nbcode[Tvaraff[lv]][lv]);
                   5515:                kl++;
                   5516:              }
                   5517:            } /* end covariate */
                   5518:          } /* end if covariate */
                   5519:        } /* nlstate */
                   5520:        fprintf(ficgp,"\nset out\n");
                   5521:       } /* end cpt state*/
                   5522:     } /* end covariate */
                   5523:   } /* End if prevfcast */
                   5524: 
                   5525: 
1.126     brouard  5526:   /* proba elementaires */
1.187     brouard  5527:   fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
1.126     brouard  5528:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  5529:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  5530:     for(k=1; k <=(nlstate+ndeath); k++){
                   5531:       if (k != i) {
1.187     brouard  5532:        fprintf(ficgp,"#   current state %d\n",k);
1.126     brouard  5533:        for(j=1; j <=ncovmodel; j++){
1.187     brouard  5534:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
1.126     brouard  5535:          jk++; 
                   5536:        }
1.187     brouard  5537:        fprintf(ficgp,"\n");
1.126     brouard  5538:       }
                   5539:     }
                   5540:    }
1.187     brouard  5541:   fprintf(ficgp,"##############\n#\n");
                   5542: 
1.145     brouard  5543:   /*goto avoid;*/
1.200     brouard  5544:   fprintf(ficgp,"\n##############\n#Graphics of probabilities or incidences\n#############\n");
1.187     brouard  5545:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   5546:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   5547:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   5548:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   5549:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   5550:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   5551:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   5552:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   5553:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   5554:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   5555:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   5556:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   5557:   fprintf(ficgp,"#\n");
1.201     brouard  5558:    for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.187     brouard  5559:      fprintf(ficgp,"# ng=%d\n",ng);
                   5560:      fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);
1.126     brouard  5561:      for(jk=1; jk <=m; jk++) {
1.187     brouard  5562:        fprintf(ficgp,"#    jk=%d\n",jk);
1.201     brouard  5563:        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);
                   5564:        fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   5565:        if (ng==1){
                   5566:         fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   5567:         fprintf(ficgp,"\nunset log y");
                   5568:        }else if (ng==2){
                   5569:         fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   5570:         fprintf(ficgp,"\nset log y");
                   5571:        }else if (ng==3){
1.126     brouard  5572:         fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
1.201     brouard  5573:         fprintf(ficgp,"\nset log y");
                   5574:        }else
                   5575:         fprintf(ficgp,"\nunset title ");
                   5576:        fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
1.126     brouard  5577:        i=1;
                   5578:        for(k2=1; k2<=nlstate; k2++) {
                   5579:         k3=i;
                   5580:         for(k=1; k<=(nlstate+ndeath); k++) {
                   5581:           if (k != k2){
1.201     brouard  5582:             switch( ng) {
                   5583:             case 1:
1.187     brouard  5584:               if(nagesqr==0)
1.201     brouard  5585:                 fprintf(ficgp," p%d+p%d*x",i,i+1);
1.187     brouard  5586:               else /* nagesqr =1 */
1.201     brouard  5587:                 fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   5588:               break;
                   5589:             case 2: /* ng=2 */
1.187     brouard  5590:               if(nagesqr==0)
                   5591:                 fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   5592:               else /* nagesqr =1 */
1.201     brouard  5593:                   fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   5594:               break;
                   5595:             case 3:
                   5596:               if(nagesqr==0)
                   5597:                 fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   5598:               else /* nagesqr =1 */
                   5599:                 fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   5600:               break;
                   5601:             }
1.141     brouard  5602:             ij=1;/* To be checked else nbcode[0][0] wrong */
1.187     brouard  5603:             for(j=3; j <=ncovmodel-nagesqr; j++) {
1.197     brouard  5604:               /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
                   5605:               if(ij <=cptcovage) { /* Bug valgrind */
                   5606:                 if((j-2)==Tage[ij]) { /* Bug valgrind */
1.200     brouard  5607:                   fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   5608:                   /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
1.197     brouard  5609:                   ij++;
                   5610:                 }
1.186     brouard  5611:               }
                   5612:               else
1.198     brouard  5613:                 fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.126     brouard  5614:             }
1.201     brouard  5615:             if(ng != 1){
                   5616:               fprintf(ficgp,")/(1");
1.126     brouard  5617:             
1.201     brouard  5618:               for(k1=1; k1 <=nlstate; k1++){ 
                   5619:                 if(nagesqr==0)
                   5620:                   fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                   5621:                 else /* nagesqr =1 */
                   5622:                   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);
                   5623:                 
                   5624:                 ij=1;
                   5625:                 for(j=3; j <=ncovmodel-nagesqr; j++){
                   5626:                   if(ij <=cptcovage) { /* Bug valgrind */
                   5627:                     if((j-2)==Tage[ij]) { /* Bug valgrind */
                   5628:                       fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   5629:                       /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   5630:                       ij++;
                   5631:                     }
1.197     brouard  5632:                   }
1.201     brouard  5633:                   else
                   5634:                     fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.186     brouard  5635:                 }
1.201     brouard  5636:                 fprintf(ficgp,")");
1.126     brouard  5637:               }
                   5638:               fprintf(ficgp,")");
1.201     brouard  5639:               if(ng ==2)
                   5640:                 fprintf(ficgp," t \"p%d%d\" ", k2,k);
                   5641:               else /* ng= 3 */
                   5642:                 fprintf(ficgp," t \"i%d%d\" ", k2,k);
                   5643:             }else{ /* end ng <> 1 */
                   5644:               fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
1.126     brouard  5645:             }
                   5646:             if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
                   5647:             i=i+ncovmodel;
                   5648:           }
                   5649:         } /* end k */
                   5650:        } /* end k2 */
1.201     brouard  5651:        fprintf(ficgp,"\n set out\n");
1.126     brouard  5652:      } /* end jk */
                   5653:    } /* end ng */
1.164     brouard  5654:  /* avoid: */
1.126     brouard  5655:    fflush(ficgp); 
                   5656: }  /* end gnuplot */
                   5657: 
                   5658: 
                   5659: /*************** Moving average **************/
                   5660: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
                   5661: 
                   5662:   int i, cpt, cptcod;
                   5663:   int modcovmax =1;
                   5664:   int mobilavrange, mob;
                   5665:   double age;
                   5666: 
                   5667:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
                   5668:                           a covariate has 2 modalities */
                   5669:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
                   5670: 
                   5671:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   5672:     if(mobilav==1) mobilavrange=5; /* default */
                   5673:     else mobilavrange=mobilav;
                   5674:     for (age=bage; age<=fage; age++)
                   5675:       for (i=1; i<=nlstate;i++)
                   5676:        for (cptcod=1;cptcod<=modcovmax;cptcod++)
                   5677:          mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   5678:     /* We keep the original values on the extreme ages bage, fage and for 
                   5679:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   5680:        we use a 5 terms etc. until the borders are no more concerned. 
                   5681:     */ 
                   5682:     for (mob=3;mob <=mobilavrange;mob=mob+2){
                   5683:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   5684:        for (i=1; i<=nlstate;i++){
                   5685:          for (cptcod=1;cptcod<=modcovmax;cptcod++){
                   5686:            mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   5687:              for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   5688:                mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   5689:                mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   5690:              }
                   5691:            mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   5692:          }
                   5693:        }
                   5694:       }/* end age */
                   5695:     }/* end mob */
                   5696:   }else return -1;
                   5697:   return 0;
                   5698: }/* End movingaverage */
                   5699: 
                   5700: 
                   5701: /************** Forecasting ******************/
1.169     brouard  5702: 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  5703:   /* proj1, year, month, day of starting projection 
                   5704:      agemin, agemax range of age
                   5705:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   5706:      anproj2 year of en of projection (same day and month as proj1).
                   5707:   */
1.164     brouard  5708:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126     brouard  5709:   double agec; /* generic age */
                   5710:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   5711:   double *popeffectif,*popcount;
                   5712:   double ***p3mat;
                   5713:   double ***mobaverage;
                   5714:   char fileresf[FILENAMELENGTH];
                   5715: 
                   5716:   agelim=AGESUP;
1.211     brouard  5717:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   5718:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   5719:      We still use firstpass and lastpass as another selection.
                   5720:   */
1.214     brouard  5721:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   5722:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  5723:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   5724:  
1.201     brouard  5725:   strcpy(fileresf,"F_"); 
                   5726:   strcat(fileresf,fileresu);
1.126     brouard  5727:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   5728:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   5729:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   5730:   }
1.215     brouard  5731:   printf("Computing forecasting: result on file '%s', please wait... \n", fileresf);
                   5732:   fprintf(ficlog,"Computing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  5733: 
                   5734:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   5735: 
                   5736:   if (mobilav!=0) {
                   5737:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5738:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   5739:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   5740:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   5741:     }
                   5742:   }
                   5743: 
                   5744:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   5745:   if (stepm<=12) stepsize=1;
                   5746:   if(estepm < stepm){
                   5747:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5748:   }
                   5749:   else  hstepm=estepm;   
                   5750: 
                   5751:   hstepm=hstepm/stepm; 
                   5752:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   5753:                                fractional in yp1 */
                   5754:   anprojmean=yp;
                   5755:   yp2=modf((yp1*12),&yp);
                   5756:   mprojmean=yp;
                   5757:   yp1=modf((yp2*30.5),&yp);
                   5758:   jprojmean=yp;
                   5759:   if(jprojmean==0) jprojmean=1;
                   5760:   if(mprojmean==0) jprojmean=1;
                   5761: 
                   5762:   i1=cptcoveff;
                   5763:   if (cptcovn < 1){i1=1;}
                   5764:   
                   5765:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   5766:   
                   5767:   fprintf(ficresf,"#****** Routine prevforecast **\n");
                   5768: 
                   5769: /*           if (h==(int)(YEARM*yearp)){ */
                   5770:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
                   5771:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   5772:       k=k+1;
1.211     brouard  5773:       fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
1.126     brouard  5774:       for(j=1;j<=cptcoveff;j++) {
1.211     brouard  5775:        fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  5776:       }
1.211     brouard  5777:       fprintf(ficresf," yearproj age");
1.126     brouard  5778:       for(j=1; j<=nlstate+ndeath;j++){ 
                   5779:        for(i=1; i<=nlstate;i++)              
                   5780:           fprintf(ficresf," p%d%d",i,j);
                   5781:        fprintf(ficresf," p.%d",j);
                   5782:       }
                   5783:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
                   5784:        fprintf(ficresf,"\n");
                   5785:        fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   5786: 
                   5787:        for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   5788:          nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   5789:          nhstepm = nhstepm/hstepm; 
                   5790:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5791:          oldm=oldms;savm=savms;
                   5792:          hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5793:        
                   5794:          for (h=0; h<=nhstepm; h++){
                   5795:            if (h*hstepm/YEARM*stepm ==yearp) {
                   5796:               fprintf(ficresf,"\n");
                   5797:               for(j=1;j<=cptcoveff;j++) 
1.198     brouard  5798:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  5799:              fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   5800:            } 
                   5801:            for(j=1; j<=nlstate+ndeath;j++) {
                   5802:              ppij=0.;
                   5803:              for(i=1; i<=nlstate;i++) {
                   5804:                if (mobilav==1) 
                   5805:                  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
                   5806:                else {
                   5807:                  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
                   5808:                }
                   5809:                if (h*hstepm/YEARM*stepm== yearp) {
                   5810:                  fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   5811:                }
                   5812:              } /* end i */
                   5813:              if (h*hstepm/YEARM*stepm==yearp) {
                   5814:                fprintf(ficresf," %.3f", ppij);
                   5815:              }
                   5816:            }/* end j */
                   5817:          } /* end h */
                   5818:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5819:        } /* end agec */
                   5820:       } /* end yearp */
                   5821:     } /* end cptcod */
                   5822:   } /* end  cptcov */
                   5823:        
                   5824:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5825: 
                   5826:   fclose(ficresf);
1.215     brouard  5827:   printf("End of Computing forecasting \n");
                   5828:   fprintf(ficlog,"End of Computing forecasting\n");
                   5829: 
1.126     brouard  5830: }
                   5831: 
                   5832: /************** Forecasting *****not tested NB*************/
1.169     brouard  5833: 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  5834:   
                   5835:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
                   5836:   int *popage;
                   5837:   double calagedatem, agelim, kk1, kk2;
                   5838:   double *popeffectif,*popcount;
                   5839:   double ***p3mat,***tabpop,***tabpopprev;
                   5840:   double ***mobaverage;
                   5841:   char filerespop[FILENAMELENGTH];
                   5842: 
                   5843:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5844:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5845:   agelim=AGESUP;
                   5846:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
                   5847:   
                   5848:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   5849:   
                   5850:   
1.201     brouard  5851:   strcpy(filerespop,"POP_"); 
                   5852:   strcat(filerespop,fileresu);
1.126     brouard  5853:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
                   5854:     printf("Problem with forecast resultfile: %s\n", filerespop);
                   5855:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
                   5856:   }
                   5857:   printf("Computing forecasting: result on file '%s' \n", filerespop);
                   5858:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
                   5859: 
                   5860:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   5861: 
                   5862:   if (mobilav!=0) {
                   5863:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5864:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   5865:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   5866:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   5867:     }
                   5868:   }
                   5869: 
                   5870:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   5871:   if (stepm<=12) stepsize=1;
                   5872:   
                   5873:   agelim=AGESUP;
                   5874:   
                   5875:   hstepm=1;
                   5876:   hstepm=hstepm/stepm; 
                   5877:   
                   5878:   if (popforecast==1) {
                   5879:     if((ficpop=fopen(popfile,"r"))==NULL) {
                   5880:       printf("Problem with population file : %s\n",popfile);exit(0);
                   5881:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
                   5882:     } 
                   5883:     popage=ivector(0,AGESUP);
                   5884:     popeffectif=vector(0,AGESUP);
                   5885:     popcount=vector(0,AGESUP);
                   5886:     
                   5887:     i=1;   
                   5888:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
                   5889:    
                   5890:     imx=i;
                   5891:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
                   5892:   }
                   5893: 
                   5894:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
                   5895:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   5896:       k=k+1;
                   5897:       fprintf(ficrespop,"\n#******");
                   5898:       for(j=1;j<=cptcoveff;j++) {
1.198     brouard  5899:        fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  5900:       }
                   5901:       fprintf(ficrespop,"******\n");
                   5902:       fprintf(ficrespop,"# Age");
                   5903:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
                   5904:       if (popforecast==1)  fprintf(ficrespop," [Population]");
                   5905:       
                   5906:       for (cpt=0; cpt<=0;cpt++) { 
                   5907:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   5908:        
                   5909:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   5910:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   5911:          nhstepm = nhstepm/hstepm; 
                   5912:          
                   5913:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5914:          oldm=oldms;savm=savms;
                   5915:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5916:        
                   5917:          for (h=0; h<=nhstepm; h++){
                   5918:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   5919:              fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   5920:            } 
                   5921:            for(j=1; j<=nlstate+ndeath;j++) {
                   5922:              kk1=0.;kk2=0;
                   5923:              for(i=1; i<=nlstate;i++) {              
                   5924:                if (mobilav==1) 
                   5925:                  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
                   5926:                else {
                   5927:                  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
                   5928:                }
                   5929:              }
                   5930:              if (h==(int)(calagedatem+12*cpt)){
                   5931:                tabpop[(int)(agedeb)][j][cptcod]=kk1;
                   5932:                  /*fprintf(ficrespop," %.3f", kk1);
                   5933:                    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
                   5934:              }
                   5935:            }
                   5936:            for(i=1; i<=nlstate;i++){
                   5937:              kk1=0.;
                   5938:                for(j=1; j<=nlstate;j++){
                   5939:                  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
                   5940:                }
                   5941:                  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
                   5942:            }
                   5943: 
                   5944:            if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
                   5945:              fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
                   5946:          }
                   5947:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5948:        }
                   5949:       }
                   5950:  
                   5951:   /******/
                   5952: 
                   5953:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
                   5954:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   5955:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   5956:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   5957:          nhstepm = nhstepm/hstepm; 
                   5958:          
                   5959:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5960:          oldm=oldms;savm=savms;
                   5961:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5962:          for (h=0; h<=nhstepm; h++){
                   5963:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   5964:              fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   5965:            } 
                   5966:            for(j=1; j<=nlstate+ndeath;j++) {
                   5967:              kk1=0.;kk2=0;
                   5968:              for(i=1; i<=nlstate;i++) {              
                   5969:                kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
                   5970:              }
                   5971:              if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
                   5972:            }
                   5973:          }
                   5974:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5975:        }
                   5976:       }
                   5977:    } 
                   5978:   }
                   5979:  
                   5980:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5981: 
                   5982:   if (popforecast==1) {
                   5983:     free_ivector(popage,0,AGESUP);
                   5984:     free_vector(popeffectif,0,AGESUP);
                   5985:     free_vector(popcount,0,AGESUP);
                   5986:   }
                   5987:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5988:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5989:   fclose(ficrespop);
                   5990: } /* End of popforecast */
                   5991: 
                   5992: int fileappend(FILE *fichier, char *optionfich)
                   5993: {
                   5994:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   5995:     printf("Problem with file: %s\n", optionfich);
                   5996:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   5997:     return (0);
                   5998:   }
                   5999:   fflush(fichier);
                   6000:   return (1);
                   6001: }
                   6002: 
                   6003: 
                   6004: /**************** function prwizard **********************/
                   6005: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   6006: {
                   6007: 
                   6008:   /* Wizard to print covariance matrix template */
                   6009: 
1.164     brouard  6010:   char ca[32], cb[32];
                   6011:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  6012:   int numlinepar;
                   6013: 
                   6014:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   6015:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   6016:   for(i=1; i <=nlstate; i++){
                   6017:     jj=0;
                   6018:     for(j=1; j <=nlstate+ndeath; j++){
                   6019:       if(j==i) continue;
                   6020:       jj++;
                   6021:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   6022:       printf("%1d%1d",i,j);
                   6023:       fprintf(ficparo,"%1d%1d",i,j);
                   6024:       for(k=1; k<=ncovmodel;k++){
                   6025:        /*        printf(" %lf",param[i][j][k]); */
                   6026:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   6027:        printf(" 0.");
                   6028:        fprintf(ficparo," 0.");
                   6029:       }
                   6030:       printf("\n");
                   6031:       fprintf(ficparo,"\n");
                   6032:     }
                   6033:   }
                   6034:   printf("# Scales (for hessian or gradient estimation)\n");
                   6035:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   6036:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   6037:   for(i=1; i <=nlstate; i++){
                   6038:     jj=0;
                   6039:     for(j=1; j <=nlstate+ndeath; j++){
                   6040:       if(j==i) continue;
                   6041:       jj++;
                   6042:       fprintf(ficparo,"%1d%1d",i,j);
                   6043:       printf("%1d%1d",i,j);
                   6044:       fflush(stdout);
                   6045:       for(k=1; k<=ncovmodel;k++){
                   6046:        /*      printf(" %le",delti3[i][j][k]); */
                   6047:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   6048:        printf(" 0.");
                   6049:        fprintf(ficparo," 0.");
                   6050:       }
                   6051:       numlinepar++;
                   6052:       printf("\n");
                   6053:       fprintf(ficparo,"\n");
                   6054:     }
                   6055:   }
                   6056:   printf("# Covariance matrix\n");
                   6057: /* # 121 Var(a12)\n\ */
                   6058: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   6059: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   6060: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   6061: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   6062: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   6063: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   6064: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   6065:   fflush(stdout);
                   6066:   fprintf(ficparo,"# Covariance matrix\n");
                   6067:   /* # 121 Var(a12)\n\ */
                   6068:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   6069:   /* #   ...\n\ */
                   6070:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   6071:   
                   6072:   for(itimes=1;itimes<=2;itimes++){
                   6073:     jj=0;
                   6074:     for(i=1; i <=nlstate; i++){
                   6075:       for(j=1; j <=nlstate+ndeath; j++){
                   6076:        if(j==i) continue;
                   6077:        for(k=1; k<=ncovmodel;k++){
                   6078:          jj++;
                   6079:          ca[0]= k+'a'-1;ca[1]='\0';
                   6080:          if(itimes==1){
                   6081:            printf("#%1d%1d%d",i,j,k);
                   6082:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   6083:          }else{
                   6084:            printf("%1d%1d%d",i,j,k);
                   6085:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   6086:            /*  printf(" %.5le",matcov[i][j]); */
                   6087:          }
                   6088:          ll=0;
                   6089:          for(li=1;li <=nlstate; li++){
                   6090:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   6091:              if(lj==li) continue;
                   6092:              for(lk=1;lk<=ncovmodel;lk++){
                   6093:                ll++;
                   6094:                if(ll<=jj){
                   6095:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   6096:                  if(ll<jj){
                   6097:                    if(itimes==1){
                   6098:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   6099:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   6100:                    }else{
                   6101:                      printf(" 0.");
                   6102:                      fprintf(ficparo," 0.");
                   6103:                    }
                   6104:                  }else{
                   6105:                    if(itimes==1){
                   6106:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   6107:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   6108:                    }else{
                   6109:                      printf(" 0.");
                   6110:                      fprintf(ficparo," 0.");
                   6111:                    }
                   6112:                  }
                   6113:                }
                   6114:              } /* end lk */
                   6115:            } /* end lj */
                   6116:          } /* end li */
                   6117:          printf("\n");
                   6118:          fprintf(ficparo,"\n");
                   6119:          numlinepar++;
                   6120:        } /* end k*/
                   6121:       } /*end j */
                   6122:     } /* end i */
                   6123:   } /* end itimes */
                   6124: 
                   6125: } /* end of prwizard */
                   6126: /******************* Gompertz Likelihood ******************************/
                   6127: double gompertz(double x[])
                   6128: { 
                   6129:   double A,B,L=0.0,sump=0.,num=0.;
                   6130:   int i,n=0; /* n is the size of the sample */
                   6131: 
                   6132:   for (i=0;i<=imx-1 ; i++) {
                   6133:     sump=sump+weight[i];
                   6134:     /*    sump=sump+1;*/
                   6135:     num=num+1;
                   6136:   }
                   6137:  
                   6138:  
                   6139:   /* for (i=0; i<=imx; i++) 
                   6140:      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]);*/
                   6141: 
                   6142:   for (i=1;i<=imx ; i++)
                   6143:     {
                   6144:       if (cens[i] == 1 && wav[i]>1)
                   6145:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   6146:       
                   6147:       if (cens[i] == 0 && wav[i]>1)
                   6148:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   6149:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   6150:       
                   6151:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   6152:       if (wav[i] > 1 ) { /* ??? */
                   6153:        L=L+A*weight[i];
                   6154:        /*      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]);*/
                   6155:       }
                   6156:     }
                   6157: 
                   6158:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   6159:  
                   6160:   return -2*L*num/sump;
                   6161: }
                   6162: 
1.136     brouard  6163: #ifdef GSL
                   6164: /******************* Gompertz_f Likelihood ******************************/
                   6165: double gompertz_f(const gsl_vector *v, void *params)
                   6166: { 
                   6167:   double A,B,LL=0.0,sump=0.,num=0.;
                   6168:   double *x= (double *) v->data;
                   6169:   int i,n=0; /* n is the size of the sample */
                   6170: 
                   6171:   for (i=0;i<=imx-1 ; i++) {
                   6172:     sump=sump+weight[i];
                   6173:     /*    sump=sump+1;*/
                   6174:     num=num+1;
                   6175:   }
                   6176:  
                   6177:  
                   6178:   /* for (i=0; i<=imx; i++) 
                   6179:      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]);*/
                   6180:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   6181:   for (i=1;i<=imx ; i++)
                   6182:     {
                   6183:       if (cens[i] == 1 && wav[i]>1)
                   6184:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   6185:       
                   6186:       if (cens[i] == 0 && wav[i]>1)
                   6187:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   6188:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   6189:       
                   6190:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   6191:       if (wav[i] > 1 ) { /* ??? */
                   6192:        LL=LL+A*weight[i];
                   6193:        /*      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]);*/
                   6194:       }
                   6195:     }
                   6196: 
                   6197:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   6198:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   6199:  
                   6200:   return -2*LL*num/sump;
                   6201: }
                   6202: #endif
                   6203: 
1.126     brouard  6204: /******************* Printing html file ***********/
1.201     brouard  6205: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  6206:                  int lastpass, int stepm, int weightopt, char model[],\
                   6207:                  int imx,  double p[],double **matcov,double agemortsup){
                   6208:   int i,k;
                   6209: 
                   6210:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   6211:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   6212:   for (i=1;i<=2;i++) 
                   6213:     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  6214:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  6215:   fprintf(fichtm,"</ul>");
                   6216: 
                   6217: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   6218: 
                   6219:  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>");
                   6220: 
                   6221:  for (k=agegomp;k<(agemortsup-2);k++) 
                   6222:    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]);
                   6223: 
                   6224:  
                   6225:   fflush(fichtm);
                   6226: }
                   6227: 
                   6228: /******************* Gnuplot file **************/
1.201     brouard  6229: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  6230: 
                   6231:   char dirfileres[132],optfileres[132];
1.164     brouard  6232: 
1.126     brouard  6233:   int ng;
                   6234: 
                   6235: 
                   6236:   /*#ifdef windows */
                   6237:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   6238:     /*#endif */
                   6239: 
                   6240: 
                   6241:   strcpy(dirfileres,optionfilefiname);
                   6242:   strcpy(optfileres,"vpl");
1.199     brouard  6243:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  6244:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  6245:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  6246:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  6247:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   6248: 
                   6249: } 
                   6250: 
1.136     brouard  6251: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   6252: {
1.126     brouard  6253: 
1.136     brouard  6254:   /*-------- data file ----------*/
                   6255:   FILE *fic;
                   6256:   char dummy[]="                         ";
1.164     brouard  6257:   int i=0, j=0, n=0;
1.136     brouard  6258:   int linei, month, year,iout;
                   6259:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  6260:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  6261:   char *stratrunc;
                   6262:   int lstra;
1.126     brouard  6263: 
                   6264: 
1.136     brouard  6265:   if((fic=fopen(datafile,"r"))==NULL)    {
1.195     brouard  6266:     printf("Problem while opening datafile: %s\n", datafile);fflush(stdout);
                   6267:     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);fflush(ficlog);return 1;
1.136     brouard  6268:   }
1.126     brouard  6269: 
1.136     brouard  6270:   i=1;
                   6271:   linei=0;
                   6272:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   6273:     linei=linei+1;
                   6274:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   6275:       if(line[j] == '\t')
                   6276:        line[j] = ' ';
                   6277:     }
                   6278:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   6279:       ;
                   6280:     };
                   6281:     line[j+1]=0;  /* Trims blanks at end of line */
                   6282:     if(line[0]=='#'){
                   6283:       fprintf(ficlog,"Comment line\n%s\n",line);
                   6284:       printf("Comment line\n%s\n",line);
                   6285:       continue;
                   6286:     }
                   6287:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  6288:     strcpy(line, linetmp);
1.136     brouard  6289:   
1.126     brouard  6290: 
1.136     brouard  6291:     for (j=maxwav;j>=1;j--){
1.137     brouard  6292:       cutv(stra, strb, line, ' '); 
1.136     brouard  6293:       if(strb[0]=='.') { /* Missing status */
                   6294:        lval=-1;
                   6295:       }else{
                   6296:        errno=0;
                   6297:        lval=strtol(strb,&endptr,10); 
                   6298:       /*       if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   6299:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  6300:          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);
                   6301:          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);
1.136     brouard  6302:          return 1;
                   6303:        }
                   6304:       }
                   6305:       s[j][i]=lval;
                   6306:       
                   6307:       strcpy(line,stra);
                   6308:       cutv(stra, strb,line,' ');
1.169     brouard  6309:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  6310:       }
1.169     brouard  6311:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  6312:        month=99;
                   6313:        year=9999;
                   6314:       }else{
1.141     brouard  6315:        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);
                   6316:        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);
1.136     brouard  6317:        return 1;
                   6318:       }
                   6319:       anint[j][i]= (double) year; 
                   6320:       mint[j][i]= (double)month; 
                   6321:       strcpy(line,stra);
                   6322:     } /* ENd Waves */
                   6323:     
                   6324:     cutv(stra, strb,line,' '); 
1.169     brouard  6325:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  6326:     }
1.169     brouard  6327:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  6328:       month=99;
                   6329:       year=9999;
                   6330:     }else{
1.141     brouard  6331:       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);
                   6332:        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);
1.136     brouard  6333:        return 1;
                   6334:     }
                   6335:     andc[i]=(double) year; 
                   6336:     moisdc[i]=(double) month; 
                   6337:     strcpy(line,stra);
                   6338:     
                   6339:     cutv(stra, strb,line,' '); 
1.169     brouard  6340:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  6341:     }
1.169     brouard  6342:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  6343:       month=99;
                   6344:       year=9999;
                   6345:     }else{
1.141     brouard  6346:       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);
                   6347:       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.136     brouard  6348:        return 1;
                   6349:     }
                   6350:     if (year==9999) {
1.141     brouard  6351:       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);
                   6352:       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.136     brouard  6353:        return 1;
1.126     brouard  6354: 
1.136     brouard  6355:     }
                   6356:     annais[i]=(double)(year);
                   6357:     moisnais[i]=(double)(month); 
                   6358:     strcpy(line,stra);
                   6359:     
                   6360:     cutv(stra, strb,line,' '); 
                   6361:     errno=0;
                   6362:     dval=strtod(strb,&endptr); 
                   6363:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  6364:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   6365:       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  6366:       fflush(ficlog);
                   6367:       return 1;
                   6368:     }
                   6369:     weight[i]=dval; 
                   6370:     strcpy(line,stra);
                   6371:     
                   6372:     for (j=ncovcol;j>=1;j--){
                   6373:       cutv(stra, strb,line,' '); 
                   6374:       if(strb[0]=='.') { /* Missing status */
                   6375:        lval=-1;
                   6376:       }else{
                   6377:        errno=0;
                   6378:        lval=strtol(strb,&endptr,10); 
                   6379:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  6380:          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);
                   6381:          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);
1.136     brouard  6382:          return 1;
                   6383:        }
                   6384:       }
                   6385:       if(lval <-1 || lval >1){
1.141     brouard  6386:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  6387:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   6388:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   6389:  For example, for multinomial values like 1, 2 and 3,\n \
                   6390:  build V1=0 V2=0 for the reference value (1),\n \
                   6391:         V1=1 V2=0 for (2) \n \
                   6392:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   6393:  output of IMaCh is often meaningless.\n \
                   6394:  Exiting.\n",lval,linei, i,line,j);
1.141     brouard  6395:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  6396:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   6397:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   6398:  For example, for multinomial values like 1, 2 and 3,\n \
                   6399:  build V1=0 V2=0 for the reference value (1),\n \
                   6400:         V1=1 V2=0 for (2) \n \
                   6401:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   6402:  output of IMaCh is often meaningless.\n \
                   6403:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
                   6404:        return 1;
                   6405:       }
                   6406:       covar[j][i]=(double)(lval);
                   6407:       strcpy(line,stra);
                   6408:     }  
                   6409:     lstra=strlen(stra);
                   6410:      
                   6411:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   6412:       stratrunc = &(stra[lstra-9]);
                   6413:       num[i]=atol(stratrunc);
                   6414:     }
                   6415:     else
                   6416:       num[i]=atol(stra);
                   6417:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   6418:       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;}*/
                   6419:     
                   6420:     i=i+1;
                   6421:   } /* End loop reading  data */
1.126     brouard  6422: 
1.136     brouard  6423:   *imax=i-1; /* Number of individuals */
                   6424:   fclose(fic);
                   6425:  
                   6426:   return (0);
1.164     brouard  6427:   /* endread: */
1.136     brouard  6428:     printf("Exiting readdata: ");
                   6429:     fclose(fic);
                   6430:     return (1);
1.126     brouard  6431: 
                   6432: 
                   6433: 
1.136     brouard  6434: }
1.145     brouard  6435: void removespace(char *str) {
                   6436:   char *p1 = str, *p2 = str;
                   6437:   do
                   6438:     while (*p2 == ' ')
                   6439:       p2++;
1.169     brouard  6440:   while (*p1++ == *p2++);
1.145     brouard  6441: }
                   6442: 
                   6443: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
1.187     brouard  6444:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   6445:    * - nagesqr = 1 if age*age in the model, otherwise 0.
                   6446:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   6447:    * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
1.145     brouard  6448:    * - cptcovage number of covariates with age*products =2
                   6449:    * - cptcovs number of simple covariates
                   6450:    * - 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
                   6451:    *     which is a new column after the 9 (ncovcol) variables. 
                   6452:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   6453:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   6454:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   6455:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   6456:  */
1.136     brouard  6457: {
1.145     brouard  6458:   int i, j, k, ks;
1.164     brouard  6459:   int  j1, k1, k2;
1.136     brouard  6460:   char modelsav[80];
1.145     brouard  6461:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  6462:   char *strpt;
1.136     brouard  6463: 
1.145     brouard  6464:   /*removespace(model);*/
1.136     brouard  6465:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  6466:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  6467:     if (strstr(model,"AGE") !=0){
1.192     brouard  6468:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   6469:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  6470:       return 1;
                   6471:     }
1.141     brouard  6472:     if (strstr(model,"v") !=0){
                   6473:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   6474:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   6475:       return 1;
                   6476:     }
1.187     brouard  6477:     strcpy(modelsav,model); 
                   6478:     if ((strpt=strstr(model,"age*age")) !=0){
                   6479:       printf(" strpt=%s, model=%s\n",strpt, model);
                   6480:       if(strpt != model){
                   6481:       printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  6482:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  6483:  corresponding column of parameters.\n",model);
                   6484:       fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  6485:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  6486:  corresponding column of parameters.\n",model); fflush(ficlog);
                   6487:       return 1;
                   6488:     }
                   6489: 
                   6490:       nagesqr=1;
                   6491:       if (strstr(model,"+age*age") !=0)
                   6492:        substrchaine(modelsav, model, "+age*age");
                   6493:       else if (strstr(model,"age*age+") !=0)
                   6494:        substrchaine(modelsav, model, "age*age+");
                   6495:       else 
                   6496:        substrchaine(modelsav, model, "age*age");
                   6497:     }else
                   6498:       nagesqr=0;
                   6499:     if (strlen(modelsav) >1){
                   6500:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   6501:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
                   6502:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2  */
                   6503:       cptcovt= j+1; /* Number of total covariates in the model, not including
                   6504:                   * cst, age and age*age 
                   6505:                   * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
                   6506:                   /* including age products which are counted in cptcovage.
                   6507:                  * but the covariates which are products must be treated 
                   6508:                  * separately: ncovn=4- 2=2 (V1+V3). */
                   6509:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   6510:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
                   6511: 
                   6512:     
                   6513:       /*   Design
                   6514:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   6515:        *  <          ncovcol=8                >
                   6516:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   6517:        *   k=  1    2      3       4     5       6      7        8
                   6518:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   6519:        *  covar[k,i], value of kth covariate if not including age for individual i:
                   6520:        *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
                   6521:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
                   6522:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   6523:        *  Tage[++cptcovage]=k
                   6524:        *       if products, new covar are created after ncovcol with k1
                   6525:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   6526:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   6527:        *  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
                   6528:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   6529:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   6530:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   6531:        *  <          ncovcol=8                >
                   6532:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   6533:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   6534:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   6535:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   6536:        * p Tprod[1]@2={                         6, 5}
                   6537:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   6538:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   6539:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   6540:        *How to reorganize?
                   6541:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   6542:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   6543:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   6544:        * Struct []
                   6545:        */
1.145     brouard  6546: 
1.187     brouard  6547:       /* This loop fills the array Tvar from the string 'model'.*/
                   6548:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   6549:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   6550:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   6551:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   6552:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   6553:       /*       k=1 Tvar[1]=2 (from V2) */
                   6554:       /*       k=5 Tvar[5] */
                   6555:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  6556:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  6557:       /*       } */
1.198     brouard  6558:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  6559:       /*
                   6560:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
                   6561:       for(k=cptcovt; k>=1;k--) /**< Number of covariates */
1.145     brouard  6562:         Tvar[k]=0;
1.187     brouard  6563:       cptcovage=0;
                   6564:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
                   6565:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
                   6566:                                         modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
                   6567:        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
                   6568:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   6569:        /*scanf("%d",i);*/
                   6570:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   6571:          cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   6572:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   6573:            /* covar is not filled and then is empty */
                   6574:            cptcovprod--;
                   6575:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   6576:            Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
                   6577:            cptcovage++; /* Sums the number of covariates which include age as a product */
                   6578:            Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   6579:            /*printf("stre=%s ", stre);*/
                   6580:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   6581:            cptcovprod--;
                   6582:            cutl(stre,strb,strc,'V');
                   6583:            Tvar[k]=atoi(stre);
                   6584:            cptcovage++;
                   6585:            Tage[cptcovage]=k;
                   6586:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   6587:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   6588:            cptcovn++;
                   6589:            cptcovprodnoage++;k1++;
                   6590:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   6591:            Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
                   6592:                                   because this model-covariate is a construction we invent a new column
                   6593:                                   ncovcol + k1
                   6594:                                   If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   6595:                                   Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
                   6596:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   6597:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
                   6598:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   6599:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   6600:            k2=k2+2;
                   6601:            Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
                   6602:            Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
                   6603:            for (i=1; i<=lastobs;i++){
                   6604:              /* Computes the new covariate which is a product of
                   6605:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   6606:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   6607:            }
                   6608:          } /* End age is not in the model */
                   6609:        } /* End if model includes a product */
                   6610:        else { /* no more sum */
                   6611:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   6612:          /*  scanf("%d",i);*/
                   6613:          cutl(strd,strc,strb,'V');
                   6614:          ks++; /**< Number of simple covariates */
1.145     brouard  6615:          cptcovn++;
1.187     brouard  6616:          Tvar[k]=atoi(strd);
                   6617:        }
                   6618:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
                   6619:        /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
                   6620:          scanf("%d",i);*/
                   6621:       } /* end of loop + on total covariates */
                   6622:     } /* end if strlen(modelsave == 0) age*age might exist */
                   6623:   } /* end if strlen(model == 0) */
1.136     brouard  6624:   
                   6625:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   6626:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
                   6627: 
                   6628:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
                   6629:   printf("cptcovprod=%d ", cptcovprod);
                   6630:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   6631: 
                   6632:   scanf("%d ",i);*/
                   6633: 
                   6634: 
1.137     brouard  6635:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  6636:   /*endread:*/
1.136     brouard  6637:     printf("Exiting decodemodel: ");
                   6638:     return (1);
                   6639: }
                   6640: 
1.169     brouard  6641: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136     brouard  6642: {
                   6643:   int i, m;
                   6644: 
                   6645:   for (i=1; i<=imx; i++) {
                   6646:     for(m=2; (m<= maxwav); m++) {
                   6647:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   6648:        anint[m][i]=9999;
1.216   ! brouard  6649:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
        !          6650:          s[m][i]=-1;
1.136     brouard  6651:       }
                   6652:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169     brouard  6653:        *nberr = *nberr + 1;
                   6654:        printf("Error! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown, you must set an arbitrary year of death or he/she is skipped and results are biased (%d)\n",(int)moisdc[i],(int)andc[i],num[i],i, *nberr);
                   6655:        fprintf(ficlog,"Error! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown, you must set an arbitrary year of death or he/she is skipped and results are biased (%d)\n",(int)moisdc[i],(int)andc[i],num[i],i, *nberr);
1.136     brouard  6656:        s[m][i]=-1;
                   6657:       }
                   6658:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  6659:        (*nberr)++;
1.136     brouard  6660:        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]); 
                   6661:        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]); 
                   6662:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   6663:       }
                   6664:     }
                   6665:   }
                   6666: 
                   6667:   for (i=1; i<=imx; i++)  {
                   6668:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   6669:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  6670:       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  6671:        if (s[m][i] >= nlstate+1) {
1.169     brouard  6672:          if(agedc[i]>0){
                   6673:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  6674:              agev[m][i]=agedc[i];
1.214     brouard  6675:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  6676:            }else {
1.136     brouard  6677:              if ((int)andc[i]!=9999){
                   6678:                nbwarn++;
                   6679:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   6680:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   6681:                agev[m][i]=-1;
                   6682:              }
                   6683:            }
1.169     brouard  6684:          } /* agedc > 0 */
1.214     brouard  6685:        } /* end if */
1.136     brouard  6686:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   6687:                                 years but with the precision of a month */
                   6688:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   6689:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   6690:            agev[m][i]=1;
                   6691:          else if(agev[m][i] < *agemin){ 
                   6692:            *agemin=agev[m][i];
                   6693:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   6694:          }
                   6695:          else if(agev[m][i] >*agemax){
                   6696:            *agemax=agev[m][i];
1.156     brouard  6697:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  6698:          }
                   6699:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   6700:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  6701:        } /* en if 9*/
1.136     brouard  6702:        else { /* =9 */
1.214     brouard  6703:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  6704:          agev[m][i]=1;
                   6705:          s[m][i]=-1;
                   6706:        }
                   6707:       }
1.214     brouard  6708:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  6709:        agev[m][i]=1;
1.214     brouard  6710:       else{
                   6711:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   6712:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   6713:        agev[m][i]=0;
                   6714:       }
                   6715:     } /* End for lastpass */
                   6716:   }
1.136     brouard  6717:     
                   6718:   for (i=1; i<=imx; i++)  {
                   6719:     for(m=firstpass; (m<=lastpass); m++){
                   6720:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  6721:        (*nberr)++;
1.136     brouard  6722:        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);     
                   6723:        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);     
                   6724:        return 1;
                   6725:       }
                   6726:     }
                   6727:   }
                   6728: 
                   6729:   /*for (i=1; i<=imx; i++){
                   6730:   for (m=firstpass; (m<lastpass); m++){
                   6731:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   6732: }
                   6733: 
                   6734: }*/
                   6735: 
                   6736: 
1.139     brouard  6737:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   6738:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  6739: 
                   6740:   return (0);
1.164     brouard  6741:  /* endread:*/
1.136     brouard  6742:     printf("Exiting calandcheckages: ");
                   6743:     return (1);
                   6744: }
                   6745: 
1.172     brouard  6746: #if defined(_MSC_VER)
                   6747: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   6748: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   6749: //#include "stdafx.h"
                   6750: //#include <stdio.h>
                   6751: //#include <tchar.h>
                   6752: //#include <windows.h>
                   6753: //#include <iostream>
                   6754: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   6755: 
                   6756: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   6757: 
                   6758: BOOL IsWow64()
                   6759: {
                   6760:        BOOL bIsWow64 = FALSE;
                   6761: 
                   6762:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   6763:        //  (HANDLE, PBOOL);
                   6764: 
                   6765:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   6766: 
                   6767:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   6768:        const char funcName[] = "IsWow64Process";
                   6769:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   6770:                GetProcAddress(module, funcName);
                   6771: 
                   6772:        if (NULL != fnIsWow64Process)
                   6773:        {
                   6774:                if (!fnIsWow64Process(GetCurrentProcess(),
                   6775:                        &bIsWow64))
                   6776:                        //throw std::exception("Unknown error");
                   6777:                        printf("Unknown error\n");
                   6778:        }
                   6779:        return bIsWow64 != FALSE;
                   6780: }
                   6781: #endif
1.177     brouard  6782: 
1.191     brouard  6783: void syscompilerinfo(int logged)
1.167     brouard  6784:  {
                   6785:    /* #include "syscompilerinfo.h"*/
1.185     brouard  6786:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   6787:    /* /GS /W3 /Gy
                   6788:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   6789:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   6790:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  6791:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   6792:    */ 
                   6793:    /* 64 bits */
1.185     brouard  6794:    /*
                   6795:      /GS /W3 /Gy
                   6796:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   6797:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   6798:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   6799:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   6800:    /* Optimization are useless and O3 is slower than O2 */
                   6801:    /*
                   6802:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   6803:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   6804:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   6805:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   6806:    */
1.186     brouard  6807:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  6808:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   6809:       /PDB:"visual studio
                   6810:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   6811:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   6812:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   6813:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   6814:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   6815:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   6816:       uiAccess='false'"
                   6817:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   6818:       /NOLOGO /TLBID:1
                   6819:    */
1.177     brouard  6820: #if defined __INTEL_COMPILER
1.178     brouard  6821: #if defined(__GNUC__)
                   6822:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   6823: #endif
1.177     brouard  6824: #elif defined(__GNUC__) 
1.179     brouard  6825: #ifndef  __APPLE__
1.174     brouard  6826: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  6827: #endif
1.177     brouard  6828:    struct utsname sysInfo;
1.178     brouard  6829:    int cross = CROSS;
                   6830:    if (cross){
                   6831:           printf("Cross-");
1.191     brouard  6832:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  6833:    }
1.174     brouard  6834: #endif
                   6835: 
1.171     brouard  6836: #include <stdint.h>
1.178     brouard  6837: 
1.191     brouard  6838:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  6839: #if defined(__clang__)
1.191     brouard  6840:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  6841: #endif
                   6842: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  6843:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  6844: #endif
                   6845: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  6846:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  6847: #endif
                   6848: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  6849:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  6850: #endif
                   6851: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  6852:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  6853: #endif
                   6854: #if defined(_MSC_VER)
1.191     brouard  6855:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  6856: #endif
                   6857: #if defined(__PGI)
1.191     brouard  6858:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  6859: #endif
                   6860: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  6861:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  6862: #endif
1.191     brouard  6863:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  6864:    
1.167     brouard  6865: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   6866: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   6867:     // Windows (x64 and x86)
1.191     brouard  6868:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  6869: #elif __unix__ // all unices, not all compilers
                   6870:     // Unix
1.191     brouard  6871:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  6872: #elif __linux__
                   6873:     // linux
1.191     brouard  6874:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  6875: #elif __APPLE__
1.174     brouard  6876:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  6877:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  6878: #endif
                   6879: 
                   6880: /*  __MINGW32__          */
                   6881: /*  __CYGWIN__  */
                   6882: /* __MINGW64__  */
                   6883: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   6884: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   6885: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   6886: /* _WIN64  // Defined for applications for Win64. */
                   6887: /* _M_X64 // Defined for compilations that target x64 processors. */
                   6888: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  6889: 
1.167     brouard  6890: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  6891:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  6892: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  6893:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  6894: #else
1.191     brouard  6895:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  6896: #endif
                   6897: 
1.169     brouard  6898: #if defined(__GNUC__)
                   6899: # if defined(__GNUC_PATCHLEVEL__)
                   6900: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   6901:                             + __GNUC_MINOR__ * 100 \
                   6902:                             + __GNUC_PATCHLEVEL__)
                   6903: # else
                   6904: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   6905:                             + __GNUC_MINOR__ * 100)
                   6906: # endif
1.174     brouard  6907:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  6908:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  6909: 
                   6910:    if (uname(&sysInfo) != -1) {
                   6911:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  6912:         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  6913:    }
                   6914:    else
                   6915:       perror("uname() error");
1.179     brouard  6916:    //#ifndef __INTEL_COMPILER 
                   6917: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  6918:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  6919:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  6920: #endif
1.169     brouard  6921: #endif
1.172     brouard  6922: 
                   6923:    //   void main()
                   6924:    //   {
1.169     brouard  6925: #if defined(_MSC_VER)
1.174     brouard  6926:    if (IsWow64()){
1.191     brouard  6927:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   6928:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  6929:    }
                   6930:    else{
1.191     brouard  6931:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   6932:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  6933:    }
1.172     brouard  6934:    //     printf("\nPress Enter to continue...");
                   6935:    //     getchar();
                   6936:    //   }
                   6937: 
1.169     brouard  6938: #endif
                   6939:    
1.167     brouard  6940: 
                   6941:  }
1.136     brouard  6942: 
1.209     brouard  6943:  int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.180     brouard  6944:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
                   6945:   int i, j, k, i1 ;
1.202     brouard  6946:   /* double ftolpl = 1.e-10; */
1.180     brouard  6947:   double age, agebase, agelim;
1.203     brouard  6948:   double tot;
1.180     brouard  6949: 
1.202     brouard  6950:   strcpy(filerespl,"PL_");
                   6951:   strcat(filerespl,fileresu);
                   6952:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
                   6953:     printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   6954:     fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   6955:   }
                   6956:   printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   6957:   fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   6958:   pstamp(ficrespl);
1.203     brouard  6959:   fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  6960:   fprintf(ficrespl,"#Age ");
                   6961:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   6962:   fprintf(ficrespl,"\n");
1.180     brouard  6963:   
                   6964:     /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   6965: 
                   6966:     agebase=ageminpar;
                   6967:     agelim=agemaxpar;
                   6968: 
                   6969:     i1=pow(2,cptcoveff);
                   6970:     if (cptcovn < 1){i1=1;}
                   6971: 
                   6972:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   6973:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   6974:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   6975:        k=k+1;
                   6976:        /* to clean */
1.198     brouard  6977:        //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
1.200     brouard  6978:        fprintf(ficrespl,"#******");
                   6979:        printf("#******");
                   6980:        fprintf(ficlog,"#******");
1.180     brouard  6981:        for(j=1;j<=cptcoveff;j++) {
1.198     brouard  6982:          fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   6983:          printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   6984:          fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180     brouard  6985:        }
                   6986:        fprintf(ficrespl,"******\n");
                   6987:        printf("******\n");
                   6988:        fprintf(ficlog,"******\n");
                   6989: 
                   6990:        fprintf(ficrespl,"#Age ");
                   6991:        for(j=1;j<=cptcoveff;j++) {
1.200     brouard  6992:          fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180     brouard  6993:        }
1.203     brouard  6994:        for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   6995:        fprintf(ficrespl,"Total Years_to_converge\n");
1.180     brouard  6996:        
                   6997:        for (age=agebase; age<=agelim; age++){
                   6998:        /* for (age=agebase; age<=agebase; age++){ */
1.209     brouard  6999:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k);
1.180     brouard  7000:          fprintf(ficrespl,"%.0f ",age );
                   7001:          for(j=1;j<=cptcoveff;j++)
1.198     brouard  7002:            fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.203     brouard  7003:          tot=0.;
                   7004:          for(i=1; i<=nlstate;i++){
                   7005:            tot +=  prlim[i][i];
1.180     brouard  7006:            fprintf(ficrespl," %.5f", prlim[i][i]);
1.203     brouard  7007:          }
1.209     brouard  7008:          fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
1.180     brouard  7009:        } /* Age */
                   7010:        /* was end of cptcod */
                   7011:     } /* cptcov */
1.184     brouard  7012:        return 0;
1.180     brouard  7013: }
                   7014: 
                   7015: int hPijx(double *p, int bage, int fage){
                   7016:     /*------------- h Pij x at various ages ------------*/
                   7017: 
                   7018:   int stepsize;
                   7019:   int agelim;
                   7020:   int hstepm;
                   7021:   int nhstepm;
                   7022:   int h, i, i1, j, k;
                   7023: 
                   7024:   double agedeb;
                   7025:   double ***p3mat;
                   7026: 
1.201     brouard  7027:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  7028:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   7029:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   7030:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   7031:     }
                   7032:     printf("Computing pij: result on file '%s' \n", filerespij);
                   7033:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   7034:   
                   7035:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   7036:     /*if (stepm<=24) stepsize=2;*/
                   7037: 
                   7038:     agelim=AGESUP;
                   7039:     hstepm=stepsize*YEARM; /* Every year of age */
                   7040:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   7041: 
                   7042:     /* hstepm=1;   aff par mois*/
                   7043:     pstamp(ficrespij);
                   7044:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   7045:     i1= pow(2,cptcoveff);
1.183     brouard  7046:    /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   7047:    /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   7048:    /*          k=k+1;  */
                   7049:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   7050:       fprintf(ficrespij,"\n#****** ");
                   7051:       for(j=1;j<=cptcoveff;j++) 
1.198     brouard  7052:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.183     brouard  7053:       fprintf(ficrespij,"******\n");
                   7054:       
                   7055:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   7056:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7057:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7058:        
                   7059:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  7060:        
1.183     brouard  7061:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7062:        oldm=oldms;savm=savms;
                   7063:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   7064:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   7065:        for(i=1; i<=nlstate;i++)
                   7066:          for(j=1; j<=nlstate+ndeath;j++)
                   7067:            fprintf(ficrespij," %1d-%1d",i,j);
                   7068:        fprintf(ficrespij,"\n");
                   7069:        for (h=0; h<=nhstepm; h++){
                   7070:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   7071:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  7072:          for(i=1; i<=nlstate;i++)
                   7073:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  7074:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  7075:          fprintf(ficrespij,"\n");
                   7076:        }
1.183     brouard  7077:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7078:        fprintf(ficrespij,"\n");
                   7079:       }
1.180     brouard  7080:       /*}*/
                   7081:     }
1.184     brouard  7082:        return 0;
1.180     brouard  7083: }
                   7084: 
                   7085: 
1.136     brouard  7086: /***********************************************/
                   7087: /**************** Main Program *****************/
                   7088: /***********************************************/
                   7089: 
                   7090: int main(int argc, char *argv[])
                   7091: {
                   7092: #ifdef GSL
                   7093:   const gsl_multimin_fminimizer_type *T;
                   7094:   size_t iteri = 0, it;
                   7095:   int rval = GSL_CONTINUE;
                   7096:   int status = GSL_SUCCESS;
                   7097:   double ssval;
                   7098: #endif
                   7099:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164     brouard  7100:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
1.209     brouard  7101:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  7102:   int jj, ll, li, lj, lk;
1.136     brouard  7103:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  7104:   int num_filled;
1.136     brouard  7105:   int itimes;
                   7106:   int NDIM=2;
                   7107:   int vpopbased=0;
                   7108: 
1.164     brouard  7109:   char ca[32], cb[32];
1.136     brouard  7110:   /*  FILE *fichtm; *//* Html File */
                   7111:   /* FILE *ficgp;*/ /*Gnuplot File */
                   7112:   struct stat info;
1.191     brouard  7113:   double agedeb=0.;
1.194     brouard  7114: 
                   7115:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.136     brouard  7116: 
1.165     brouard  7117:   double fret;
1.191     brouard  7118:   double dum=0.; /* Dummy variable */
1.136     brouard  7119:   double ***p3mat;
                   7120:   double ***mobaverage;
1.164     brouard  7121: 
                   7122:   char line[MAXLINE];
1.197     brouard  7123:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   7124: 
                   7125:   char model[MAXLINE], modeltemp[MAXLINE];
1.136     brouard  7126:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  7127:   char *tok, *val; /* pathtot */
1.136     brouard  7128:   int firstobs=1, lastobs=10;
1.195     brouard  7129:   int c,  h , cpt, c2;
1.191     brouard  7130:   int jl=0;
                   7131:   int i1, j1, jk, stepsize=0;
1.194     brouard  7132:   int count=0;
                   7133: 
1.164     brouard  7134:   int *tab; 
1.136     brouard  7135:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
                   7136:   int mobilav=0,popforecast=0;
1.191     brouard  7137:   int hstepm=0, nhstepm=0;
1.136     brouard  7138:   int agemortsup;
                   7139:   float  sumlpop=0.;
                   7140:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   7141:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   7142: 
1.191     brouard  7143:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  7144:   double ftolpl=FTOL;
                   7145:   double **prlim;
                   7146:   double ***param; /* Matrix of parameters */
                   7147:   double  *p;
                   7148:   double **matcov; /* Matrix of covariance */
1.203     brouard  7149:   double **hess; /* Hessian matrix */
1.136     brouard  7150:   double ***delti3; /* Scale */
                   7151:   double *delti; /* Scale */
                   7152:   double ***eij, ***vareij;
                   7153:   double **varpl; /* Variances of prevalence limits by age */
                   7154:   double *epj, vepp;
1.164     brouard  7155: 
1.136     brouard  7156:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
                   7157:   double **ximort;
1.145     brouard  7158:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  7159:   int *dcwave;
                   7160: 
1.164     brouard  7161:   char z[1]="c";
1.136     brouard  7162: 
                   7163:   /*char  *strt;*/
                   7164:   char strtend[80];
1.126     brouard  7165: 
1.164     brouard  7166: 
1.126     brouard  7167: /*   setlocale (LC_ALL, ""); */
                   7168: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   7169: /*   textdomain (PACKAGE); */
                   7170: /*   setlocale (LC_CTYPE, ""); */
                   7171: /*   setlocale (LC_MESSAGES, ""); */
                   7172: 
                   7173:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  7174:   rstart_time = time(NULL);  
                   7175:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   7176:   start_time = *localtime(&rstart_time);
1.126     brouard  7177:   curr_time=start_time;
1.157     brouard  7178:   /*tml = *localtime(&start_time.tm_sec);*/
                   7179:   /* strcpy(strstart,asctime(&tml)); */
                   7180:   strcpy(strstart,asctime(&start_time));
1.126     brouard  7181: 
                   7182: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  7183: /*  tp.tm_sec = tp.tm_sec +86400; */
                   7184: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  7185: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   7186: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   7187: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  7188: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  7189: /*   strt=asctime(&tmg); */
                   7190: /*   printf("Time(after) =%s",strstart);  */
                   7191: /*  (void) time (&time_value);
                   7192: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   7193: *  tm = *localtime(&time_value);
                   7194: *  strstart=asctime(&tm);
                   7195: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   7196: */
                   7197: 
                   7198:   nberr=0; /* Number of errors and warnings */
                   7199:   nbwarn=0;
1.184     brouard  7200: #ifdef WIN32
                   7201:   _getcwd(pathcd, size);
                   7202: #else
1.126     brouard  7203:   getcwd(pathcd, size);
1.184     brouard  7204: #endif
1.191     brouard  7205:   syscompilerinfo(0);
1.196     brouard  7206:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  7207:   if(argc <=1){
                   7208:     printf("\nEnter the parameter file name: ");
1.205     brouard  7209:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   7210:       printf("ERROR Empty parameter file name\n");
                   7211:       goto end;
                   7212:     }
1.126     brouard  7213:     i=strlen(pathr);
                   7214:     if(pathr[i-1]=='\n')
                   7215:       pathr[i-1]='\0';
1.156     brouard  7216:     i=strlen(pathr);
1.205     brouard  7217:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  7218:       pathr[i-1]='\0';
1.205     brouard  7219:     }
                   7220:     i=strlen(pathr);
                   7221:     if( i==0 ){
                   7222:       printf("ERROR Empty parameter file name\n");
                   7223:       goto end;
                   7224:     }
                   7225:     for (tok = pathr; tok != NULL; ){
1.126     brouard  7226:       printf("Pathr |%s|\n",pathr);
                   7227:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   7228:       printf("val= |%s| pathr=%s\n",val,pathr);
                   7229:       strcpy (pathtot, val);
                   7230:       if(pathr[0] == '\0') break; /* Dirty */
                   7231:     }
                   7232:   }
                   7233:   else{
                   7234:     strcpy(pathtot,argv[1]);
                   7235:   }
                   7236:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   7237:   /*cygwin_split_path(pathtot,path,optionfile);
                   7238:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   7239:   /* cutv(path,optionfile,pathtot,'\\');*/
                   7240: 
                   7241:   /* Split argv[0], imach program to get pathimach */
                   7242:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   7243:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   7244:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   7245:  /*   strcpy(pathimach,argv[0]); */
                   7246:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   7247:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   7248:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  7249: #ifdef WIN32
                   7250:   _chdir(path); /* Can be a relative path */
                   7251:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   7252: #else
1.126     brouard  7253:   chdir(path); /* Can be a relative path */
1.184     brouard  7254:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   7255: #endif
                   7256:   printf("Current directory %s!\n",pathcd);
1.126     brouard  7257:   strcpy(command,"mkdir ");
                   7258:   strcat(command,optionfilefiname);
                   7259:   if((outcmd=system(command)) != 0){
1.169     brouard  7260:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  7261:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   7262:     /* fclose(ficlog); */
                   7263: /*     exit(1); */
                   7264:   }
                   7265: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   7266: /*     perror("mkdir"); */
                   7267: /*   } */
                   7268: 
                   7269:   /*-------- arguments in the command line --------*/
                   7270: 
1.186     brouard  7271:   /* Main Log file */
1.126     brouard  7272:   strcat(filelog, optionfilefiname);
                   7273:   strcat(filelog,".log");    /* */
                   7274:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   7275:     printf("Problem with logfile %s\n",filelog);
                   7276:     goto end;
                   7277:   }
                   7278:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  7279:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  7280:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   7281:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   7282:  path=%s \n\
                   7283:  optionfile=%s\n\
                   7284:  optionfilext=%s\n\
1.156     brouard  7285:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  7286: 
1.197     brouard  7287:   syscompilerinfo(1);
1.167     brouard  7288: 
1.126     brouard  7289:   printf("Local time (at start):%s",strstart);
                   7290:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   7291:   fflush(ficlog);
                   7292: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  7293: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  7294: 
                   7295:   /* */
                   7296:   strcpy(fileres,"r");
                   7297:   strcat(fileres, optionfilefiname);
1.201     brouard  7298:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  7299:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  7300:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  7301: 
1.186     brouard  7302:   /* Main ---------arguments file --------*/
1.126     brouard  7303: 
                   7304:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  7305:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   7306:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  7307:     fflush(ficlog);
1.149     brouard  7308:     /* goto end; */
                   7309:     exit(70); 
1.126     brouard  7310:   }
                   7311: 
                   7312: 
                   7313: 
                   7314:   strcpy(filereso,"o");
1.201     brouard  7315:   strcat(filereso,fileresu);
1.126     brouard  7316:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   7317:     printf("Problem with Output resultfile: %s\n", filereso);
                   7318:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   7319:     fflush(ficlog);
                   7320:     goto end;
                   7321:   }
                   7322: 
                   7323:   /* Reads comments: lines beginning with '#' */
                   7324:   numlinepar=0;
1.197     brouard  7325: 
                   7326:     /* First parameter line */
                   7327:   while(fgets(line, MAXLINE, ficpar)) {
                   7328:     /* If line starts with a # it is a comment */
                   7329:     if (line[0] == '#') {
                   7330:       numlinepar++;
                   7331:       fputs(line,stdout);
                   7332:       fputs(line,ficparo);
                   7333:       fputs(line,ficlog);
                   7334:       continue;
                   7335:     }else
                   7336:       break;
                   7337:   }
                   7338:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   7339:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   7340:     if (num_filled != 5) {
                   7341:       printf("Should be 5 parameters\n");
                   7342:     }
1.126     brouard  7343:     numlinepar++;
1.197     brouard  7344:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   7345:   }
                   7346:   /* Second parameter line */
                   7347:   while(fgets(line, MAXLINE, ficpar)) {
                   7348:     /* If line starts with a # it is a comment */
                   7349:     if (line[0] == '#') {
                   7350:       numlinepar++;
                   7351:       fputs(line,stdout);
                   7352:       fputs(line,ficparo);
                   7353:       fputs(line,ficlog);
                   7354:       continue;
                   7355:     }else
                   7356:       break;
                   7357:   }
                   7358:   if((num_filled=sscanf(line,"ftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", \
                   7359:                        &ftol, &stepm, &ncovcol, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   7360:     if (num_filled != 8) {
1.209     brouard  7361:       printf("Not 8 parameters, for example:ftol=1.e-8 stepm=12 ncovcol=2 nlstate=2 ndeath=1 maxwav=3 mle=1 weight=1\n");
                   7362:       printf("but line=%s\n",line);
1.197     brouard  7363:     }
                   7364:     printf("ftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n",ftol, stepm, ncovcol, nlstate,ndeath, maxwav, mle, weightopt);
1.126     brouard  7365:   }
1.203     brouard  7366:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  7367:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  7368:   /* Third parameter line */
                   7369:   while(fgets(line, MAXLINE, ficpar)) {
                   7370:     /* If line starts with a # it is a comment */
                   7371:     if (line[0] == '#') {
                   7372:       numlinepar++;
                   7373:       fputs(line,stdout);
                   7374:       fputs(line,ficparo);
                   7375:       fputs(line,ficlog);
                   7376:       continue;
                   7377:     }else
                   7378:       break;
                   7379:   }
1.201     brouard  7380:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
                   7381:     if (num_filled == 0)
                   7382:             model[0]='\0';
                   7383:     else if (num_filled != 1){
1.197     brouard  7384:       printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   7385:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   7386:       model[0]='\0';
                   7387:       goto end;
                   7388:     }
                   7389:     else{
                   7390:       if (model[0]=='+'){
                   7391:        for(i=1; i<=strlen(model);i++)
                   7392:          modeltemp[i-1]=model[i];
1.201     brouard  7393:        strcpy(model,modeltemp); 
1.197     brouard  7394:       }
                   7395:     }
1.199     brouard  7396:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  7397:     printf("model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  7398:   }
                   7399:   /* 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); */
                   7400:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   7401:   /* 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.203     brouard  7402:   fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=1+age+%s.\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);
                   7403:   fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\nmodel=1+age+%s.\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);
1.126     brouard  7404:   fflush(ficlog);
1.190     brouard  7405:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   7406:   if(model[0]=='#'){
1.187     brouard  7407:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
                   7408:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
                   7409:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");         \
                   7410:     if(mle != -1){
                   7411:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
                   7412:       exit(1);
                   7413:     }
                   7414:   }
1.126     brouard  7415:   while((c=getc(ficpar))=='#' && c!= EOF){
                   7416:     ungetc(c,ficpar);
                   7417:     fgets(line, MAXLINE, ficpar);
                   7418:     numlinepar++;
1.195     brouard  7419:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   7420:       z[0]=line[1];
                   7421:     }
                   7422:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  7423:     fputs(line, stdout);
                   7424:     //puts(line);
1.126     brouard  7425:     fputs(line,ficparo);
                   7426:     fputs(line,ficlog);
                   7427:   }
                   7428:   ungetc(c,ficpar);
                   7429: 
                   7430:    
1.145     brouard  7431:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
1.136     brouard  7432:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   7433:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   7434:      v1+v2*age+v2*v3 makes cptcovn = 3
                   7435:   */
                   7436:   if (strlen(model)>1) 
1.187     brouard  7437:     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  7438:   else
1.187     brouard  7439:     ncovmodel=2; /* Constant and age */
1.133     brouard  7440:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   7441:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  7442:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   7443:     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);
                   7444:     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);
                   7445:     fflush(stdout);
                   7446:     fclose (ficlog);
                   7447:     goto end;
                   7448:   }
1.126     brouard  7449:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   7450:   delti=delti3[1][1];
                   7451:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   7452:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   7453:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  7454:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   7455:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  7456:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   7457:     fclose (ficparo);
                   7458:     fclose (ficlog);
                   7459:     goto end;
                   7460:     exit(0);
                   7461:   }
1.186     brouard  7462:   else if(mle==-3) { /* Main Wizard */
1.126     brouard  7463:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  7464:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   7465:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  7466:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   7467:     matcov=matrix(1,npar,1,npar);
1.203     brouard  7468:     hess=matrix(1,npar,1,npar);
1.126     brouard  7469:   }
                   7470:   else{
1.145     brouard  7471:     /* Read guessed parameters */
1.126     brouard  7472:     /* Reads comments: lines beginning with '#' */
                   7473:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7474:       ungetc(c,ficpar);
                   7475:       fgets(line, MAXLINE, ficpar);
                   7476:       numlinepar++;
1.141     brouard  7477:       fputs(line,stdout);
1.126     brouard  7478:       fputs(line,ficparo);
                   7479:       fputs(line,ficlog);
                   7480:     }
                   7481:     ungetc(c,ficpar);
                   7482:     
                   7483:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   7484:     for(i=1; i <=nlstate; i++){
                   7485:       j=0;
                   7486:       for(jj=1; jj <=nlstate+ndeath; jj++){
                   7487:        if(jj==i) continue;
                   7488:        j++;
                   7489:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.193     brouard  7490:        if ((i1 != i) || (j1 != jj)){
1.126     brouard  7491:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
                   7492: It might be a problem of design; if ncovcol and the model are correct\n \
                   7493: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
                   7494:          exit(1);
                   7495:        }
                   7496:        fprintf(ficparo,"%1d%1d",i1,j1);
                   7497:        if(mle==1)
1.193     brouard  7498:          printf("%1d%1d",i,jj);
                   7499:        fprintf(ficlog,"%1d%1d",i,jj);
1.126     brouard  7500:        for(k=1; k<=ncovmodel;k++){
                   7501:          fscanf(ficpar," %lf",&param[i][j][k]);
                   7502:          if(mle==1){
                   7503:            printf(" %lf",param[i][j][k]);
                   7504:            fprintf(ficlog," %lf",param[i][j][k]);
                   7505:          }
                   7506:          else
                   7507:            fprintf(ficlog," %lf",param[i][j][k]);
                   7508:          fprintf(ficparo," %lf",param[i][j][k]);
                   7509:        }
                   7510:        fscanf(ficpar,"\n");
                   7511:        numlinepar++;
                   7512:        if(mle==1)
                   7513:          printf("\n");
                   7514:        fprintf(ficlog,"\n");
                   7515:        fprintf(ficparo,"\n");
                   7516:       }
                   7517:     }  
                   7518:     fflush(ficlog);
                   7519: 
1.145     brouard  7520:     /* Reads scales values */
1.126     brouard  7521:     p=param[1][1];
                   7522:     
                   7523:     /* Reads comments: lines beginning with '#' */
                   7524:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7525:       ungetc(c,ficpar);
                   7526:       fgets(line, MAXLINE, ficpar);
                   7527:       numlinepar++;
1.141     brouard  7528:       fputs(line,stdout);
1.126     brouard  7529:       fputs(line,ficparo);
                   7530:       fputs(line,ficlog);
                   7531:     }
                   7532:     ungetc(c,ficpar);
                   7533: 
                   7534:     for(i=1; i <=nlstate; i++){
                   7535:       for(j=1; j <=nlstate+ndeath-1; j++){
                   7536:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164     brouard  7537:        if ( (i1-i) * (j1-j) != 0){
1.126     brouard  7538:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   7539:          exit(1);
                   7540:        }
                   7541:        printf("%1d%1d",i,j);
                   7542:        fprintf(ficparo,"%1d%1d",i1,j1);
                   7543:        fprintf(ficlog,"%1d%1d",i1,j1);
                   7544:        for(k=1; k<=ncovmodel;k++){
                   7545:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   7546:          printf(" %le",delti3[i][j][k]);
                   7547:          fprintf(ficparo," %le",delti3[i][j][k]);
                   7548:          fprintf(ficlog," %le",delti3[i][j][k]);
                   7549:        }
                   7550:        fscanf(ficpar,"\n");
                   7551:        numlinepar++;
                   7552:        printf("\n");
                   7553:        fprintf(ficparo,"\n");
                   7554:        fprintf(ficlog,"\n");
                   7555:       }
                   7556:     }
                   7557:     fflush(ficlog);
                   7558: 
1.145     brouard  7559:     /* Reads covariance matrix */
1.126     brouard  7560:     delti=delti3[1][1];
                   7561: 
                   7562: 
                   7563:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
                   7564:   
                   7565:     /* Reads comments: lines beginning with '#' */
                   7566:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7567:       ungetc(c,ficpar);
                   7568:       fgets(line, MAXLINE, ficpar);
                   7569:       numlinepar++;
1.141     brouard  7570:       fputs(line,stdout);
1.126     brouard  7571:       fputs(line,ficparo);
                   7572:       fputs(line,ficlog);
                   7573:     }
                   7574:     ungetc(c,ficpar);
                   7575:   
                   7576:     matcov=matrix(1,npar,1,npar);
1.203     brouard  7577:     hess=matrix(1,npar,1,npar);
1.131     brouard  7578:     for(i=1; i <=npar; i++)
                   7579:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
                   7580:       
1.194     brouard  7581:     /* Scans npar lines */
1.126     brouard  7582:     for(i=1; i <=npar; i++){
1.194     brouard  7583:       count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);
                   7584:       if(count != 3){
                   7585:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
                   7586: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   7587: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
                   7588:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
                   7589: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   7590: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
                   7591:        exit(1);
                   7592:       }else
1.126     brouard  7593:       if(mle==1)
1.194     brouard  7594:        printf("%1d%1d%1d",i1,j1,jk);
                   7595:       fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);
                   7596:       fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);
1.126     brouard  7597:       for(j=1; j <=i; j++){
                   7598:        fscanf(ficpar," %le",&matcov[i][j]);
                   7599:        if(mle==1){
                   7600:          printf(" %.5le",matcov[i][j]);
                   7601:        }
                   7602:        fprintf(ficlog," %.5le",matcov[i][j]);
                   7603:        fprintf(ficparo," %.5le",matcov[i][j]);
                   7604:       }
                   7605:       fscanf(ficpar,"\n");
                   7606:       numlinepar++;
                   7607:       if(mle==1)
                   7608:        printf("\n");
                   7609:       fprintf(ficlog,"\n");
                   7610:       fprintf(ficparo,"\n");
                   7611:     }
1.194     brouard  7612:     /* End of read covariance matrix npar lines */
1.126     brouard  7613:     for(i=1; i <=npar; i++)
                   7614:       for(j=i+1;j<=npar;j++)
                   7615:        matcov[i][j]=matcov[j][i];
                   7616:     
                   7617:     if(mle==1)
                   7618:       printf("\n");
                   7619:     fprintf(ficlog,"\n");
                   7620:     
                   7621:     fflush(ficlog);
                   7622:     
                   7623:     /*-------- Rewriting parameter file ----------*/
                   7624:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   7625:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   7626:     strcat(rfileres,".");    /* */
                   7627:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   7628:     if((ficres =fopen(rfileres,"w"))==NULL) {
1.201     brouard  7629:       printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   7630:       fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
1.126     brouard  7631:     }
                   7632:     fprintf(ficres,"#%s\n",version);
                   7633:   }    /* End of mle != -3 */
                   7634: 
1.186     brouard  7635:   /*  Main data
                   7636:    */
1.126     brouard  7637:   n= lastobs;
                   7638:   num=lvector(1,n);
                   7639:   moisnais=vector(1,n);
                   7640:   annais=vector(1,n);
                   7641:   moisdc=vector(1,n);
                   7642:   andc=vector(1,n);
                   7643:   agedc=vector(1,n);
                   7644:   cod=ivector(1,n);
                   7645:   weight=vector(1,n);
                   7646:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
                   7647:   mint=matrix(1,maxwav,1,n);
                   7648:   anint=matrix(1,maxwav,1,n);
1.131     brouard  7649:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  7650:   tab=ivector(1,NCOVMAX);
1.144     brouard  7651:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  7652:   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  7653: 
1.136     brouard  7654:   /* Reads data from file datafile */
                   7655:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   7656:     goto end;
                   7657: 
                   7658:   /* Calculation of the number of parameters from char model */
1.137     brouard  7659:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
                   7660:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   7661:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   7662:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   7663:        k=1 Tvar[1]=2 (from V2)
                   7664:     */
                   7665:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   7666:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   7667:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   7668:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   7669:   */
                   7670:   /* For model-covariate k tells which data-covariate to use but
                   7671:     because this model-covariate is a construction we invent a new column
                   7672:     ncovcol + k1
                   7673:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   7674:     Tvar[3=V1*V4]=4+1 etc */
1.145     brouard  7675:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137     brouard  7676:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   7677:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
                   7678:   */
1.145     brouard  7679:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   7680:   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  7681:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   7682:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  7683:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  7684:                         4 covariates (3 plus signs)
                   7685:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   7686:                      */  
1.136     brouard  7687: 
1.186     brouard  7688: /* Main decodemodel */
                   7689: 
1.187     brouard  7690: 
1.136     brouard  7691:   if(decodemodel(model, lastobs) == 1)
                   7692:     goto end;
                   7693: 
1.137     brouard  7694:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   7695:     nbwarn++;
                   7696:     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); 
                   7697:     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); 
                   7698:   }
1.136     brouard  7699:     /*  if(mle==1){*/
1.137     brouard  7700:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   7701:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  7702:   }
                   7703: 
                   7704:     /*-calculation of age at interview from date of interview and age at death -*/
                   7705:   agev=matrix(1,maxwav,1,imx);
                   7706: 
                   7707:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   7708:     goto end;
                   7709: 
1.126     brouard  7710: 
1.136     brouard  7711:   agegomp=(int)agemin;
                   7712:   free_vector(moisnais,1,n);
                   7713:   free_vector(annais,1,n);
1.126     brouard  7714:   /* free_matrix(mint,1,maxwav,1,n);
                   7715:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  7716:   /* free_vector(moisdc,1,n); */
                   7717:   /* free_vector(andc,1,n); */
1.145     brouard  7718:   /* */
                   7719:   
1.126     brouard  7720:   wav=ivector(1,imx);
1.214     brouard  7721:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   7722:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   7723:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   7724:   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.*/
                   7725:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   7726:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  7727:    
                   7728:   /* Concatenates waves */
1.214     brouard  7729:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   7730:      Death is a valid wave (if date is known).
                   7731:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   7732:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   7733:      and mw[mi+1][i]. dh depends on stepm.
                   7734:   */
                   7735: 
1.126     brouard  7736:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.145     brouard  7737:   /* */
                   7738:  
1.215     brouard  7739:   free_vector(moisdc,1,n);
                   7740:   free_vector(andc,1,n);
                   7741: 
1.126     brouard  7742:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   7743: 
                   7744:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   7745:   ncodemax[1]=1;
1.145     brouard  7746:   Ndum =ivector(-1,NCOVMAX);  
1.187     brouard  7747:   if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */
1.145     brouard  7748:     tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.211     brouard  7749:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  7750:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  7751:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.145     brouard  7752: 
1.200     brouard  7753:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  7754:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  7755:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  7756:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   7757:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   7758:    * (currently 0 or 1) in the data.
                   7759:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   7760:    * corresponding modality (h,j).
                   7761:    */
                   7762: 
1.145     brouard  7763:   h=0;
                   7764: 
                   7765: 
                   7766:   /*if (cptcovn > 0) */
1.126     brouard  7767:       
1.145     brouard  7768:  
1.126     brouard  7769:   m=pow(2,cptcoveff);
                   7770:  
1.144     brouard  7771:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  7772:           * For k=4 covariates, h goes from 1 to m=2**k
                   7773:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   7774:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.186     brouard  7775:           *     h\k   1     2     3     4
1.143     brouard  7776:           *______________________________  
                   7777:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   7778:           *     2     2     1     1     1
                   7779:           *     3 i=2 1     2     1     1
                   7780:           *     4     2     2     1     1
                   7781:           *     5 i=3 1 i=2 1     2     1
                   7782:           *     6     2     1     2     1
                   7783:           *     7 i=4 1     2     2     1
                   7784:           *     8     2     2     2     1
1.197     brouard  7785:           *     9 i=5 1 i=3 1 i=2 1     2
                   7786:           *    10     2     1     1     2
                   7787:           *    11 i=6 1     2     1     2
                   7788:           *    12     2     2     1     2
                   7789:           *    13 i=7 1 i=4 1     2     2    
                   7790:           *    14     2     1     2     2
                   7791:           *    15 i=8 1     2     2     2
                   7792:           *    16     2     2     2     2
1.143     brouard  7793:           */
1.212     brouard  7794:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  7795:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   7796:      * and the value of each covariate?
                   7797:      * V1=1, V2=1, V3=2, V4=1 ?
                   7798:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   7799:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   7800:      * In order to get the real value in the data, we use nbcode
                   7801:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   7802:      * We are keeping this crazy system in order to be able (in the future?) 
                   7803:      * to have more than 2 values (0 or 1) for a covariate.
                   7804:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   7805:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   7806:      *              bbbbbbbb
                   7807:      *              76543210     
                   7808:      *   h-1        00000101 (6-1=5)
                   7809:      *(h-1)>>(k-1)= 00000001 >> (2-1) = 1 right shift
                   7810:      *           &
                   7811:      *     1        00000001 (1)
                   7812:      *              00000001        = 1 & ((h-1) >> (k-1))
                   7813:      *          +1= 00000010 =2 
                   7814:      *
                   7815:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   7816:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   7817:      *    >>k'            11
                   7818:      *          &   00000001
                   7819:      *            = 00000001
                   7820:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   7821:      * Reverse h=6 and m=16?
                   7822:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   7823:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   7824:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   7825:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   7826:      * V3=decodtabm(14,3,2**4)=2
                   7827:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   7828:      *(h-1) >> (j-1)    0011 =13 >> 2
                   7829:      *          &1 000000001
                   7830:      *           = 000000001
                   7831:      *         +1= 000000010 =2
                   7832:      *                  2211
                   7833:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   7834:      *                  V3=2
                   7835:      */
                   7836: 
1.202     brouard  7837:   /* /\* for(h=1; h <=100 ;h++){  *\/ */
                   7838:   /*   /\* printf("h=%2d ", h); *\/ */
                   7839:   /*    /\* for(k=1; k <=10; k++){ *\/ */
                   7840:   /*      /\* printf("k=%d %d ",k,codtabm(h,k)); *\/ */
                   7841:   /*    /\*   codtab[h][k]=codtabm(h,k); *\/ */
                   7842:   /*    /\* } *\/ */
                   7843:   /*    /\* printf("\n"); *\/ */
                   7844:   /* } */
1.197     brouard  7845:   /* for(k=1;k<=cptcoveff; k++){ /\* scans any effective covariate *\/ */
                   7846:   /*   for(i=1; i <=pow(2,cptcoveff-k);i++){ /\* i=1 to 8/1=8; i=1 to 8/2=4; i=1 to 8/8=1 *\/  */
                   7847:   /*     for(j=1; j <= ncodemax[k]; j++){ /\* For each modality of this covariate ncodemax=2*\/ */
                   7848:   /*   for(cpt=1; cpt <=pow(2,k-1); cpt++){  /\* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 *\/  */
                   7849:   /*     h++; */
                   7850:   /*     if (h>m)  */
                   7851:   /*       h=1; */
                   7852:   /*     codtab[h][k]=j; */
                   7853:   /*     /\* codtab[12][3]=1; *\/ */
                   7854:   /*     /\*codtab[h][Tvar[k]]=j;*\/ */
                   7855:   /*     /\* printf("h=%d k=%d j=%d codtab[h][k]=%d Tvar[k]=%d codtab[h][Tvar[k]]=%d \n",h, k,j,codtab[h][k],Tvar[k],codtab[h][Tvar[k]]); *\/ */
                   7856:   /*   }  */
                   7857:   /*     } */
                   7858:   /*   } */
                   7859:   /* }  */
1.126     brouard  7860:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
                   7861:      codtab[1][2]=1;codtab[2][2]=2; */
1.197     brouard  7862:   /* for(i=1; i <=m ;i++){  */
                   7863:   /*    for(k=1; k <=cptcovn; k++){ */
                   7864:   /*      printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff); */
                   7865:   /*    } */
                   7866:   /*    printf("\n"); */
                   7867:   /* } */
                   7868:   /*   scanf("%d",i);*/
1.145     brouard  7869: 
                   7870:  free_ivector(Ndum,-1,NCOVMAX);
                   7871: 
                   7872: 
1.126     brouard  7873:     
1.186     brouard  7874:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  7875:   strcpy(optionfilegnuplot,optionfilefiname);
                   7876:   if(mle==-3)
1.201     brouard  7877:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  7878:   strcat(optionfilegnuplot,".gp");
                   7879: 
                   7880:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   7881:     printf("Problem with file %s",optionfilegnuplot);
                   7882:   }
                   7883:   else{
1.204     brouard  7884:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  7885:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  7886:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   7887:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  7888:   }
                   7889:   /*  fclose(ficgp);*/
1.186     brouard  7890: 
                   7891: 
                   7892:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  7893: 
                   7894:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   7895:   if(mle==-3)
1.201     brouard  7896:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  7897:   strcat(optionfilehtm,".htm");
                   7898:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  7899:     printf("Problem with %s \n",optionfilehtm);
                   7900:     exit(0);
1.126     brouard  7901:   }
                   7902: 
                   7903:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   7904:   strcat(optionfilehtmcov,"-cov.htm");
                   7905:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   7906:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   7907:   }
                   7908:   else{
                   7909:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   7910: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  7911: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  7912:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   7913:   }
                   7914: 
1.213     brouard  7915:   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  7916: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   7917: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  7918: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  7919: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  7920: \n\
                   7921: <hr  size=\"2\" color=\"#EC5E5E\">\
                   7922:  <ul><li><h4>Parameter files</h4>\n\
                   7923:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   7924:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   7925:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   7926:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   7927:  - Date and time at start: %s</ul>\n",\
                   7928:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   7929:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   7930:          fileres,fileres,\
                   7931:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   7932:   fflush(fichtm);
                   7933: 
                   7934:   strcpy(pathr,path);
                   7935:   strcat(pathr,optionfilefiname);
1.184     brouard  7936: #ifdef WIN32
                   7937:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   7938: #else
1.126     brouard  7939:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  7940: #endif
                   7941:          
1.126     brouard  7942:   
                   7943:   /* Calculates basic frequencies. Computes observed prevalence at single age
                   7944:      and prints on file fileres'p'. */
1.214     brouard  7945:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\
                   7946:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  7947: 
                   7948:   fprintf(fichtm,"\n");
                   7949:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   7950: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   7951: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   7952:          imx,agemin,agemax,jmin,jmax,jmean);
                   7953:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7954:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7955:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7956:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7957:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
                   7958:     
                   7959:    
                   7960:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   7961:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   7962:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   7963: 
                   7964:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  7965:   /* For mortality only */
1.126     brouard  7966:   if (mle==-3){
1.136     brouard  7967:     ximort=matrix(1,NDIM,1,NDIM); 
1.186     brouard  7968:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  7969:     cens=ivector(1,n);
                   7970:     ageexmed=vector(1,n);
                   7971:     agecens=vector(1,n);
                   7972:     dcwave=ivector(1,n);
                   7973:  
                   7974:     for (i=1; i<=imx; i++){
                   7975:       dcwave[i]=-1;
                   7976:       for (m=firstpass; m<=lastpass; m++)
                   7977:        if (s[m][i]>nlstate) {
                   7978:          dcwave[i]=m;
                   7979:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   7980:          break;
                   7981:        }
                   7982:     }
                   7983: 
                   7984:     for (i=1; i<=imx; i++) {
                   7985:       if (wav[i]>0){
                   7986:        ageexmed[i]=agev[mw[1][i]][i];
                   7987:        j=wav[i];
                   7988:        agecens[i]=1.; 
                   7989: 
                   7990:        if (ageexmed[i]> 1 && wav[i] > 0){
                   7991:          agecens[i]=agev[mw[j][i]][i];
                   7992:          cens[i]= 1;
                   7993:        }else if (ageexmed[i]< 1) 
                   7994:          cens[i]= -1;
                   7995:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   7996:          cens[i]=0 ;
                   7997:       }
                   7998:       else cens[i]=-1;
                   7999:     }
                   8000:     
                   8001:     for (i=1;i<=NDIM;i++) {
                   8002:       for (j=1;j<=NDIM;j++)
                   8003:        ximort[i][j]=(i == j ? 1.0 : 0.0);
                   8004:     }
                   8005:     
1.145     brouard  8006:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  8007:     /*printf("%lf %lf", p[1], p[2]);*/
                   8008:     
                   8009:     
1.136     brouard  8010: #ifdef GSL
                   8011:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  8012: #else
1.126     brouard  8013:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  8014: #endif
1.201     brouard  8015:     strcpy(filerespow,"POW-MORT_"); 
                   8016:     strcat(filerespow,fileresu);
1.126     brouard  8017:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   8018:       printf("Problem with resultfile: %s\n", filerespow);
                   8019:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   8020:     }
1.136     brouard  8021: #ifdef GSL
                   8022:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  8023: #else
1.126     brouard  8024:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  8025: #endif
1.126     brouard  8026:     /*  for (i=1;i<=nlstate;i++)
                   8027:        for(j=1;j<=nlstate+ndeath;j++)
                   8028:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   8029:     */
                   8030:     fprintf(ficrespow,"\n");
1.136     brouard  8031: #ifdef GSL
                   8032:     /* gsl starts here */ 
                   8033:     T = gsl_multimin_fminimizer_nmsimplex;
                   8034:     gsl_multimin_fminimizer *sfm = NULL;
                   8035:     gsl_vector *ss, *x;
                   8036:     gsl_multimin_function minex_func;
                   8037: 
                   8038:     /* Initial vertex size vector */
                   8039:     ss = gsl_vector_alloc (NDIM);
                   8040:     
                   8041:     if (ss == NULL){
                   8042:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   8043:     }
                   8044:     /* Set all step sizes to 1 */
                   8045:     gsl_vector_set_all (ss, 0.001);
                   8046: 
                   8047:     /* Starting point */
1.126     brouard  8048:     
1.136     brouard  8049:     x = gsl_vector_alloc (NDIM);
                   8050:     
                   8051:     if (x == NULL){
                   8052:       gsl_vector_free(ss);
                   8053:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   8054:     }
                   8055:   
                   8056:     /* Initialize method and iterate */
                   8057:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  8058:     /*     gsl_vector_set(x, 0, 0.0268); */
                   8059:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  8060:     gsl_vector_set(x, 0, p[1]);
                   8061:     gsl_vector_set(x, 1, p[2]);
                   8062: 
                   8063:     minex_func.f = &gompertz_f;
                   8064:     minex_func.n = NDIM;
                   8065:     minex_func.params = (void *)&p; /* ??? */
                   8066:     
                   8067:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   8068:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   8069:     
                   8070:     printf("Iterations beginning .....\n\n");
                   8071:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   8072: 
                   8073:     iteri=0;
                   8074:     while (rval == GSL_CONTINUE){
                   8075:       iteri++;
                   8076:       status = gsl_multimin_fminimizer_iterate(sfm);
                   8077:       
                   8078:       if (status) printf("error: %s\n", gsl_strerror (status));
                   8079:       fflush(0);
                   8080:       
                   8081:       if (status) 
                   8082:         break;
                   8083:       
                   8084:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   8085:       ssval = gsl_multimin_fminimizer_size (sfm);
                   8086:       
                   8087:       if (rval == GSL_SUCCESS)
                   8088:         printf ("converged to a local maximum at\n");
                   8089:       
                   8090:       printf("%5d ", iteri);
                   8091:       for (it = 0; it < NDIM; it++){
                   8092:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   8093:       }
                   8094:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   8095:     }
                   8096:     
                   8097:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   8098:     
                   8099:     gsl_vector_free(x); /* initial values */
                   8100:     gsl_vector_free(ss); /* inital step size */
                   8101:     for (it=0; it<NDIM; it++){
                   8102:       p[it+1]=gsl_vector_get(sfm->x,it);
                   8103:       fprintf(ficrespow," %.12lf", p[it]);
                   8104:     }
                   8105:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   8106: #endif
                   8107: #ifdef POWELL
                   8108:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   8109: #endif  
1.126     brouard  8110:     fclose(ficrespow);
                   8111:     
1.203     brouard  8112:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  8113: 
                   8114:     for(i=1; i <=NDIM; i++)
                   8115:       for(j=i+1;j<=NDIM;j++)
                   8116:        matcov[i][j]=matcov[j][i];
                   8117:     
                   8118:     printf("\nCovariance matrix\n ");
1.203     brouard  8119:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  8120:     for(i=1; i <=NDIM; i++) {
                   8121:       for(j=1;j<=NDIM;j++){ 
                   8122:        printf("%f ",matcov[i][j]);
1.203     brouard  8123:        fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  8124:       }
1.203     brouard  8125:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  8126:     }
                   8127:     
                   8128:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  8129:     for (i=1;i<=NDIM;i++) {
1.126     brouard  8130:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  8131:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   8132:     }
1.126     brouard  8133:     lsurv=vector(1,AGESUP);
                   8134:     lpop=vector(1,AGESUP);
                   8135:     tpop=vector(1,AGESUP);
                   8136:     lsurv[agegomp]=100000;
                   8137:     
                   8138:     for (k=agegomp;k<=AGESUP;k++) {
                   8139:       agemortsup=k;
                   8140:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   8141:     }
                   8142:     
                   8143:     for (k=agegomp;k<agemortsup;k++)
                   8144:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   8145:     
                   8146:     for (k=agegomp;k<agemortsup;k++){
                   8147:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   8148:       sumlpop=sumlpop+lpop[k];
                   8149:     }
                   8150:     
                   8151:     tpop[agegomp]=sumlpop;
                   8152:     for (k=agegomp;k<(agemortsup-3);k++){
                   8153:       /*  tpop[k+1]=2;*/
                   8154:       tpop[k+1]=tpop[k]-lpop[k];
                   8155:     }
                   8156:     
                   8157:     
                   8158:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   8159:     for (k=agegomp;k<(agemortsup-2);k++) 
                   8160:       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]);
                   8161:     
                   8162:     
                   8163:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  8164:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   8165:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   8166: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   8167: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   8168:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   8169: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   8170: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   8171:     }else
1.201     brouard  8172:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
                   8173:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  8174:                     stepm, weightopt,\
                   8175:                     model,imx,p,matcov,agemortsup);
                   8176:     
                   8177:     free_vector(lsurv,1,AGESUP);
                   8178:     free_vector(lpop,1,AGESUP);
                   8179:     free_vector(tpop,1,AGESUP);
1.136     brouard  8180: #ifdef GSL
                   8181:     free_ivector(cens,1,n);
                   8182:     free_vector(agecens,1,n);
                   8183:     free_ivector(dcwave,1,n);
                   8184:     free_matrix(ximort,1,NDIM,1,NDIM);
                   8185: #endif
1.186     brouard  8186:   } /* Endof if mle==-3 mortality only */
1.205     brouard  8187:   /* Standard  */
                   8188:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   8189:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   8190:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  8191:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  8192:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   8193:     for (k=1; k<=npar;k++)
                   8194:       printf(" %d %8.5f",k,p[k]);
                   8195:     printf("\n");
1.205     brouard  8196:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   8197:       /* mlikeli uses func not funcone */
                   8198:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   8199:     }
                   8200:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   8201:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   8202:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   8203:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   8204:     }
                   8205:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  8206:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   8207:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   8208:     for (k=1; k<=npar;k++)
                   8209:       printf(" %d %8.5f",k,p[k]);
                   8210:     printf("\n");
                   8211:     
                   8212:     /*--------- results files --------------*/
1.192     brouard  8213:     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  8214:     
                   8215:     
                   8216:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   8217:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   8218:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   8219:     for(i=1,jk=1; i <=nlstate; i++){
                   8220:       for(k=1; k <=(nlstate+ndeath); k++){
                   8221:        if (k != i) {
                   8222:          printf("%d%d ",i,k);
                   8223:          fprintf(ficlog,"%d%d ",i,k);
                   8224:          fprintf(ficres,"%1d%1d ",i,k);
                   8225:          for(j=1; j <=ncovmodel; j++){
1.190     brouard  8226:            printf("%12.7f ",p[jk]);
                   8227:            fprintf(ficlog,"%12.7f ",p[jk]);
                   8228:            fprintf(ficres,"%12.7f ",p[jk]);
1.126     brouard  8229:            jk++; 
                   8230:          }
                   8231:          printf("\n");
                   8232:          fprintf(ficlog,"\n");
                   8233:          fprintf(ficres,"\n");
                   8234:        }
                   8235:       }
                   8236:     }
1.203     brouard  8237:     if(mle != 0){
                   8238:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  8239:       ftolhess=ftol; /* Usually correct */
1.203     brouard  8240:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   8241:       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");
                   8242:       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");
                   8243:       for(i=1,jk=1; i <=nlstate; i++){
                   8244:        for(k=1; k <=(nlstate+ndeath); k++){
                   8245:          if (k != i) {
                   8246:            printf("%d%d ",i,k);
                   8247:            fprintf(ficlog,"%d%d ",i,k);
                   8248:            for(j=1; j <=ncovmodel; j++){
                   8249:              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]));
                   8250:              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]));
                   8251:              jk++; 
                   8252:            }
                   8253:            printf("\n");
                   8254:            fprintf(ficlog,"\n");
1.193     brouard  8255:          }
                   8256:        }
                   8257:       }
1.203     brouard  8258:     } /* end of hesscov and Wald tests */
1.193     brouard  8259: 
1.203     brouard  8260:     /*  */
1.126     brouard  8261:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   8262:     printf("# Scales (for hessian or gradient estimation)\n");
                   8263:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   8264:     for(i=1,jk=1; i <=nlstate; i++){
                   8265:       for(j=1; j <=nlstate+ndeath; j++){
                   8266:        if (j!=i) {
                   8267:          fprintf(ficres,"%1d%1d",i,j);
                   8268:          printf("%1d%1d",i,j);
                   8269:          fprintf(ficlog,"%1d%1d",i,j);
                   8270:          for(k=1; k<=ncovmodel;k++){
                   8271:            printf(" %.5e",delti[jk]);
                   8272:            fprintf(ficlog," %.5e",delti[jk]);
                   8273:            fprintf(ficres," %.5e",delti[jk]);
                   8274:            jk++;
                   8275:          }
                   8276:          printf("\n");
                   8277:          fprintf(ficlog,"\n");
                   8278:          fprintf(ficres,"\n");
                   8279:        }
                   8280:       }
                   8281:     }
                   8282:     
                   8283:     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  8284:     if(mle >= 1) /* To big for the screen */
1.126     brouard  8285:       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");
                   8286:     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");
                   8287:     /* # 121 Var(a12)\n\ */
                   8288:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   8289:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   8290:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   8291:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   8292:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   8293:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   8294:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   8295:     
                   8296:     
                   8297:     /* Just to have a covariance matrix which will be more understandable
                   8298:        even is we still don't want to manage dictionary of variables
                   8299:     */
                   8300:     for(itimes=1;itimes<=2;itimes++){
                   8301:       jj=0;
                   8302:       for(i=1; i <=nlstate; i++){
                   8303:        for(j=1; j <=nlstate+ndeath; j++){
                   8304:          if(j==i) continue;
                   8305:          for(k=1; k<=ncovmodel;k++){
                   8306:            jj++;
                   8307:            ca[0]= k+'a'-1;ca[1]='\0';
                   8308:            if(itimes==1){
                   8309:              if(mle>=1)
                   8310:                printf("#%1d%1d%d",i,j,k);
                   8311:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   8312:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   8313:            }else{
                   8314:              if(mle>=1)
                   8315:                printf("%1d%1d%d",i,j,k);
                   8316:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   8317:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   8318:            }
                   8319:            ll=0;
                   8320:            for(li=1;li <=nlstate; li++){
                   8321:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   8322:                if(lj==li) continue;
                   8323:                for(lk=1;lk<=ncovmodel;lk++){
                   8324:                  ll++;
                   8325:                  if(ll<=jj){
                   8326:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   8327:                    if(ll<jj){
                   8328:                      if(itimes==1){
                   8329:                        if(mle>=1)
                   8330:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   8331:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   8332:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   8333:                      }else{
                   8334:                        if(mle>=1)
                   8335:                          printf(" %.5e",matcov[jj][ll]); 
                   8336:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   8337:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   8338:                      }
                   8339:                    }else{
                   8340:                      if(itimes==1){
                   8341:                        if(mle>=1)
                   8342:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   8343:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   8344:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   8345:                      }else{
                   8346:                        if(mle>=1)
1.203     brouard  8347:                          printf(" %.7e",matcov[jj][ll]); 
                   8348:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   8349:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
1.126     brouard  8350:                      }
                   8351:                    }
                   8352:                  }
                   8353:                } /* end lk */
                   8354:              } /* end lj */
                   8355:            } /* end li */
                   8356:            if(mle>=1)
                   8357:              printf("\n");
                   8358:            fprintf(ficlog,"\n");
                   8359:            fprintf(ficres,"\n");
                   8360:            numlinepar++;
                   8361:          } /* end k*/
                   8362:        } /*end j */
                   8363:       } /* end i */
                   8364:     } /* end itimes */
                   8365:     
                   8366:     fflush(ficlog);
                   8367:     fflush(ficres);
1.209     brouard  8368:       while(fgets(line, MAXLINE, ficpar)) {
                   8369:     /* If line starts with a # it is a comment */
                   8370:     if (line[0] == '#') {
                   8371:       numlinepar++;
1.141     brouard  8372:       fputs(line,stdout);
1.126     brouard  8373:       fputs(line,ficparo);
1.209     brouard  8374:       fputs(line,ficlog);
                   8375:       continue;
                   8376:     }else
                   8377:       break;
                   8378:   }
                   8379: 
                   8380:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   8381:     /*   ungetc(c,ficpar); */
                   8382:     /*   fgets(line, MAXLINE, ficpar); */
                   8383:     /*   fputs(line,stdout); */
                   8384:     /*   fputs(line,ficparo); */
                   8385:     /* } */
                   8386:     /* ungetc(c,ficpar); */
1.126     brouard  8387:     
                   8388:     estepm=0;
1.209     brouard  8389:     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){
                   8390: 
                   8391:     if (num_filled != 6) {
                   8392:       printf("Not 6 parameters in line, for example:agemin=60 agemax=95 bage=55 fage=95 estepm=24 ftolpl=6e-4\n");
                   8393:       printf("but line=%s\n",line);
                   8394:       goto end;
                   8395:     }
                   8396:     printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   8397:   }
                   8398:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   8399:   /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   8400: 
                   8401:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  8402:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   8403:     if (fage <= 2) {
                   8404:       bage = ageminpar;
                   8405:       fage = agemaxpar;
                   8406:     }
                   8407:     
                   8408:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  8409:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   8410:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.186     brouard  8411: 
                   8412:     /* Other stuffs, more or less useful */    
1.126     brouard  8413:     while((c=getc(ficpar))=='#' && c!= EOF){
                   8414:       ungetc(c,ficpar);
                   8415:       fgets(line, MAXLINE, ficpar);
1.141     brouard  8416:       fputs(line,stdout);
1.126     brouard  8417:       fputs(line,ficparo);
                   8418:     }
                   8419:     ungetc(c,ficpar);
                   8420:     
                   8421:     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);
                   8422:     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);
                   8423:     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);
                   8424:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   8425:     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);
                   8426:     
                   8427:     while((c=getc(ficpar))=='#' && c!= EOF){
                   8428:       ungetc(c,ficpar);
                   8429:       fgets(line, MAXLINE, ficpar);
1.141     brouard  8430:       fputs(line,stdout);
1.126     brouard  8431:       fputs(line,ficparo);
                   8432:     }
                   8433:     ungetc(c,ficpar);
                   8434:     
                   8435:     
                   8436:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   8437:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   8438:     
                   8439:     fscanf(ficpar,"pop_based=%d\n",&popbased);
1.193     brouard  8440:     fprintf(ficlog,"pop_based=%d\n",popbased);
1.126     brouard  8441:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   8442:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   8443:     
                   8444:     while((c=getc(ficpar))=='#' && c!= EOF){
                   8445:       ungetc(c,ficpar);
                   8446:       fgets(line, MAXLINE, ficpar);
1.141     brouard  8447:       fputs(line,stdout);
1.126     brouard  8448:       fputs(line,ficparo);
                   8449:     }
                   8450:     ungetc(c,ficpar);
                   8451:     
                   8452:     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);
                   8453:     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);
                   8454:     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);
                   8455:     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);
                   8456:     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);
                   8457:     /* day and month of proj2 are not used but only year anproj2.*/
                   8458:     
                   8459:     
                   8460:     
1.145     brouard  8461:      /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
                   8462:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  8463:     
                   8464:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  8465:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
                   8466:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   8467: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   8468: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   8469:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   8470: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   8471: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   8472:     }else
1.211     brouard  8473:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, pathc,p);
1.126     brouard  8474:     
1.201     brouard  8475:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt,\
1.211     brouard  8476:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,prevfcast,estepm, \
1.213     brouard  8477:                 jprev1,mprev1,anprev1,dateprev1,jprev2,mprev2,anprev2,dateprev2);
1.126     brouard  8478:       
                   8479:    /*------------ free_vector  -------------*/
                   8480:    /*  chdir(path); */
                   8481:  
1.215     brouard  8482:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   8483:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   8484:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   8485:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.126     brouard  8486:     free_lvector(num,1,n);
                   8487:     free_vector(agedc,1,n);
                   8488:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   8489:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   8490:     fclose(ficparo);
                   8491:     fclose(ficres);
                   8492: 
                   8493: 
1.186     brouard  8494:     /* Other results (useful)*/
                   8495: 
                   8496: 
1.126     brouard  8497:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  8498:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   8499:     prlim=matrix(1,nlstate,1,nlstate);
1.209     brouard  8500:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  8501:     fclose(ficrespl);
                   8502: 
1.145     brouard  8503: #ifdef FREEEXIT2
                   8504: #include "freeexit2.h"
                   8505: #endif
                   8506: 
1.126     brouard  8507:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  8508:     /*#include "hpijx.h"*/
                   8509:     hPijx(p, bage, fage);
1.145     brouard  8510:     fclose(ficrespij);
1.126     brouard  8511: 
1.145     brouard  8512:   /*-------------- Variance of one-step probabilities---*/
                   8513:     k=1;
1.126     brouard  8514:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
                   8515: 
                   8516: 
                   8517:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   8518:     for(i=1;i<=AGESUP;i++)
                   8519:       for(j=1;j<=NCOVMAX;j++)
                   8520:        for(k=1;k<=NCOVMAX;k++)
                   8521:          probs[i][j][k]=0.;
                   8522: 
                   8523:     /*---------- Forecasting ------------------*/
                   8524:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   8525:     if(prevfcast==1){
                   8526:       /*    if(stepm ==1){*/
1.201     brouard  8527:       prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
1.126     brouard  8528:       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
                   8529:       /*      }  */
                   8530:       /*      else{ */
                   8531:       /*        erreur=108; */
                   8532:       /*        printf("Warning %d!! You can only forecast the prevalences if the optimization\n  has been performed with stepm = 1 (month) instead of %d or model=. instead of '%s'\n", erreur, stepm, model); */
                   8533:       /*        fprintf(ficlog,"Warning %d!! You can only forecast the prevalences if the optimization\n  has been performed with stepm = 1 (month) instead of %d or model=. instead of '%s'\n", erreur, stepm, model); */
                   8534:       /*      } */
                   8535:     }
1.186     brouard  8536:  
                   8537:     /* ------ Other prevalence ratios------------ */
1.126     brouard  8538: 
1.127     brouard  8539:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
                   8540: 
                   8541:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   8542:     /*  printf("ageminpar=%f, agemax=%f, s[lastpass][imx]=%d, agev[lastpass][imx]=%f, nlstate=%d, imx=%d,  mint[lastpass][imx]=%f, anint[lastpass][imx]=%f,dateprev1=%f, dateprev2=%f, firstpass=%d, lastpass=%d\n",\
                   8543:        ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
                   8544:     */
1.215     brouard  8545:     free_ivector(wav,1,imx);
                   8546:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   8547:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   8548:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
                   8549: 
1.126     brouard  8550: 
1.127     brouard  8551:     if (mobilav!=0) {
                   8552:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   8553:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   8554:        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   8555:        printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   8556:       }
1.126     brouard  8557:     }
                   8558: 
                   8559: 
1.127     brouard  8560:     /*---------- Health expectancies, no variances ------------*/
                   8561: 
1.201     brouard  8562:     strcpy(filerese,"E_");
                   8563:     strcat(filerese,fileresu);
1.126     brouard  8564:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   8565:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   8566:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   8567:     }
1.208     brouard  8568:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   8569:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.145     brouard  8570:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   8571:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   8572:           
                   8573:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127     brouard  8574:        fprintf(ficreseij,"\n#****** ");
                   8575:        for(j=1;j<=cptcoveff;j++) {
1.200     brouard  8576:          fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.127     brouard  8577:        }
                   8578:        fprintf(ficreseij,"******\n");
                   8579: 
                   8580:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   8581:        oldm=oldms;savm=savms;
                   8582:        evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
                   8583:       
                   8584:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145     brouard  8585:       /*}*/
1.127     brouard  8586:     }
                   8587:     fclose(ficreseij);
1.208     brouard  8588:     printf("done evsij\n");fflush(stdout);
                   8589:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.127     brouard  8590: 
                   8591:     /*---------- Health expectancies and variances ------------*/
                   8592: 
                   8593: 
1.201     brouard  8594:     strcpy(filerest,"T_");
                   8595:     strcat(filerest,fileresu);
1.127     brouard  8596:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   8597:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   8598:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   8599:     }
1.208     brouard  8600:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   8601:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.127     brouard  8602: 
1.126     brouard  8603: 
1.201     brouard  8604:     strcpy(fileresstde,"STDE_");
                   8605:     strcat(fileresstde,fileresu);
1.126     brouard  8606:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
                   8607:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   8608:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   8609:     }
1.208     brouard  8610:     printf("  Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   8611:     fprintf(ficlog,"  Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  8612: 
1.201     brouard  8613:     strcpy(filerescve,"CVE_");
                   8614:     strcat(filerescve,fileresu);
1.126     brouard  8615:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
                   8616:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   8617:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   8618:     }
1.208     brouard  8619:     printf("    Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   8620:     fprintf(ficlog,"    Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  8621: 
1.201     brouard  8622:     strcpy(fileresv,"V_");
                   8623:     strcat(fileresv,fileresu);
1.126     brouard  8624:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   8625:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   8626:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   8627:     }
1.208     brouard  8628:     printf("      Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(stdout);
                   8629:     fprintf(ficlog,"      Computing Variance-covariance of DFLEs: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  8630: 
1.145     brouard  8631:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   8632:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   8633:           
                   8634:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.208     brouard  8635:       fprintf(ficrest,"\n#****** ");
                   8636:       for(j=1;j<=cptcoveff;j++) 
                   8637:        fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8638:       fprintf(ficrest,"******\n");
                   8639:       
                   8640:       fprintf(ficresstdeij,"\n#****** ");
                   8641:       fprintf(ficrescveij,"\n#****** ");
                   8642:       for(j=1;j<=cptcoveff;j++) {
                   8643:        fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8644:        fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8645:       }
                   8646:       fprintf(ficresstdeij,"******\n");
                   8647:       fprintf(ficrescveij,"******\n");
                   8648:       
                   8649:       fprintf(ficresvij,"\n#****** ");
                   8650:       for(j=1;j<=cptcoveff;j++) 
                   8651:        fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8652:       fprintf(ficresvij,"******\n");
                   8653:       
                   8654:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   8655:       oldm=oldms;savm=savms;
                   8656:       printf(" cvevsij %d, ",k);
                   8657:       fprintf(ficlog, " cvevsij %d, ",k);
                   8658:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);
                   8659:       printf(" end cvevsij \n ");
                   8660:       fprintf(ficlog, " end cvevsij \n ");
                   8661:       
                   8662:       /*
                   8663:        */
                   8664:       /* goto endfree; */
                   8665:       
                   8666:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   8667:       pstamp(ficrest);
                   8668:       
                   8669:       
                   8670:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
                   8671:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   8672:        cptcod= 0; /* To be deleted */
                   8673:        printf("varevsij %d \n",vpopbased);
                   8674:        fprintf(ficlog, "varevsij %d \n",vpopbased);
1.209     brouard  8675:        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 */
1.208     brouard  8676:        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 ");
                   8677:        if(vpopbased==1)
                   8678:          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);
                   8679:        else
                   8680:          fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
                   8681:        fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
                   8682:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   8683:        fprintf(ficrest,"\n");
                   8684:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
                   8685:        epj=vector(1,nlstate+1);
                   8686:        printf("Computing age specific period (stable) prevalences in each health state \n");
                   8687:        fprintf(ficlog,"Computing age specific period (stable) prevalences in each health state \n");
                   8688:        for(age=bage; age <=fage ;age++){
1.209     brouard  8689:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k); /*ZZ Is it the correct prevalim */
1.208     brouard  8690:          if (vpopbased==1) {
                   8691:            if(mobilav ==0){
                   8692:              for(i=1; i<=nlstate;i++)
                   8693:                prlim[i][i]=probs[(int)age][i][k];
                   8694:            }else{ /* mobilav */ 
                   8695:              for(i=1; i<=nlstate;i++)
                   8696:                prlim[i][i]=mobaverage[(int)age][i][k];
1.126     brouard  8697:            }
1.208     brouard  8698:          }
                   8699:          
                   8700:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   8701:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   8702:          /* printf(" age %4.0f ",age); */
                   8703:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   8704:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   8705:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   8706:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   8707:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
1.126     brouard  8708:            }
1.208     brouard  8709:            epj[nlstate+1] +=epj[j];
                   8710:          }
                   8711:          /* printf(" age %4.0f \n",age); */
                   8712:          
                   8713:          for(i=1, vepp=0.;i <=nlstate;i++)
                   8714:            for(j=1;j <=nlstate;j++)
                   8715:              vepp += vareij[i][j][(int)age];
                   8716:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   8717:          for(j=1;j <=nlstate;j++){
                   8718:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
1.126     brouard  8719:          }
1.208     brouard  8720:          fprintf(ficrest,"\n");
1.126     brouard  8721:        }
1.208     brouard  8722:       } /* End vpopbased */
                   8723:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   8724:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   8725:       free_vector(epj,1,nlstate+1);
                   8726:       printf("done \n");fflush(stdout);
                   8727:       fprintf(ficlog,"done\n");fflush(ficlog);
                   8728:       
1.145     brouard  8729:       /*}*/
1.208     brouard  8730:     } /* End k */
1.126     brouard  8731:     free_vector(weight,1,n);
1.145     brouard  8732:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126     brouard  8733:     free_imatrix(s,1,maxwav+1,1,n);
                   8734:     free_matrix(anint,1,maxwav,1,n); 
                   8735:     free_matrix(mint,1,maxwav,1,n);
                   8736:     free_ivector(cod,1,n);
                   8737:     free_ivector(tab,1,NCOVMAX);
                   8738:     fclose(ficresstdeij);
                   8739:     fclose(ficrescveij);
                   8740:     fclose(ficresvij);
                   8741:     fclose(ficrest);
1.208     brouard  8742:     printf("done Health expectancies\n");fflush(stdout);
                   8743:     fprintf(ficlog,"done Health expectancies\n");fflush(ficlog);
1.126     brouard  8744:     fclose(ficpar);
                   8745:   
                   8746:     /*------- Variance of period (stable) prevalence------*/   
                   8747: 
1.201     brouard  8748:     strcpy(fileresvpl,"VPL_");
                   8749:     strcat(fileresvpl,fileresu);
1.126     brouard  8750:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   8751:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   8752:       exit(0);
                   8753:     }
1.208     brouard  8754:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   8755:     fprintf(ficlog, "Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.126     brouard  8756: 
1.145     brouard  8757:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   8758:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   8759:           
                   8760:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   8761:        fprintf(ficresvpl,"\n#****** ");
1.126     brouard  8762:        for(j=1;j<=cptcoveff;j++) 
1.200     brouard  8763:          fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  8764:        fprintf(ficresvpl,"******\n");
                   8765:       
                   8766:        varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   8767:        oldm=oldms;savm=savms;
1.209     brouard  8768:        varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, strstart);
1.126     brouard  8769:        free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145     brouard  8770:       /*}*/
1.126     brouard  8771:     }
                   8772: 
                   8773:     fclose(ficresvpl);
1.208     brouard  8774:     printf("done variance-covariance of period prevalence\n");fflush(stdout);
                   8775:     fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
1.126     brouard  8776: 
                   8777:     /*---------- End : free ----------------*/
                   8778:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   8779:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   8780:   }  /* mle==-3 arrives here for freeing */
1.164     brouard  8781:  /* endfree:*/
1.141     brouard  8782:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126     brouard  8783:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
                   8784:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   8785:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   8786:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   8787:     free_matrix(covar,0,NCOVMAX,1,n);
                   8788:     free_matrix(matcov,1,npar,1,npar);
1.203     brouard  8789:     free_matrix(hess,1,npar,1,npar);
1.126     brouard  8790:     /*free_vector(delti,1,npar);*/
                   8791:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   8792:     free_matrix(agev,1,maxwav,1,imx);
                   8793:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   8794: 
1.145     brouard  8795:     free_ivector(ncodemax,1,NCOVMAX);
1.192     brouard  8796:     free_ivector(ncodemaxwundef,1,NCOVMAX);
1.145     brouard  8797:     free_ivector(Tvar,1,NCOVMAX);
                   8798:     free_ivector(Tprod,1,NCOVMAX);
                   8799:     free_ivector(Tvaraff,1,NCOVMAX);
                   8800:     free_ivector(Tage,1,NCOVMAX);
1.126     brouard  8801: 
                   8802:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
1.200     brouard  8803:     /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  8804:   fflush(fichtm);
                   8805:   fflush(ficgp);
                   8806:   
                   8807: 
                   8808:   if((nberr >0) || (nbwarn>0)){
1.216   ! brouard  8809:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
        !          8810:     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  8811:   }else{
                   8812:     printf("End of Imach\n");
                   8813:     fprintf(ficlog,"End of Imach\n");
                   8814:   }
                   8815:   printf("See log file on %s\n",filelog);
                   8816:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  8817:   /*(void) gettimeofday(&end_time,&tzp);*/
                   8818:   rend_time = time(NULL);  
                   8819:   end_time = *localtime(&rend_time);
                   8820:   /* tml = *localtime(&end_time.tm_sec); */
                   8821:   strcpy(strtend,asctime(&end_time));
1.126     brouard  8822:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   8823:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  8824:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126     brouard  8825: 
1.157     brouard  8826:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   8827:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   8828:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  8829:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   8830: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   8831:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   8832:   fclose(fichtm);
                   8833:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   8834:   fclose(fichtmcov);
                   8835:   fclose(ficgp);
                   8836:   fclose(ficlog);
                   8837:   /*------ End -----------*/
                   8838: 
                   8839: 
                   8840:    printf("Before Current directory %s!\n",pathcd);
1.184     brouard  8841: #ifdef WIN32
                   8842:    if (_chdir(pathcd) != 0)
                   8843:           printf("Can't move to directory %s!\n",path);
                   8844:    if(_getcwd(pathcd,MAXLINE) > 0)
                   8845: #else
1.126     brouard  8846:    if(chdir(pathcd) != 0)
1.184     brouard  8847:           printf("Can't move to directory %s!\n", path);
                   8848:    if (getcwd(pathcd, MAXLINE) > 0)
                   8849: #endif 
1.126     brouard  8850:     printf("Current directory %s!\n",pathcd);
                   8851:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   8852:   sprintf(plotcmd,"gnuplot");
1.157     brouard  8853: #ifdef _WIN32
1.126     brouard  8854:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   8855: #endif
                   8856:   if(!stat(plotcmd,&info)){
1.158     brouard  8857:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  8858:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  8859:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  8860:     }else
                   8861:       strcpy(pplotcmd,plotcmd);
1.157     brouard  8862: #ifdef __unix
1.126     brouard  8863:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   8864:     if(!stat(plotcmd,&info)){
1.158     brouard  8865:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  8866:     }else
                   8867:       strcpy(pplotcmd,plotcmd);
                   8868: #endif
                   8869:   }else
                   8870:     strcpy(pplotcmd,plotcmd);
                   8871:   
                   8872:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  8873:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  8874: 
                   8875:   if((outcmd=system(plotcmd)) != 0){
1.158     brouard  8876:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  8877:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  8878:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150     brouard  8879:     if((outcmd=system(plotcmd)) != 0)
1.153     brouard  8880:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126     brouard  8881:   }
1.158     brouard  8882:   printf(" Successful, please wait...");
1.126     brouard  8883:   while (z[0] != 'q') {
                   8884:     /* chdir(path); */
1.154     brouard  8885:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  8886:     scanf("%s",z);
                   8887: /*     if (z[0] == 'c') system("./imach"); */
                   8888:     if (z[0] == 'e') {
1.158     brouard  8889: #ifdef __APPLE__
1.152     brouard  8890:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  8891: #elif __linux
                   8892:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  8893: #else
1.152     brouard  8894:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  8895: #endif
                   8896:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   8897:       system(pplotcmd);
1.126     brouard  8898:     }
                   8899:     else if (z[0] == 'g') system(plotcmd);
                   8900:     else if (z[0] == 'q') exit(0);
                   8901:   }
                   8902:   end:
                   8903:   while (z[0] != 'q') {
1.195     brouard  8904:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  8905:     scanf("%s",z);
                   8906:   }
                   8907: }

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